我正在尝试在PHP和Java之间使用AES-256位GCM加密。问题是我在Android上的Java端收到了这个例外:
Decryption Error.!
javax.crypto.AEADBadTagException: error:1e06e065:Cipher functions:aead_aes_gcm_open:BAD_DECRYPT
我正在使用的代码: 在PHP方面
$algo = 'aes-256-gcm';
$iv = random_bytes(openssl_cipher_iv_length($algo));
$key = "secretKey12345678998765432112345"; // 256 bit
$data = "HelloWorld";
$ciphertext = openssl_encrypt(
$data,
$algo,
$key,
OPENSSL_ZERO_PADDING,
$iv,
$tag
);
echo base64_encode($key);
echo base64_encode($iv);
echo $ciphertext;
在Java,Android上,我正在使用此代码:
static final int GCM_TAG_LENGTH = 16;
...
String decryptedText = null;
byte[] encodedData = Base64.decode(data, Base64.DEFAULT);
byte[] decodediv = Base64.decode(iv, Base64.DEFAULT);
byte[] decodedKey = Base64.decode(key, Base64.DEFAULT);
Log.e("data", new String(encodedData, 0));
Log.e("iv", new String(decodediv, 0));
Log.e("key", new String(decodedKey, 0));
Log.d("test", "test");
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
try {
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, originalKey , new GCMParameterSpec(GCM_TAG_LENGTH * 8,decodediv));
byte[] decodedData = c.doFinal(encodedData);
decryptedText = new String(decodedData, "UTF-8");
Log.e("MainActivity", "After decryption : "+ decryptedText);
} catch (Exception e) {
Log.e("MainActivity", "Decryption Error.!", e);
}
return decryptedText;
我正在使用此页面中的php代码:
zimuel.it/blog/authenticated-encrypt-with-openssl-and-php-7-1
我使用的是php v7.1.4
可能是例外原因?
答案 0 :(得分:0)
我自己解决了这个问题,我只需要在base64中将编码在base64中的$ tag变量添加到PHP的加密消息末尾,因为JAVA AES gcm实现搜索标记,我之前没有提供过。