简体   繁体   中英

Why can't java decrypt CryptoJS encrypted data?

I have function for decrypting in Java as such

public String decrypt() throws Exception {
        SecretKey secretKey = getSecretKey("o9szYIOq1rRMiouNhNvaq96lqUvCekxR");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(base64Decode("ASDASDADS")));
    }

public SecretKey getSecretKey(String secretKey) throws Exception {
        byte[] decodeSecretKey = base64Decode(secretKey);
        return new SecretKeySpec(decodeSecretKey, 0, decodeSecretKey.length, "AES");
    }

I tried to encrypt the data using CryptoJS as such

  function aesEncrypt(data, secretKey) {
    var encrypted = CryptoJS.AES.encrypt(data, secretKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
    });

    var ciphertext = encrypted.ciphertext.toString();

    var wordArray = CryptoJS.enc.Utf8.parse(ciphertext);
    var base64 = CryptoJS.enc.Base64.stringify(wordArray);
    return base64
  }
  //call the function
  aesEncrypt('Test' , 'o9szYIOq1rRMiouNhNvaq96lqUvCekxR');

When I send the request to JAVA API I get

Given final block not properly padded. Such issues can arise if a bad key is used during decryption

I even tried with forge library. It does not work either.

function aesEncrypt(data, secretKey) {
    var cipher = forge.cipher.createCipher('AES-ECB', secretKey)

    cipher.start()
    cipher.update(forge.util.createBuffer(data))
    cipher.finish()

    return forge.util.encode64(cipher.output.data)
  }

The difference I see between the two is from forge, when I output the data ie console.log(cipher.output.data) . I get

uJ@^$¿EÅKÖé1ÙN¢cÖúpxÇÅÂëv¥qè9Ï/¨§È5æý»¸,À?¿ "y§¯:ßñ[® ?ÓjÃùØQèó÷à¯~6jØ¿óðn5»§Ñ ,A.ÛCeða©ëZÁR¸:jy¹ScÃ6d?#ÚÔí\\N¤s~ã¯ÃÉ5d0U:©ªÕ"ã¾xx ?§F?ØïÅFÛb?ÒÓJ§j ¸²ä2½]Õç£ÿ#È&?C! M¡ è ÁÖÈ ¾¦aÒc~: °j>yc6ÞÖú]OAÅÖ!x ìJu2ðΡ¦*õô±¤kÆ ÂTùû=|2^XAy5?¹Êè?díXÝg ë?q" %üSyÿO¾bzjc²·ákÑî¼¾¡ÓV?*Çr¢?rÎlò ?ÓjÃùØQèó÷à¯~6jØ¿óðn5»§Ñ ,A.ÛCeða©ëZÁR¸:jy¹ScÃ6d?#ÚÔí\\N¤s~ã¯ÃÉ5d0U:©ªÕ"ã¾xx ?§F?ØïÅFÛb?ÒÓJ§j ¸²ä2½]Õç£ÿ#È&?C! M¡ è ÁÖÈ ¾¦aÒc~: °j>yc6ÞÖú]OAÅÖ!x ìJu2ðΡ¦*õô±¤kÆ ÂTùû=|2^XAy5?¹Êè?díXÝg ë?q" %üSyÿO¾bzjc²·ákÑî¼¾¡ÓV?*Çr¢?rÎlò z°»yN?ûöCpã

But from CryptoJS I get console.log(ciphertext)

How to use either of the two? and Why is there a difference between the above output?

Please find below a code pair that uses Javascript to en- and decrypt a string with static key in ECB mode. The Java code is taking the ciphertext (= output of encryption function) from Javascript and decrypts the Base64 encoded ciphertext.

Security warning: Both codes are UNSECURE as they use the ECB mode and static encryption key.

Javascript output (see live example with this link: https://playcode.io/682378 )

plaintext: Test
ciphertext: oNP8t53ZTi1WUptGCDh5NQ==
decryptedtext: Test

Java output:

ciphertextFromJavascript: oNP8t53ZTi1WUptGCDh5NQ==
decrypted: Test

Javascript code:

// *** Security warning **
// DO NOT USE THIS CODE IN PRODUCTION AS IT IS UNSECURE
// it uses ECB mode and static key

var plaintext = 'Test';
console.log('plaintext: ', plaintext);

/**
 * Encryption
 * @param word
 * @returns {*}
 */
function encrypt(word){
    const keyBase64 = "o9szYIOq1rRMiouNhNvaq96lqUvCekxR";
    var key = CryptoJS.enc.Base64.parse(keyBase64);
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
}
 
/**
   * Decrypt
 * @param word
 * @returns {*}
 */
function decrypt(word){
    const keyBase64 = "o9szYIOq1rRMiouNhNvaq96lqUvCekxR";
    var key = CryptoJS.enc.Base64.parse(keyBase64);
    var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

var ciphertext = encrypt(plaintext);
console.log('ciphertext: ', ciphertext);
var decryptedtext = decrypt(ciphertext);
console.log('decryptedtext: ', decryptedtext);

Java code:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("Why can't java decrypt CryptoJS encrypted data ?");
        String ciphertextFromJavascript = "oNP8t53ZTi1WUptGCDh5NQ==";
        System.out.println("ciphertextFromJavascript: " + ciphertextFromJavascript);
        System.out.println("decrypted: " + decrypt(ciphertextFromJavascript));
    }
    public static String decrypt(String ciphertext) throws Exception {
        SecretKey secretKey = getSecretKey("o9szYIOq1rRMiouNhNvaq96lqUvCekxR");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)));
        //return new String(cipher.doFinal(base64Decode("ASDASDADS")));
    }

    public static SecretKey getSecretKey(String secretKey) throws Exception {
        byte[] decodeSecretKey = Base64.getDecoder().decode(secretKey);
        //byte[] decodeSecretKey = base64Decode(secretKey);
        return new SecretKeySpec(decodeSecretKey, 0, decodeSecretKey.length, "AES");
    }
}

JavaScript

encryptMethod(word){
const keyBase64 = "o9szYIOq1rRMiouNhNvaq96lqUvCekxR";
var key = CryptoJS.enc.Base64.parse(keyBase64);
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return encrypted.toString();}

Java

public String decriptMethod(String text) throws Exception {
    String ciphertextFromJavascript = text;
    return decrypt(ciphertextFromJavascript);
}
public static String decrypt(String ciphertext) throws Exception {
    SecretKey secretKey = getKey("o9szYIOq1rRMiouNhNvaq96lqUvCekxR");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)));
    //return new String(cipher.doFinal(base64Decode("ASDASDADS")));
}

public static SecretKey getKey(String secretKey) throws Exception {
    byte[] decodeSecretKey = Base64.getDecoder().decode(secretKey);
    return new SecretKeySpec(decodeSecretKey, 0, decodeSecretKey.length, "AES");
}

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