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
34
35
36
37 public class StreamExample {
38
39 public static void main(final String []args) throws IOException {
40 final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("1234567890123456"),"AES");
41 final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
42 final Properties properties = new Properties();
43 final String transform = "AES/CBC/PKCS5Padding";
44
45 final String input = "hello world!";
46
47
48 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
49
50 try (CryptoOutputStream cos = new CryptoOutputStream(transform, properties, outputStream, key, iv)) {
51 cos.write(getUTF8Bytes(input));
52 cos.flush();
53 }
54
55
56 System.out.println("Encrypted: "+Arrays.toString(outputStream.toByteArray()));
57
58
59 final InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
60
61 try (CryptoInputStream cis = new CryptoInputStream(transform, properties, inputStream, key, iv)) {
62 final byte[] decryptedData = new byte[1024];
63 int decryptedLen = 0;
64 int i;
65 while ((i = cis.read(decryptedData, decryptedLen, decryptedData.length - decryptedLen)) > -1) {
66 decryptedLen += i;
67 }
68 System.out.println("Decrypted: "+new String(decryptedData, 0, decryptedLen, StandardCharsets.UTF_8));
69 }
70 }
71
72
73
74
75
76
77
78 private static byte[] getUTF8Bytes(final String input) {
79 return input.getBytes(StandardCharsets.UTF_8);
80 }
81
82 }