0

I am trying to send an encrypted username from my React frontend to my Spring Boot backend. My frontend looks like this:

const secretKey = "mySecretKey";
        const encrypted = CryptoJS.AES.encrypt(username, secretKey).toString();
        setHashedUsername(encrypted);

Which is then sent through a GET request in the backend. The backend looks like this:

public String decryptData(String encryptedUsername) throws NoSuchAlgorithmException {
        try {
            byte[] keyBytes = secretKey.getBytes("UTF-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

            byte[] decryptedBytes =        cipher.doFinal(Base64.getDecoder().decode(encryptedUsername));

          
            return new String(decryptedBytes,"UTF-8");
        } catch (Exception e) {
            return "Error";
        }
    }

I always get the following error while debugging: Cipher.AES/ECB/PKCS5Padding, mode: not initialized, algorithm from: (no provider)

I tried to replace the "AES/ECB/PKCS5Padding" transformation with other variations, hoping that the original one didn't match the requirements from the frontend, but all failed. Then I also tried the following solution: What are the AES parameters used and steps performed internally by crypto-js while encrypting a message with a password? , but still didn't work. What could be the problem?

  • That's the full extent of the error? You don't know what line in your code is generating the exception? – President James K. Polk Aug 25 '23 at 12:51
  • It's from the following line: Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); – rubyzli Aug 25 '23 at 12:53
  • `PKCS#5 padding [..] has only been defined for block ciphers that use a 64-bit (8-byte) block size.` https://en.wikipedia.org/wiki/Padding_(cryptography) But AES has a block size of 128 bit. Therefore you have to use PKCS#7 padding which is identical to PKCS#5 padding, just that it supports a block size of 128bit. => use `AES/ECB/PKCS7Padding` – Robert Aug 25 '23 at 13:25
  • 1
    @Robert: This is effectively false. In Java "PKCS5Padding" really means PKCS7 padding. – President James K. Polk Aug 25 '23 at 14:20
  • `I am trying to send an encrypted username from my React frontend to my Spring Boot backend.` Just use HTTPS. Having encryption with a password/key available to the client (and all the stack) increases complexity, but not security. Definitely not with the ECB mode either! Next - are you sure the `encrypted` username is base64 encoded? – gusto2 Aug 28 '23 at 17:20

0 Answers0