#include "openssl/sms4.h" #include #define GETCH() getchar() #define PUTCH(ch) int SM4_ECB(int Flag, unsigned char* Key, unsigned char* In, unsigned char* Out, unsigned int Len); int AddPadding(unsigned char* In, int inLen, unsigned char* Out, int* outLen); /* sm4 ecb模式加密/解密 Flag 运算标志,0为加密,1为解密。 Key sm4算法密钥。 In sm4算法ecb运算输入数据。 Out sm4算法ecb计算得到密文。 Len ecb明文/密文长度。 */ int SM4_ECB(int Flag, unsigned char* Key, unsigned char* In, unsigned char* Out, unsigned int Len) { int i; int Ret; int PadLen; unsigned char Pad[256];//可以根据实际情况malloc需要的空间 sms4_key_t key; if (!Flag) { memset(Pad, 0, sizeof(Pad)); Ret = AddPadding(In, Len, Pad, &PadLen);//检查是否是16倍数,不是补全 if (Ret < 0) { return -2; } sms4_set_encrypt_key(&key, Key); for (i = 0; i < PadLen / 16; i++) { sms4_encrypt(Pad + i * 16, Out + i * 16, &key); } } else { sms4_set_decrypt_key(&key, Key); for (i = 0; i < Len / 16; i++) { sms4_encrypt(In + i * 16, Out + i * 16, &key); } } return 0; } int AddPadding(unsigned char* In, int inLen, unsigned char* Out, int* outLen) { int PaddingLen = -1; char tmpPadding[16]; if (inLen <= 0) { return -1; } *outLen = 0; PaddingLen = 16 - (inLen % 16 == 0 ? 16 : inLen % 16); if (PaddingLen == 0) { memcpy(Out, In, inLen); *outLen = inLen; return 1; } memset(tmpPadding, 0, 16); memset(tmpPadding, PaddingLen, PaddingLen); memcpy(Out, In, inLen); *outLen += inLen; memcpy(Out + *outLen, tmpPadding, PaddingLen); *outLen += PaddingLen; return 0; } int main() { int rv; int flag = 0; unsigned char pbKeyValue[16] = { 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10 }; unsigned char pbPlainText[16] = { 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10 }; unsigned char pbCipherText[16] = { 0x68,0x1e,0xdf,0x34,0xd2,0x06,0x96,0x5e,0x86,0xb3,0xe9,0x4f,0x53,0x6e,0x42,0x46 }; unsigned char pbDataOut[16] = { 0 }; unsigned int len = sizeof(pbPlainText); //flag=0,调用加密方法,将加密结果取出与标准加密结果对比 rv = SM4_ECB(flag, pbKeyValue, pbPlainText, pbDataOut, len); if (len != sizeof(pbCipherText) || memcmp(pbDataOut, pbCipherText, len) != 0) { printf("\n"); printf("sm4-ecb encrypt is error!\n"); printf("\n按任意键继续..."); GETCH(); } else { printf("\n"); printf("sm4-ecb encrypt is ok!\n"); printf("\n按任意键继续..."); GETCH(); } } |