public static byte [ ] encryptAsBytes ( final SecretKey secretKey , final String plainText ) throws Exception { final byte [ ] clean = plainText . getBytes ( ) ; // Generating IV int ivSize = 16 ; final byte [ ] iv = new byte [ ivSize ] ; final SecureRandom random = new SecureRandom ( ) ; random . nextBytes ( iv ) ; final IvParameterSpec ivParameterSpec = new IvParameterSpec ( iv ) ; // Encrypt final Cipher cipher = Cipher . getInstance ( "AES/CBC/PKCS5Padding" ) ; cipher . init ( Cipher . ENCRYPT_MODE , secretKey , ivParameterSpec ) ; final byte [ ] encrypted = cipher . doFinal ( clean ) ; // Combine IV and encrypted parts final byte [ ] encryptedIVAndText = new byte [ ivSize + encrypted . length ] ; System . arraycopy ( iv , 0 , encryptedIVAndText , 0 , ivSize ) ; System . arraycopy ( encrypted , 0 , encryptedIVAndText , ivSize , encrypted . length ) ; return encryptedIVAndText ; }
Encrypts the specified plainText using AES - 256 .