0

I have an AES class in java, my intention to decrypt a JSON string in js which encrypted in java, here is my encryption code

public static void setKey(String myKey)
    {
        MessageDigest sha = null;
        try {
            key = myKey.getBytes("UTF-8");
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            System.out.println(Arrays.toString(key));
            secretKey = new SecretKeySpec(key, "AES");
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String strToEncrypt, String secret)
    {
        try
        {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        }
        catch (Exception e)
        {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

And I have tried many way using Cryptojs

var secret = "llssshhhhhhhhhhh";


      var new_secret = CryptoJS.SHA1(getBytes(secret));
      console.log(getBytes(new_secret.toString()));


      var test = "<Encrypted Text>";
      var bytes  = CryptoJS.AES.decrypt(test, new_secret, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
        });
      var originalText = bytes.toString(CryptoJS.enc.Utf8);
      console.log({originalText});

But I am not getting the original text even its return a blank string. Can anyone know I am wrong?

  • Does this answer your question? [How to decrypt message with CryptoJS AES. I have a working Ruby example](https://stackoverflow.com/questions/14958103/how-to-decrypt-message-with-cryptojs-aes-i-have-a-working-ruby-example) – Sambit Apr 03 '20 at 05:21
  • The purpose of the (not posted) `getBytes` is not clear to me, because a string can also be passed _directly_ to SHA1: `var new_secret = CryptoJS.SHA1(secret);`. Furthermore, the resulting hash is 20 bytes long, of which _only 16 bytes_ are used in the Java code. The latter can be achieved in the CyptoJS code with e.g. `new_secret.sigBytes = 16;`. – Topaco Apr 03 '20 at 07:07
  • I was trying to mimic the generate Key like in the Java code. – Subhendu Mondal Apr 03 '20 at 07:40

0 Answers0