我想用nodejs加密数据,然后用java解密数据。我在网上搜索了很多例子,但没有找到合适的答案。nodejs代码如下:
const crypto = require('crypto');
function encrypt(content) {
const salt = crypto.randomBytes(cryptoConfig.saltLength);
const iv = crypto.randomBytes(cryptoConfig.ivLength);
const key = crypto.pbkdf2Sync(cryptoConfig.masterKey, salt, cryptoConfig.iterations,
cryptoConfig.keyLength, cryptoConfig.digest);
const cipher = crypto.createCipheriv(cryptoConfig.cipherAlgorithm, key, iv);
const encrypted = Buffer.concat([cipher.update(content, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
const encdata = Buffer.concat([salt, iv, tag, encrypted]).toString('base64');
return encdata;
}
const cryptoConfig = {
cipherAlgorithm: 'aes-256-gcm',
masterKey: 'sfcpnnjFG6dULJfo1BEGqczpfN0SmwZ6bgKO5FcDRfI=',
iterations: 65535,
keyLength: 32,
saltLength: 16,
ivLength: 12,
tagLength: 16,
digest: 'sha512'
}
const encrypteddata=encrypt('hello world');console.log('加密数据->',加密数据);
java代码:
private static final Charset UTF_8 = StandardCharsets.UTF_8;
private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
private static final int TAG_LENGTH = 16;
private static final int IV_LENGTH = 12;
private static final int SALT_LENGTH = 16;
private static final int KEY_LENGTH = 16;
private static final int ITERATIONS = 65535;
public static String decrypt(String cipherContent, String password) throws Exception {
byte[] decode = Base64.getDecoder().decode(cipherContent.getBytes(UTF_8));
ByteBuffer bb = ByteBuffer.wrap(decode);
byte[] salt = new byte[SALT_LENGTH];
bb.get(salt);
byte[] iv = new byte[IV_LENGTH];
bb.get(iv);
byte[] content = new byte[bb.remaining()];
bb.get(content);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKey aesKeyFromPassword = getAESKeyFromPassword(password.toCharArray(), salt);
cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH * 8, iv));
byte[] plainText = cipher.doFinal(content);
return new String(plainText, UTF_8);
}
private static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
KeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH * 8);
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
return secret;
}
public static void main(String[] args) throws Exception {
String masterKey = "sfcpnnjFG6dULJfo1BEGqczpfN0SmwZ6bgKO5FcDRfI=";
String encryptedData = "<NodeJS return encryptedData>";
String decryptedText = decrypt(encryptedData, masterKey);
System.out.println("Decrypted: " + decryptedText));
}
执行后,引发异常:
Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch!
at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:571)
at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1046)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:983)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:845)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at com.xxx.common.AesCrypto.decrypt(AesCrypto.java:92)
at com.xxx.common.AesCrypto.main(AesCrypto.java:131)
我该如何改变才能让这一幕贯穿始终
1条答案
按热度按时间fdx2calv1#
代码中总共有两个问题使您无法在nodejs/crypto和java之间成功地加密,但是如果更改了两行代码,它将像预期的那样工作。
nodejs:在加密函数的末尾,您将解密所需的参数连接到一个更大的数组中。正如java所期望的
ciphertext:gcmTag
输入您应该更改行java:您要求aes gcm 256加密,这意味着您必须在两边使用256/8=32字节长的密钥,所以只需更改常量即可
你可以在这里在线运行这两个代码,nodejs:https://repl.it/@javacrypto/sonodejscryptoaesgcm256pbkdf2stringencryption#index.js和java:https://repl.it/@javacrypto/sojavaaesgcm256pbkdf2stringdecryption#主.java
以下是输出:
节点:
java 语:
安全警告:代码没有异常处理,仅用于教育目的。
节点:
java 语: