我想将CryptoJS代码转换为java代码。这是javascript代码:
CryptoJS.AES.encrypt('hello',CryptoJS.enc.Utf8.parse(CryptoJS.MD5("http://stackoverflow.com")), {iv: CryptoJS.enc.Utf8.parse("1234567812345678")})
在代码结果上方调用字符串是' QtzDsbCgmA9 + XBVEsEm70w =='
然后我通过CryptoJS.MD5获取键值(" http://stackoverflow.com")。toString()方法(键= 57f4dad48e7a4f7cd171c654226feb5a)
这是java代码:
try {
String content = "hello";
String key = "57f4dad48e7a4f7cd171c654226feb5a";
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key.getBytes("utf-8")));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key1 = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key1,new IvParameterSpec("1234567812345678".getBytes("UTF-8")));
byte[] result = cipher.doFinal(byteContent);
System.out.println(new String(result).equals("QtzDsbCgmA9+XBVEsEm70w=="));
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
但输出结果为false。如何修复java代码以将结果更改为true。
答案 0 :(得分:0)
根据@Luka Park的建议,我已经解决了我的问题。这是我的解决方案:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);