结构体值传递问题
这两天一直出现结构体成员值无法通过函数传递问题,由于项目需求,才刚开始写C,写的质量实在是太差劲了,最后也是成功解决了这个小问题。
结构体中包括明文、密文、IV、密钥等结构。在函数中调用SM加密算法,将值传递给结构体指针变量。
下面来看看(批评) 我的代码,
c
typedef struct
{
uint32_t messageCmd;
uint32_t keyidx;
uint8_t keylen;
uint32_t algID;
uint8_t pucIV[16];
uint32_t uiDataLength;
uint8_t * plaintext;
uint32_t uiEncDataLength;
BYTE * ciphertext;
} MSG_struct;
在函数中调用SM4_Encrypt
c
int dataFrame_decode(Prot_struct *port_recv_struct)
{
SM4_Encrypt((unsigned char *)test_data_key, plaintexxt, port_recv_struct->msg_struct.ciphertext, RNG_BUF_SIZE, 0, ALGMOD_ECB);
unsigned char expected_cipher[16] = {
0x0B, 0x6F, 0x8D, 0x59,
0xBB, 0x72, 0x9C, 0x0D,
0x0B, 0x73, 0xE6, 0xD9,
0xCB, 0xCF, 0x3D, 0x2D
};
unsigned char test_data[16]={0};
memcpy(test_data,encdata,16);
int reslt = memcmp(encdata, expected_cipher, 16);
return 0;
}
main.c代码
c
MSG_struct msg = {
.messageCmd = cmd_SYM_Encrypt,
.keyidx = 0x0,
.keylen = 16,
.algID = SGD_SM4_ECB,
.pucIV = {0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
.uiDataLength = 16,
.plaintext = (uint8_t *)data,
.uiEncDataLength = 16,
.ciphertext = NULL
};
Prot_struct p_s1 = {0};
p_s1.msg_head_struct = head;
p_s1.msg_struct = msg;
p_s1.msg_struct.ciphertext = (BYTE *)malloc(16);
dataFrame_decode(&p_s1);
通过内存查看指针值port_recv_struct->msg_struct.ciphertext

通过内存查看指针值p_s1>msg_struct.ciphertext

SM4加密测试用例数据
- 明文:0x31323334353637383930313233343536
- 密钥:0xA9087EB16C246ED3BE8DAAE737D672ED
- 加密模式:ECB
- IV:0或者NULL
- 密文:0x0B6F8D59BB729C0D0B73E6D9CBCF3D2D