简体   繁体   中英

Need help converting encryption logic from Js to Java

I am trying to re-create a code snippet from JS to Java, but the outputs are different. What am I doing wrong? This is the code snippet from JS:

var randomKey = 2116781760886580;

var key = CryptoJS.enc.Utf8.parse(randomKey);

var iv = CryptoJS.enc.Utf8.parse(randomKey);

var encrypt = CryptoJS.AES
    .encrypt(CryptoJS.enc.Utf8.parse("Text to encrypt"), key,
        {
            keySize: 128 / 8,
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });

var out = btoa(encrypt);   //SGpJSWhDUXNmMEMzSk0vbmovaGZyQT09

The following is the Java code snippet:

String randomKey = "2116781760886580";

String plainText = "Text to encrypt";

byte[] keyBytes = randomKey.getBytes(StandardCharsets.UTF_8);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);

SecretKeySpec sKey = new SecretKeySpec(keyBytes,"AES");

cipher.init(Cipher.ENCRYPT_MODE, sKey, ivSpec);

byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

String out = Base64.getEncoder().encodeToString(encryptedBytes);    //HjIIhCQsf0C3JM/nj/hfrA==

CryptoJS.AES.encrypt() returns a CipherParams object that encapsulates several data, in particular the ciphertext. If the CipherParams object is passed to btoa() , it is first implicitly converted to a string using toString() which returns the Base64 encoded ciphertext of the CipherParams object by default, at least if no salt is involved as in this case. Together with the Base64 encoding of btoa() , the ciphertext is therefore Base64 encoded twice .

So that the Java code provides the same result as the JavaScript code, the ciphertext must therefore also be Base64 encoded twice, which is done eg with the following addition:

String out2 = Base64.getEncoder().encodeToString(out.getBytes(StandardCharsets.UTF_8));

Note that the redundant Base64 encoding is actually useless and only increases the amount of data ( Base64 has 33% overhead ). Also, using the key as IV is generally insecure, here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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