90 lines
2.3 KiB
C++
Raw Normal View History

2017-09-18 06:34:03 -05:00
#include "aes.h"
#include <stdio.h>
#include <stdlib.h>
2018-07-21 02:06:15 -05:00
#include <assert.h>
2017-09-18 06:34:03 -05:00
#if defined(AES256) && (AES256 == 1)
#define AES_KEYSIZE 256
#elif defined(AES192) && (AES192 == 1)
#define AES_KEYSIZE 192
#else
#define AES_KEYSIZE 128
#endif
void AES_ECB_encrypt(const uint8_t* input, const uint8_t* key, uint8_t *output, const uint32_t length)
{
printf("AES_ECB_encrypt not implemented\n");
exit(-1);
}
void AES_ECB_decrypt(const uint8_t* input, const uint8_t* key, uint8_t *output, const uint32_t length)
{
printf("AES_ECB_encrypt not implemented\n");
exit(-1);
}
void AES_CBC_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)
{
2017-09-18 07:10:24 -05:00
static aes_context ctx;
2018-07-21 02:06:15 -05:00
char tmp_iv[16];
if(key!=0)
2017-09-18 07:10:24 -05:00
{
aes_init( &ctx);
2018-07-21 02:06:15 -05:00
aes_setkey_enc(&ctx,key,AES_KEYSIZE);
2017-09-18 07:10:24 -05:00
}
2017-09-18 06:34:03 -05:00
memcpy(tmp_iv,iv,16);
2018-07-21 02:06:15 -05:00
int ret=aes_crypt_cbc( &ctx, AES_ENCRYPT, length, (unsigned char* )tmp_iv, (const unsigned char*)input,(unsigned char*) output );
assert(ret==0);
2017-09-18 06:34:03 -05:00
return ;
}
void AES_CBC_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)
{
2017-09-18 07:10:24 -05:00
static aes_context ctx;
2018-07-21 02:06:15 -05:00
char tmp_iv[16];
if(key!=0)
{
aes_init( &ctx);
aes_setkey_dec(&ctx,key,AES_KEYSIZE);
}
memcpy(tmp_iv,iv,16);
int ret=aes_crypt_cbc( &ctx,AES_DECRYPT, length, (unsigned char*)tmp_iv, (const unsigned char*)input, (unsigned char*) output );
assert(ret==0);
}
void AES_CFB_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)
{
static aes_context ctx;
char tmp_iv[16];
if(key!=0)
2017-09-18 07:10:24 -05:00
{
aes_init( &ctx);
2018-07-21 02:06:15 -05:00
aes_setkey_enc(&ctx,key,AES_KEYSIZE);
2017-09-18 07:10:24 -05:00
}
2018-07-21 02:06:15 -05:00
memcpy(tmp_iv,iv,16);
size_t offset=0;
int ret=aes_crypt_cfb128( &ctx, AES_ENCRYPT, length,&offset, (unsigned char* )tmp_iv, (const unsigned char*)input,(unsigned char*) output );
assert(ret==0);
return ;
}
void AES_CFB_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)
{
static aes_context ctx;
2017-09-18 07:31:49 -05:00
2017-09-18 06:34:03 -05:00
char tmp_iv[16];
2018-07-21 02:06:15 -05:00
if(key!=0)
{
aes_init( &ctx);
aes_setkey_enc(&ctx,key,AES_KEYSIZE);// its aes_setkey_enc again, no typo
}
2017-09-18 06:34:03 -05:00
memcpy(tmp_iv,iv,16);
2018-07-21 02:06:15 -05:00
size_t offset=0;
int ret=aes_crypt_cfb128( &ctx,AES_DECRYPT, length,&offset, (unsigned char*)tmp_iv, (const unsigned char*)input, (unsigned char*) output );
assert(ret==0);
2017-09-18 06:34:03 -05:00
return;
}
2018-07-21 02:06:15 -05:00