在Java中使用相同的加密算法和密钥将字符串进行加密,然后将其传输到Angular端。在Angular中使用CryptoJS库解密该加密字符串。
下面是Java端的示例代码:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class CryptoUtil {
private static final String ALGO = "AES";
private static final byte[] KEY_VALUE = "thisismysecrekey".getBytes();
public static String encrypt(String data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(data.getBytes());
return new sun.misc.BASE64Encoder().encode(encVal);
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new sun.misc.BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
return new String(decValue);
}
private static Key generateKey() throws Exception {
return new SecretKeySpec(KEY_VALUE, ALGO);
}
}
下面是Angular端的示例代码:
import * as CryptoJS from 'crypto-js';
const encryptedData = 'zwjkleHKJscVVJnQSPNv4M4AZR2WblrEbEJnIqZXIvw=';
const key = CryptoJS.enc.Utf8.parse('thisismysecrekey');
const decryptedData = CryptoJS.AES.decrypt(encryptedData, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log(decryptedData.toString(CryptoJS.enc.Utf8));
这两段代码将会输出同样的字符串,即在Java端加密并在Angular端解密的字符串。