· 9 years ago · Sep 29, 2016, 07:42 AM
1import java.security.Key;
2import java.security.SecureRandom;
3
4import javax.crypto.Cipher;
5import javax.crypto.KeyGenerator;
6import javax.crypto.SecretKey;
7import javax.crypto.spec.IvParameterSpec;
8
9import org.apache.commons.codec.binary.Base64;
10
11public class CryptoHelper {
12
13 public static void main( String [] args ) throws Exception {
14
15 CryptoHelper crypto = new CryptoHelper();
16
17 String plaintext = "This is a good secret.";
18 System.out.println( plaintext );
19
20 String ciphertext = crypto.encrypt( plaintext );
21 System.out.println( ciphertext );
22
23 String decrypted = crypto.decrypt( ciphertext );
24 System.out.println( decrypted );
25
26 }
27
28 public String encrypt( String plaintext ) throws Exception {
29 return encrypt( generateIV(), plaintext );
30 }
31
32 public String encrypt( byte [] iv, String plaintext ) throws Exception {
33
34 byte [] decrypted = plaintext.getBytes();
35 byte [] encrypted = encrypt( iv, decrypted );
36
37 StringBuilder ciphertext = new StringBuilder();
38
39 ciphertext.append( Base64.encodeBase64String( iv ) );
40 ciphertext.append( ":" );
41 ciphertext.append( Base64.encodeBase64String( encrypted ) );
42
43 return ciphertext.toString();
44
45 }
46
47 public String decrypt( String ciphertext ) throws Exception {
48 String [] parts = ciphertext.split( ":" );
49 byte [] iv = Base64.decodeBase64( parts[0] );
50 byte [] encrypted = Base64.decodeBase64( parts[1] );
51 byte [] decrypted = decrypt( iv, encrypted );
52 return new String( decrypted );
53 }
54
55 private Key key;
56
57 public CryptoHelper( Key key ) {
58 this.key = key;
59 }
60
61 public CryptoHelper() throws Exception {
62 this( generateSymmetricKey() );
63 }
64
65 public Key getKey() {
66 return key;
67 }
68
69 public void setKey( Key key ) {
70 this.key = key;
71 }
72
73 public static byte [] generateIV() {
74 SecureRandom random = new SecureRandom();
75 byte [] iv = new byte [16];
76 random.nextBytes( iv );
77 return iv;
78 }
79
80 public static Key generateSymmetricKey() throws Exception {
81 KeyGenerator generator = KeyGenerator.getInstance( "AES" );
82 SecretKey key = generator.generateKey();
83 return key;
84 }
85
86 public byte [] encrypt( byte [] iv, byte [] plaintext ) throws Exception {
87 Cipher cipher = Cipher.getInstance( key.getAlgorithm() + "/CBC/PKCS5Padding" );
88 cipher.init( Cipher.ENCRYPT_MODE, key, new IvParameterSpec( iv ) );
89 return cipher.doFinal( plaintext );
90 }
91
92 public byte [] decrypt( byte [] iv, byte [] ciphertext ) throws Exception {
93 Cipher cipher = Cipher.getInstance( key.getAlgorithm() + "/CBC/PKCS5Padding" );
94 cipher.init( Cipher.DECRYPT_MODE, key, new IvParameterSpec( iv ) );
95 return cipher.doFinal( ciphertext );
96 }
97
98}