gpt4 book ai didi

javascript - 通过 javascript 加密并通过 Java 解密

转载 作者:行者123 更新时间:2023-12-02 09:22:01 25 4
gpt4 key购买 nike

我在我的 react native 应用程序中使用 AES 加密,如下所示

import CryptoJS from 'crypto-js' ;
encryptFun() {
var data = "123456";
var key = CryptoJS.enc.Latin1.parse('1234567812345678');
var iv = CryptoJS.enc.Latin1.parse('1234567812345678');
var encrypted = CryptoJS.AES.encrypt(
data,
key,
{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding
});
console.log('encrypted: ' + encrypted) ;
var decrypted = CryptoJS.AES.decrypt(encrypted,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});
console.log('decrypted: '+decrypted.toString(CryptoJS.enc.Utf8));
}

结果=加密:aK7+UX24ttBgfTnAndz9aQ==

以下是我在后端使用 java 进行解密的代码

 public static String desEncrypt() throws Exception {

try
{
String data = "aK7+UX24ttBgfTnAndz9aQ==" ;
String key = "1234567812345678";
String iv = "1234567812345678";

byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);

Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}

输出=解密:= 123456[][][][][][][][][][]

我将输出为 16 位,如上所述。我想要的是输出应该只有 123456。

最佳答案

我建议您使用java.util.Base64进行解码。以下结果正确。我还建议在 returnoriginalString 中使用 trim ,看看它是否有效。

public class Decrypt {

public static void main(String[] args) {
try
{
String data = "aK7+UX24ttBgfTnAndz9aQ==" ;
String key = "1234567812345678";
String iv = "1234567812345678";

Decoder decoder = Base64.getDecoder();
byte[] encrypted1 = decoder.decode(data);

Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
System.out.println(originalString.trim());
}
catch (Exception e) {
e.printStackTrace();
}
}
}

关于javascript - 通过 javascript 加密并通过 Java 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58621582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com