0

I want to do encryption in Javascript and decrypt it in Java but it kept getting me bad padding exception. I have no idea what to do.

Here's the code

  key: string;
  iv:string
  keySize:256
  iterations:1000;

  constructor() { }

  encrypt(keys, passw){
    var salt = "12345678123456781234567812345678"
    // var salt = CryptoJS.lib.WordArray.random(128/8);
    
    console.log(passw)
    console.log(salt)

    var key = CryptoJS.PBKDF2(passw, salt, {
      keySize: this.keySize/32,
      iterations: this.iterations
    });

    var iv = CryptoJS.lib.WordArray.random(128/8);

    var encrypted = CryptoJS.AES.encrypt(keys, key,{
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })

    var transitmessage = salt.toString() +  iv.toString() + encrypted.toString()
    console.log("tl: " + transitmessage.length)
    return transitmessage;
  }
public String decrypt(String encryptText) throws Exception {
        try {
            System.out.println("begin: " + encryptText);
            
            String saltt = encryptText.substring(0,32);
            
            String iv = encryptText.substring(32,64);
            String encText = encryptText.substring(64);
            System.out.println("enc: " + encText);
            
            byte[] encryptTextBytes = Base64.getDecoder().decode(encText);
        
            System.out.println("encbytes: " + encryptTextBytes);
            
            SecretKeySpec key;
            try {
                SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(this.secretKeyFactoryAlgorithm);
                KeySpec keySpec = new PBEKeySpec(TOKEN.toCharArray(), hex(saltt), this.pwdIterations, this.keySize);
                SecretKey secretKeyTemp = secretKeyFactory.generateSecret(keySpec);
                key = new SecretKeySpec(secretKeyTemp.getEncoded(),keyAlgorithm);
            }catch(NoSuchAlgorithmException | InvalidKeySpecException e) {
                e.printStackTrace();
                return null;
            }
        
            //decrypt the message
            Cipher cipher = Cipher.getInstance(this.encryptAlgorithm);
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(hex(iv)));
            
            byte[] decryptTextBytes = null;
            try {
                decryptTextBytes = cipher.doFinal(encryptTextBytes);
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
            
            String text = new String(decryptTextBytes);
            System.out.println("text: " + text);
            return text;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

The error was like this : javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

The iv : [0000: A7 18 56 5D 79 22 2D C8 3F 3A 62 A0 BE 22 A1 D2 ..V]y"-.?:b..".. ]

Please help me, i need to finish it quickly. Thanks.

dnault
  • 8,340
  • 1
  • 34
  • 53
archaenjel
  • 25
  • 2
  • 7
  • Are you sure the JS encode the message into Base64. It seems not. – kelalaka Sep 28 '20 at 19:36
  • 1
    `hex(saltt)` looks incorrect – Artjom B. Sep 28 '20 at 19:38
  • i follow the code from here somehow https://www.devglan.com/corejava/aes-encryption-javascript-and-decryption-in-java – archaenjel Sep 28 '20 at 19:45
  • i've tried to change it to KeySpec keySpec = new PBEKeySpec(TOKEN.toCharArray(), saltt.getBytes(), this.pwdIterations, this.keySize); but it still gave me the same error tho @ArtjomB. – archaenjel Sep 28 '20 at 19:48
  • 2
    You already know that everyone here on SO is assisting in our free time ? If you need a "quickly" help kindly order a freelancer and give him a deadline for your request. Another way could be to edit your question and provide some sample data (keys, passw and transitmessage) that was used on js-side and your edited Java code that show how those data are used as input on Java-side. – Michael Fehr Sep 28 '20 at 20:56
  • 1
    It would be easier for someone to reproduce the problem if you share the `encryptText` as well as all the Java code you're using to decrypt it. See https://stackoverflow.com/help/minimal-reproducible-example – dnault Sep 28 '20 at 21:18
  • 3
    @kelalaka: crypto-js.AES.encrypt returns a CipherParams object whose default formatter is base64. (More exactly it is OpenSSLFormatter which is base64 of just the ciphertext if no salt is used, or of magic Salted__ plus salt plus ciphertext if salt is used, matching variously ancient and sane versions of `openssl enc -$cipher -a`.) OP: **with hex(saltt) changed to saltt.getBytes() and all the hidden references replaced by correct values, your code works for me**. Please make your example a _reproducible_ example -- one that a Stack reader can actually compile and run. – dave_thompson_085 Sep 29 '20 at 01:42

0 Answers0