· 6 years ago · Jul 17, 2019, 05:46 PM
1public class Test {
2
3 public static String test = "Hallo, ich bin eine Test Nachricht!";
4
5 public static void main( String[] args ) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
6 byte[] initVector = new byte[16];
7 new Random().nextBytes( initVector );
8 IvParameterSpec ivParameterSpec = new IvParameterSpec( initVector );
9 KeyGenerator keyGenerator = KeyGenerator.getInstance( "AES" );
10 SecretKey key = keyGenerator.generateKey();
11 Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5PADDING" );
12
13 cipher.init( Cipher.ENCRYPT_MODE, key, ivParameterSpec );
14 byte[] toEncrypt = test.getBytes();
15 byte[] encrypted = new byte[0];
16 for ( int i = 0; i < toEncrypt.length; i++ ) {
17 byte b = toEncrypt[i];
18 byte[] result = cipher.update( new byte[]{ b } );
19 encrypted = ArrayUtils.concatByteArrays( encrypted, result );
20 }
21 byte[] finalEncryptResult = cipher.doFinal();
22 encrypted = ArrayUtils.concatByteArrays( encrypted, finalEncryptResult );
23
24 cipher.init( Cipher.DECRYPT_MODE, key, ivParameterSpec );
25 byte[] decrypted = new byte[0];
26 for ( int i = 0; i < encrypted.length; i++ ) {
27 byte b = encrypted[i];
28 byte[] result = cipher.update( new byte[]{ b } );
29 decrypted = ArrayUtils.concatByteArrays( decrypted, result );
30 }
31 byte[] finalDecryptResult = cipher.doFinal();
32 decrypted = ArrayUtils.concatByteArrays( decrypted, finalDecryptResult );
33
34 String decryptedText = new String( decrypted );
35 System.out.println( test );
36 System.out.println( decryptedText );
37 }
38}