static int my_aes_create_key(const char *key, int key_length, uint8 *rkey)
{
uint8 *rkey_end= rkey + AES_KEY_LENGTH / 8;
uint8 *ptr;
const char *sptr;
const char *key_end= key + key_length;
memset(rkey, 0, AES_KEY_LENGTH / 8);
for (ptr= rkey, sptr= key; sptr < key_end; ptr ++, sptr ++)
{
if (ptr == rkey_end)
ptr= rkey;
*ptr ^= (uint8) *sptr;
}
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,unsigned char *ciphertext)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
my_aes_create_key(key,20,rkey);
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 128 bit AES (i.e. a 128 bit key).
*/
if(1 != EVP_EncryptInit(ctx, EVP_aes_128_ecb(),(const unsigned char *)rkey,NULL))
handleErrors();
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, (unsigned const char *)plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
/* Finalise the encryption. Further ciphertext bytes may be written at
* * * this stage.
* * */
if(1 != EVP_EncryptFinal(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
my_aes_create_key(key,20,rkey);
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* Initialise the decryption operation. IMPORTANT - ensure you use a key
* size appropriate for your cipher
* In this example we are using 128 bit AES (i.e. a 128 bit key). The
*/
if(1 != EVP_DecryptInit(ctx, EVP_aes_128_ecb(),rkey,NULL))
handleErrors();
/* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary
*
*/
if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
/* Finalise the decryption. Further plaintext bytes may be written at
* * * this stage.
* * */
if(1 != EVP_DecryptFinal(ctx, plaintext + len, &len)) handleErrors();
plaintext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}