Java 256-bit AES Password-Based Encryption

后端 未结 9 1375
名媛妹妹
名媛妹妹 2020-11-21 05:22

I need to implement 256 bit AES encryption, but all the examples I have found online use a \"KeyGenerator\" to generate a 256 bit key, but I would like to use my own passkey

9条回答
  •  遥遥无期
    2020-11-21 05:55

    Use this class for encryption. It works.

    public class ObjectCrypter {
    
    
        public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] mes) 
                throws NoSuchAlgorithmException,
                NoSuchPaddingException,
                InvalidKeyException,
                InvalidAlgorithmParameterException,
                IllegalBlockSizeException,
                BadPaddingException, IOException {
    
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
            SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = null;
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
            return  cipher.doFinal(mes);
    
        }
    
        public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] bytes) 
                throws NoSuchAlgorithmException,
                NoSuchPaddingException,
                InvalidKeyException,
                InvalidAlgorithmParameterException,
                IllegalBlockSizeException,
                BadPaddingException, IOException, ClassNotFoundException {
    
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
            SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
            return  cipher.doFinal(bytes);
    
        }
    }
    

    And these are ivBytes and a random key;

    String key = "e8ffc7e56311679f12b6fc91aa77a5eb";
    
    byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    keyBytes = key.getBytes("UTF-8");
    

提交回复
热议问题