Created
September 23, 2022 18:17
-
-
Save kakopappa/fd214fdc1493d12c02d2d7e6149908c8 to your computer and use it in GitHub Desktop.
aes_big_cbc-256
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String encrypt(String plain_data){ | |
int i; | |
// PKCS#7 Padding (Encryption), Block Size : 16 | |
int len = plain_data.length(); | |
int n_blocks = len / 16 + 1; | |
uint8_t n_padding = n_blocks * 16 - len; | |
uint8_t data[n_blocks*16]; | |
memcpy(data, plain_data.c_str(), len); | |
for(i = len; i < n_blocks * 16; i++){ | |
data[i] = n_padding; | |
} | |
uint8_t key[32], iv[16]; | |
memcpy(key, cipher_key, 32); | |
memcpy(iv, cipher_iv, 16); | |
// encryption context | |
br_aes_big_cbcenc_keys encCtx; | |
// reset the encryption context and encrypt the data | |
br_aes_big_cbcenc_init(&encCtx, key, 32); | |
br_aes_big_cbcenc_run( &encCtx, iv, data, n_blocks*16 ); | |
// Base64 encode | |
len = n_blocks*16; | |
char encoded_data[ base64_enc_len(len) ]; | |
base64_encode(encoded_data, (char *)data, len); | |
return String(encoded_data); | |
} | |
// AES CBC Decryption | |
String decrypt(String encoded_data_str){ | |
int input_len = encoded_data_str.length(); | |
char *encoded_data = const_cast<char*>(encoded_data_str.c_str()); | |
int len = base64_dec_len(encoded_data, input_len); | |
uint8_t data[ len ]; | |
base64_decode((char *)data, encoded_data, input_len); | |
uint8_t key[32], iv[16]; | |
memcpy(key, cipher_key, 32); | |
memcpy(iv, cipher_iv, 16); | |
int n_blocks = len / 16; | |
br_aes_big_cbcdec_keys decCtx; | |
br_aes_big_cbcdec_init(&decCtx, key, 32); | |
br_aes_big_cbcdec_run( &decCtx, iv, data, n_blocks*16 ); | |
// PKCS#7 Padding (Decryption) | |
uint8_t n_padding = data[n_blocks*16-1]; | |
len = n_blocks*16 - n_padding; | |
char plain_data[len + 1]; | |
memcpy(plain_data, data, len); | |
plain_data[len] = '\0'; | |
return String(plain_data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment