Initial bytes incorrect after Java AES/CBC decryption

前端 未结 10 2190
鱼传尺愫
鱼传尺愫 2020-11-22 12:47

What\'s wrong with the following example?

The problem is that the first part of the decrypted string is nonsense. However, the rest is fine, I get...

10条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 13:25

    It's often the good idea to rely on standard library provided solution:

    private static void stackOverflow15554296()
        throws
            NoSuchAlgorithmException, NoSuchPaddingException,        
            InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException
    {
    
        // prepare key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecretKey aesKey = keygen.generateKey();
        String aesKeyForFutureUse = Base64.getEncoder().encodeToString(
                aesKey.getEncoded()
        );
    
        // cipher engine
        Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    
        // cipher input
        aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] clearTextBuff = "Text to encode".getBytes();
        byte[] cipherTextBuff = aesCipher.doFinal(clearTextBuff);
    
        // recreate key
        byte[] aesKeyBuff = Base64.getDecoder().decode(aesKeyForFutureUse);
        SecretKey aesDecryptKey = new SecretKeySpec(aesKeyBuff, "AES");
    
        // decipher input
        aesCipher.init(Cipher.DECRYPT_MODE, aesDecryptKey);
        byte[] decipheredBuff = aesCipher.doFinal(cipherTextBuff);
        System.out.println(new String(decipheredBuff));
    }
    

    This prints "Text to encode".

    Solution is based on Java Cryptography Architecture Reference Guide and https://stackoverflow.com/a/20591539/146745 answer.

提交回复
热议问题