java - aes gcm加解密的互通性
问题描述
请分享 node js 中加密的工作代码和 java AES/GCM/NoPadding 中的解密
在节点 js中:
function createCipherCommon(text, alg, key, iv) {
var cipher = crypto.createCipheriv(alg, key, iv);
cipher.setAAD(Buffer.from("aad", 'utf8'));
return {
enc: cipher.update(text, 'utf8', 'base64') + cipher.final('base64'),
tag: cipher.getAuthTag().toString('base64')
};
}
在Java中,下面的代码给出 javax.crypto.AEADBadTagException: Tag mismatch!
public static String createDecipherCommon(byte[] text, byte[] key, String iv, String tag) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException, InvalidAlgorithmParameterException, UnsupportedEncodingException, DecoderException {
byte[] ivBytes = Base64.getDecoder().decode(iv.getBytes());
byte[] tagBytes = Base64.getDecoder().decode(tag.getBytes());
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, ivBytes, 0, ivBytes.length));
cipher.updateAAD("aad".getBytes());
return new String(cipher.doFinal(text, 0, text.length));
}
解决方案
在Node js中,我进行了这些更改,现在它工作正常:
function createCipherCommon(text, alg, key, iv) {
var cipher = crypto.createCipheriv(alg, key, iv);
cipher.setAAD(Buffer.from("aad", 'utf8'));
return {
encwithtag: Buffer.concat([cipher.update(text, 'utf8'), cipher.final(), cipher.getAuthTag()]).toString('base64')
};
}
在Java中,不变
public static String createDecipherCommon(byte[] text, byte[] key, String iv, String tag) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException, InvalidAlgorithmParameterException, UnsupportedEncodingException, DecoderException {
byte[] ivBytes = Base64.getDecoder().decode(iv.getBytes());
byte[] tagBytes = Base64.getDecoder().decode(tag.getBytes());
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, ivBytes, 0, ivBytes.length));
cipher.updateAAD("aad".getBytes());
return new String(cipher.doFinal(text, 0, text.length));
}
推荐阅读
- python - 在许多表 django rest 框架之间对数据进行排序
- macos - 使用加拿大计算时 Mpi Bcast 错误
- git - Git Rebase 包括特定的提交
- python - 如何在 spaCy 中改进德语文本分类模型
- python - Discord.py on_message() 但仅用于私人消息
- python - 将具有不同长度数组的字典转换为 Excel
- c# - Asp.Net Core Identity、IdentityUser.Email 与 UserManage
.GetEmailAsync(IdentityUser 用户) - javascript - Rollup 只关注导出数组中的一个配置
- kotlin - 所有生产者协程完成后如何关闭通道?
- xml - RTF 模板中的 XML 标记分组以抑制重复