I am using below JAVA code to encrypt plain text, which will create cipher text, later decrypt this cipher text using Key ( which is generated via getSecretEncryptionKey().getEncoded() in JAVA File ) in C++ code.
JAVA CODE:
public byte[] encryptDecrypt(String jsonData, String publicKey) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
SecretKey secKey = getSecretEncryptionKey();
cipherText = encryptText(jsonData, secKey);
return cipherText;
}
public static SecretKey getSecretEncryptionKey() throws Exception
{
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256);
SecretKey secKey = generator.generateKey();
return secKey;
}
public static byte[] encryptText(String plainText, SecretKey secKey) throws Exception
{
// AES defaults to AES/ECB/PKCS5Padding in Java 7
SecretKeySpec skeySpec = new SecretKeySpec(secKey.getEncoded(), "AES/ECB/PKCS7Padding");
Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return aesCipher.doFinal(plainText.getBytes());
}
C++ CODE:
INT32 Security::decrypt(UINT8 *ciphertext, INT32 ciphertext_len, UINT8 *key,
UINT8 *iv, UINT8 *plaintext)
{
EVP_CIPHER_CTX *ctx;
INT32 len;
INT32 plaintext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_ecb(), 0, key, NULL)) {
printf("\n ERROR!! \n");
return -1;
}
/* 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_ex(ctx, plaintext + len, &len)) handleErrors();
plaintext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
While decrypting CipherText using Key , C++ code is generating segmentation fault and giving below error:
140159077054088:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:596: Aborted (core dumped)
I am new in this domain so please help me.