1

I am encrypting value using CryptoJS in front end but when I tried to decrypt in java am not able to do so.Is there any to decrypt value in java which am getting from front end using cryptojs.
Any help would be greatly appreciated

encryption code:

value="1234"
key="abcdabcd12341234"
encryption(value , key){

  var enc4 = CryptoJS.AES.encrypt(value,key);
  console.log(enc4.toString());

decryption code:

public static String decryption(String value, String key) throws Exception {
    try {
    SecretKeySpec secu = new SecretKeySpec(key.getBytes(character),Algorithm);
    String value1 = value.trim();
    byte[] raw = StringToBytes(value1);
    System.out.println(raw);
    Cipher cipher = Cipher.getInstance(Algorithm);
    cipher.init(Cipher.DECRYPT_MODE, secu);
    System.out.println("}}}}}}}}}}}}}}");
    byte[] fina = cipher.doFinal(raw);
    String g = new String(fina,character);
    return g;
    }
    catch(Exception e) {
        System.out.println("dead");
    }
    return "";
}


public static byte[]  StringToBytes(String value1) {
    try {
    String[] strs = value1.split("");

    System.out.println(strs.toString());
    byte[] bytes = new byte[strs.length];
    System.out.println(bytes);
    for(int i=0;i<bytes.length; i++) {
        System.out.println("came to for loop");
         //bytes[i] = (byte) Integer.parseInt(strs[i]);
        //int s = Integer.parseInt(strs[i]);
        //System.out.println("ududfdheifdei" + s);
        bytes[i]=(byte) Integer.parseInt(strs[i]);
         System.out.println("printing decrypted value"+ bytes[i]);
    }
    return bytes;
    }
    catch(Exception e) {
        System.out.println("long dead");
    }
    return new byte[0];
}
Bashir
  • 2,057
  • 5
  • 19
  • 44
Vinod
  • 21
  • 3

1 Answers1

0

Looking at your code and reading a bit about cryptojs, I assume you are encrypting in AES/ECB/PKCS5Padding so adding the same tag to your decrypt in java should be enough:

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

You can also take a look at this tutorial and this one that should provide some insight in your problem.

Also, you can take a look at this answer to check how to improve your code. It looks like you could just have:

public static String decryption(String value, String key) throws Exception {
    try {
        SecretKeySpec secu = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8),"AES");
        byte[] raw = value.trim().getBytes(StandardCharsets.UTF_8);
        System.out.println(raw);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secu);
        System.out.println("}}}}}}}}}}}}}}");
        byte[] fina = cipher.doFinal(raw);
        return new String(fina,StandardCharsets.UTF_8);
    }
    catch(Exception e) {
        System.out.println("dead");
    }
    return "";
}

And remove the StringToBytes(String value1).

fjsv
  • 705
  • 10
  • 23