本帖最后由 一路向北lm 于 2024-7-21 17:40 编辑
加解密算法具体如下:
/*******************************************************************************
* Function Name: encrypt_message_cfb
********************************************************************************
* Summary: Function used to encrypt the message through ctr mode.
*
* Parameters:
* char * message - pointer to the message to be encrypted
* uint8_t size - size of message to be encrypted.
*
* Return:
* void
*
*******************************************************************************/
void encrypt_message_ctr(uint8_t* message, uint8_t size)
{
uint32_t srcOffset;
cy_stc_cryptolite_aes_state_t aes_state;
cy_stc_cryptolite_aes_buffers_t aesBuffers;
uint8_t aes_block_count = 0;
cy_en_cryptolite_status_t res;
void* result;
aes_block_count = (size % AES128_ENCRYPTION_LENGTH == 0) ?
(size / AES128_ENCRYPTION_LENGTH)
: (1 + size / AES128_ENCRYPTION_LENGTH);
/* Initializes the AES operation by setting key and key length */
res = Cy_Cryptolite_Aes_Init(CRYPTOLITE, aes_key, &aes_state, &aesBuffers);
if(res!=CY_CRYPTOLITE_SUCCESS)
{
CY_ASSERT(0);
}
srcOffset = 0;
result = memcpy(AesCtrIV_copied, AesCtrIV, sizeof(AesCtrIV));
res = Cy_Cryptolite_Aes_Ctr( CRYPTOLITE,
aes_block_count * AES128_ENCRYPTION_LENGTH,
&srcOffset,
AesCtrIV_copied,
encrypted_msg,
message,
&aes_state);
if(res!=CY_CRYPTOLITE_SUCCESS)
{
CY_ASSERT(0);
}
res = Cy_Cryptolite_Aes_Free(CRYPTOLITE,&aes_state);
if(res!=CY_CRYPTOLITE_SUCCESS)
{
CY_ASSERT(0);
}
}
/*******************************************************************************
* Function Name: decrypt_message
********************************************************************************
* Summary: Function used to decrypt the message for ctr mode.
*
* Parameters:
* char * message - pointer to the message to be decrypted
* uint8_t size - size of message to be decrypted.
*
* Return:
* void
*
*******************************************************************************/
void decrypt_message_ctr(uint8_t* message, uint8_t size)
{
uint32_t srcOffset;
cy_stc_cryptolite_aes_state_t aes_state;
cy_stc_cryptolite_aes_buffers_t aesBuffers;
uint8_t aes_block_count = 0;
cy_en_cryptolite_status_t res;
void* result;
aes_block_count = (size % AES128_ENCRYPTION_LENGTH == 0) ?
(size / AES128_ENCRYPTION_LENGTH)
: (1 + size / AES128_ENCRYPTION_LENGTH);
/* Initializes the AES operation by setting key and key length */
res = Cy_Cryptolite_Aes_Init(CRYPTOLITE, aes_key, &aes_state, &aesBuffers);
if(res!=CY_CRYPTOLITE_SUCCESS)
{
CY_ASSERT(0);
}
srcOffset = 0;
/* Start decryption operation*/
result = memcpy(AesCtrIV_copied, AesCtrIV, sizeof(AesCtrIV));
res = Cy_Cryptolite_Aes_Ctr( CRYPTOLITE,
aes_block_count * AES128_ENCRYPTION_LENGTH,
&srcOffset,
AesCtrIV_copied,
decrypted_msg,
encrypted_msg,
&aes_state);
if(res!=CY_CRYPTOLITE_SUCCESS)
{
CY_ASSERT(0);
}
res = Cy_Cryptolite_Aes_Free(CRYPTOLITE,&aes_state);
if(res!=CY_CRYPTOLITE_SUCCESS)
{
CY_ASSERT(0);
}
decrypted_msg[size]='\0';
}
|