Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Test {
- public static String test = "Hallo, ich bin eine Test Nachricht!";
- public static void main( String[] args ) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
- byte[] initVector = new byte[16];
- new Random().nextBytes( initVector );
- IvParameterSpec ivParameterSpec = new IvParameterSpec( initVector );
- KeyGenerator keyGenerator = KeyGenerator.getInstance( "AES" );
- SecretKey key = keyGenerator.generateKey();
- Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5PADDING" );
- cipher.init( Cipher.ENCRYPT_MODE, key, ivParameterSpec );
- byte[] toEncrypt = test.getBytes();
- byte[] encrypted = new byte[0];
- for ( int i = 0; i < toEncrypt.length; i++ ) {
- byte b = toEncrypt[i];
- byte[] result = cipher.update( new byte[]{ b } );
- encrypted = ArrayUtils.concatByteArrays( encrypted, result );
- }
- byte[] finalEncryptResult = cipher.doFinal();
- encrypted = ArrayUtils.concatByteArrays( encrypted, finalEncryptResult );
- cipher.init( Cipher.DECRYPT_MODE, key, ivParameterSpec );
- byte[] decrypted = new byte[0];
- for ( int i = 0; i < encrypted.length; i++ ) {
- byte b = encrypted[i];
- byte[] result = cipher.update( new byte[]{ b } );
- decrypted = ArrayUtils.concatByteArrays( decrypted, result );
- }
- byte[] finalDecryptResult = cipher.doFinal();
- decrypted = ArrayUtils.concatByteArrays( decrypted, finalDecryptResult );
- String decryptedText = new String( decrypted );
- System.out.println( test );
- System.out.println( decryptedText );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement