1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.crypto.examples;
19
20 import java.io.ByteArrayInputStream;
21 import java.io.ByteArrayOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.nio.charset.StandardCharsets;
25 import java.util.Arrays;
26 import java.util.Properties;
27
28 import javax.crypto.spec.IvParameterSpec;
29 import javax.crypto.spec.SecretKeySpec;
30
31 import org.apache.commons.crypto.stream.CryptoInputStream;
32 import org.apache.commons.crypto.stream.CryptoOutputStream;
33 import org.apache.commons.crypto.utils.AES;
34
35
36
37
38 public class StreamExample {
39
40
41
42
43
44
45
46 private static byte[] getUTF8Bytes(final String input) {
47 return input.getBytes(StandardCharsets.UTF_8);
48 }
49
50 public static void main(final String []args) throws IOException {
51 final SecretKeySpec key = AES.newSecretKeySpec(getUTF8Bytes("1234567890123456"));
52 final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
53 final Properties properties = new Properties();
54 final String transform = AES.CBC_PKCS5_PADDING;
55
56 final String input = "hello world!";
57
58
59 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
60
61 try (CryptoOutputStream cos = new CryptoOutputStream(transform, properties, outputStream, key, iv)) {
62 cos.write(getUTF8Bytes(input));
63 cos.flush();
64 }
65
66
67 System.out.println("Encrypted: "+Arrays.toString(outputStream.toByteArray()));
68
69
70 final InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
71
72 try (CryptoInputStream cis = new CryptoInputStream(transform, properties, inputStream, key, iv)) {
73 final byte[] decryptedData = new byte[1024];
74 int decryptedLen = 0;
75 int i;
76 while ((i = cis.read(decryptedData, decryptedLen, decryptedData.length - decryptedLen)) > -1) {
77 decryptedLen += i;
78 }
79 System.out.println("Decrypted: "+new String(decryptedData, 0, decryptedLen, StandardCharsets.UTF_8));
80 }
81 }
82
83 }