var data = word;
var key = CryptoJS.enc.Utf8.parse('1111111111111111');
var iv = CryptoJS.enc.Utf8.parse('');
//加密
var encrypted = CryptoJS.AES.encrypt(data, key, {iv: iv, mode: CryptoJS.mode.CBC });
这么搞 Java 没办法解密啊。。。难倒 CryptoJS 有默认的 iv ?
public class AesJsUtil {
public static String decrypt(String password, String key) {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Resource aesJs = new ClassPathResource("js" + File.separator + "aes.js");
try {
engine.eval(new FileReader(aesJs.getFile()));
Invocable invocable = (Invocable) engine;
return (String) invocable.invokeFunction("decrypt", password, key);
} catch (Exception e) {
log.error("JS解密失败", e);
}
}
}
function decrypt(encrypt, currentKey) {
var key = CryptoJS.enc.Utf8.parse(currentKey);
var iv = CryptoJS.enc.Utf8.parse('');
var decrypted = CryptoJS.AES.decrypt(encrypt.toString(), key, { iv: iv, mode: CryptoJS.mode.CBC }).toString(CryptoJS.enc.Utf8);
return decrypted.toString();
}
1
rmb1222 2020-04-27 16:48:23 +08:00 1
|
2
zxyroy 2020-04-27 17:32:06 +08:00
随机生成的话下次要怎么解密?
|
3
LeeSeoung 2020-04-27 17:34:31 +08:00
iv 为空随机生成,解密的时候密文要跟 iv 一起提供。
|
4
jiejiss 2020-04-27 17:41:36 +08:00
@zxyroy #2 https://github.com/gwjjeff/cryptojs/blob/master/lib/AES.js#L126 iv 为空情况下(返回的密文的)前 16 字节就是随机生成的 iv
复读了一下 #1 |
6
yukiball 2020-04-27 18:41:15 +08:00
长知识了
|
7
jiejiss 2020-07-01 23:12:29 +08:00
你本可以直接 String iv = encrypted.substring(0, 16); 的,不需要调用 JS 解密
|