[英]I am trying to convert Java AES encryption to NodeJs. This is what I have tried so far
Java encryption code. Java 加密代码。
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.json.simple.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jarvis.accountopeningv2.model.PartChanRequestDTO;
import com.jarvis.accountopeningv2.model.TemplateDTO;
public class SecurityService {
private static final String ALGORITHM = "AES/CBC/PKCS5PADDING";
public static String encryptpayload(String value, String key) {
String encryptedData = null;
try {
IvParameterSpec iv = new IvParameterSpec(key.substring(0, 16).getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.substring(0, 32).getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
encryptedData = Base64.getEncoder().encodeToString(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
encryptedData = null;
}
return encryptedData;
}
}
This is what I have tried.这是我尝试过的。
function SecurityFunc(request) {
const digest = 'SHA256';
var secretkey = 'fgbnhgfcjhgfcvjkhgfcvjkhgfcvbjbnvcjhnbvcfghjnbvc'; // 256 character
var iv = Buffer.from(secretkey.substring(0,16), 'utf-8', 'aes');
const key = crypto.pbkdf2Sync(secretkey, 'boooooo!!', 65536, 32, digest);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(`${request}`, 'ascii', 'base64');
encrypted += cipher.final('base64');
return encrypted;
}
I have searched a lot about this.我对此进行了很多搜索。 I got these questions on stack overflow
我在堆栈溢出时遇到了这些问题
Difference in key lengths between crypto.pbkdf2 (node.js) and PBEKeySpec, AES/CBC/PKCS5PADDING IV - Decryption in NodeJs (Encrypted in Java) I have tried both of them but none of them resolved my query. crypto.pbkdf2 (node.js) 和 PBEKeySpec、AES/CBC/PKCS5PADDING IV 之间的密钥长度差异 - NodeJs 中的解密(用 Java 加密)我已经尝试了它们,但它们都没有解决我的查询。
Any help will be highly appreciated.任何帮助将不胜感激。
Are you trying to make the 2 compatible or just port the code from Java to JavaScript?您是想让 2 兼容还是只是将代码从 Java 移植到 JavaScript?
Update: apparently PKCS#5 will work the same as for PKCS#7 so that isn't your issue.更新:显然 PKCS#5 与 PKCS#7 的工作方式相同,所以这不是你的问题。
The key length should be 32-bytes in both cases.在这两种情况下,密钥长度都应该是 32 字节。
If you don't need backwards compatibility, I'd recommend using AES in GCM mode rather than CBC as it includes tamper protection.如果您不需要向后兼容性,我建议在 GCM 模式下使用 AES 而不是 CBC,因为它包含篡改保护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.