Java AES Decryption: random chars & message at the end

I have a problem with decrypting a message using AES. At the end when I expect a message, eg

ala123

Instead of that I receive sth like:

...6�b}7�k�8�vFP�8~%��_zժF��FW��O_e���ó������������ala123

The message I pass to encryption is built as:

  • cipher key is SHA-256 from AES_TOKEN
  • cipher IV is some characters, which are then stored in the message (at the beginnig)
  • decrypted message is wrapped up into Base64
  • The question is why at the end I eventually receive my expected message, but with a lot of rubbish chars at the beggining?

    My encryption code is:

    private static final String AES_TOKEN = "my_very_secret_token";
    
    // encrypted is base64 string
    public String decrypt(String encrypted) throws Exception {
        byte[] decrypted = Base64.getDecoder().decode(encrypted);
        return new String(aesDecrypt(decrypted), "UTF-8");
    }
    
    private byte[] aesDecrypt(byte[] message) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    
        byte[] token = MessageDigest.getInstance("SHA-256").digest(AES_TOKEN.getBytes());
        SecretKeySpec secretKey = new SecretKeySpec(token, "AES");
    
        IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(message, 16));
    
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        return cipher.doFinal(message);
    }
    

    It looks like you aren't removing the IV from the beginning of message after reading it in to iv . That would explain the garbage being at the start of the decrypted message.

    链接地址: http://www.djcxy.com/p/66302.html

    上一篇: Java AES

    下一篇: Java AES解密:最后的随机字符和消息