简体   繁体   English

cryptojs aes 256加密和Java解密

[英]cryptojs aes 256 encryption and java decryption

I encrypted message with cryptojs aes 256 on the client side. 我在客户端使用cryptojs aes 256对消息进行了加密。 But couldn't decrypt it on the java side. 但是无法在Java端对其进行解密。 First, I pass the key directly to the server side as hex, then convert it from hex to java bytearray. 首先,我将密钥以十六进制形式直接传递给服务器端,然后将其从十六进制转换为Java字节数组。 It didn't work. 没用 Then I pass the phrase, salt, iv to the server as hex. 然后,我将十六进制的盐(盐)iv传递给服务器。 Then generate the key. 然后生成密钥。 It still didn't work. 仍然没有用。 It always to complain the key length is not right. 总是抱怨密钥长度不正确。

Client side: 客户端:

var salt = CryptoJS.lib.WordArray.random(16);
var salt_hex = CryptoJS.enc.Hex.stringify(salt);

var iv = CryptoJS.lib.WordArray.random(256/32);
var iv_hex = CryptoJS.enc.Hex.stringify(iv);


var key = CryptoJS.PBKDF2(secret, salt, { keySize: 256/32, iterations: 10 });
var key_hex=CryptoJS.enc.Hex.stringify(key);

var encrypted = CryptoJS.AES.encrypt(plaintext, key, { iv: iv });    

var encryptedtxt = secret+":"+salt_hex+":"+iv_hex+":"+encrypted.ciphertext.toString(CryptoJS.enc.Base64)+":"+key_hex;

Server side: 服务器端:

    if (encrypted != null)
    {
        //Get the passphras, salt, IV and msg
        String data[] = encrypted.split(":");
        String passphrase = data[0];
        String salt_hex = data[1];
        String iv_hex = data[2];
        String msg64 = data[3];
        String jskey_hex = data[4];
        byte[] jskey = hexStringToByteArray(jskey_hex);
        byte[] iv = hexStringToByteArray(iv_hex);
        byte[] salt = hexStringToByteArray(salt_hex);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] msg = decoder.decodeBuffer(msg64);

        try {
             //theClear = AES.decrypt(encrypted);
            /* Decrypt the message, given derived key and initialization vector. */
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), salt, 10, 256/32);
            SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            String plaintext = new String(cipher.doFinal(msg), "UTF-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Finally figured it out. 终于想通了。 By default JRE 7 doesn't support 256-bit key. 默认情况下,JRE 7不支持256位密钥。 I had to download the new jars from http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html and overwrite them in the jre/lib/security folder. 我必须从http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html下载新的jar并将其覆盖在jre / lib / security文件夹中。 You will have to do the similar thing for the Websphere 6 or 7. If you don't do it, it prompts "illegal key size". 对于Websphere 6或7,您将必须执行类似的操作。如果不这样做,则会提示“非法密钥大小”。 I've also seen "illegal key size x", where x is a number. 我还看到了“非法密钥大小x”,其中x是数字。 That means the key size is not right. 这意味着密钥大小不正确。 Below are the code. 下面是代码。

Server side: 服务器端:

//@Override
public String getClearText() throws IOException {
    // Get the body
    String encrypted = super.getParameter("aes"); //base64

    if (encrypted != null)
    {
        //Get the passphras, salt, IV and msg
        String data[] = encrypted.split(":");
        String passphrase = data[0];
        String salt_hex = data[1];
        String iv_hex = data[2];
        String msg64 = data[3];
        String jskey_hex = data[4];
        byte[] jskey = hexStringToByteArray(jskey_hex);
        byte[] iv = hexStringToByteArray(iv_hex);
        byte[] salt = hexStringToByteArray(salt_hex);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] msg = decoder.decodeBuffer(msg64);
        String plaintext = "";
        try {
            SecretKey key = new SecretKeySpec(jskey, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            plaintext = new String(cipher.doFinal(msg), "UTF-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("in filter, decrypted: " +plaintext);
    }
    return plaintext;
}

Client: 客户:

$(function() {

$('#test').on('submit', function() {

var plaintext = $('#text').val();
var secret = '0123456789abcdef';

var salt = CryptoJS.lib.WordArray.random(16);
var salt_hex = CryptoJS.enc.Hex.stringify(salt);

var iv = CryptoJS.lib.WordArray.random(16);
var iv_hex = CryptoJS.enc.Hex.stringify(iv);


var key = CryptoJS.PBKDF2(secret, salt, { keySize: 256/32, iterations: 1 });
//var key_hex=CryptoJS.enc.Hex.stringify(key);
var key_hex= key;

var encrypted = CryptoJS.AES.encrypt(plaintext, key, { iv: iv });    


//decrypt
var decrypted = CryptoJS.AES.decrypt(
      encrypted,
      CryptoJS.enc.Hex.parse(key_hex),
      { iv: CryptoJS.enc.Hex.parse(iv_hex) });

var text = decrypted.toString( CryptoJS.enc.Utf8 );
//console.log(encrypted);

// ----- base64 encoding ----------
var encryptedtxt =     secret+":"+salt_hex+":"+iv_hex+":"+encrypted.ciphertext.toString(CryptoJS.enc.Base64)+":"+key_hex;
console.log('html - ciphere txt : ' +encryptedtxt);

// ---- testing ----
//var decrypted = CryptoJS.AES.decrypt(encrypted, key,{iv: CryptoJS.enc.Utf8.parse(iv)});
//console.log(decrypted.toString(CryptoJS.enc.Utf8));

post ('/E2Efilter/TheServlet', encryptedtxt);
return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM