小编典典

使用Java的AES加密和使用Java的解密

java

我正在制作一个需要基于Java的AES加密和基于JavaScript的解密的应用程序。我正在使用以下代码作为基本形式进行加密。

public class AESencrp {

  private static final String ALGO = "AES";
  private static final byte[] keyValue = 
      new byte[] { 'A', 'b', 'c', 'd', 'e', 'f', 'g',
      'h', 'i', 'j', 'k','l', 'm', 'n', 'o', 'p'};

  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());
    String encryptedValue = new BASE64Encoder().encode(encVal);
    return encryptedValue;
  }


  private static Key generateKey() throws Exception {
    Key key = new SecretKeySpec(keyValue, ALGO);
    return key;
  }
}

我试图用来解密的JavaScript是

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js">   </script>

var decrypted = CryptoJS.AES.decrypt(encrypted,"Abcdefghijklmnop").toString(CryptoJS.enc.Utf8);

但是JavaScript解密无法正常工作。我是新手,有人可以告诉我一种无需更改Java代码块即可解决的方法吗?

我尝试使用Base-64解码文本,如下所示:

var words  = CryptoJS.enc.Base64.parse(encrKey);
var base64 = CryptoJS.enc.Base64.stringify(words);
var decrypted = CryptoJS.AES.decrypt(base64, "Abcdefghijklmnop");
alert("dec :" +decrypted);

但还是不好

我尝试了以下建议的解决方案来解决可能的填充问题,但未给出任何解决方案。

var key = CryptoJS.enc.Base64.parse("QWJjZGVmZ2hpamtsbW5vcA==");
var decrypt = CryptoJS.AES.decrypt( encrKey, key, { mode: CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7 } );

alert("dec :" +decrypt);

阅读 236

收藏
2020-12-03

共1个答案

小编典典

  1. 您的Java代码使用128位AES密钥,而JavaScript代码使用256位AES密钥。

  2. 您的Java代码使用“ Abcdefghijklmnop” .getBytes()作为实际键值,而您的JavaScript代码使用“ Abcdefghijklmnop”作为导出实际密钥的密码。

  3. Java AES的默认转换是AES / ECB / PKCS5Padding,而CryptoJS的默认转换是AES / CBC / PKCS7Padding。

解决示例的一种方法是修复JavaScript方面:

// this is Base64 representation of the Java counterpart
// byte[] keyValue = new byte[] { 'A', 'b', 'c', 'd', 'e', 'f', 'g',
//                'h', 'i', 'j', 'k','l', 'm', 'n', 'o', 'p'};
// String keyForJS = new BASE64Encoder().encode(keyValue);
var base64Key = "QWJjZGVmZ2hpamtsbW5vcA==";
console.log( "base64Key = " + base64Key );

// this is the actual key as a sequence of bytes
var key = CryptoJS.enc.Base64.parse(base64Key);
console.log( "key = " + key );

// this is the plain text
var plaintText = "Hello, World!";
console.log( "plaintText = " + plaintText );

// this is Base64-encoded encrypted data
var encryptedData = CryptoJS.AES.encrypt(plaintText, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
});
console.log( "encryptedData = " + encryptedData );

// this is the decrypted data as a sequence of bytes
var decryptedData = CryptoJS.AES.decrypt( encryptedData, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
} );
console.log( "decryptedData = " + decryptedData );

// this is the decrypted data as a string
var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
console.log( "decryptedText = " + decryptedText );
2020-12-03