· 7 years ago · Mar 16, 2018, 06:56 PM
1// Get the KeyGenerator
2KeyGenerator kgen = KeyGenerator.getInstance("AES");
3kgen.init(128); // 192 and 256 bits may not be available
4
5// Generate the secret key specs.
6SecretKey skey = kgen.generateKey();
7byte[] raw = skey.getEncoded();
8
9byte[] key = null; // TODO
10byte[] input = null; // TODO
11byte[] output = null;
12SecretKeySpec keySpec = null;
13keySpec = new SecretKeySpec(key, "AES");
14Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
15cipher.init(Cipher.ENCRYPT_MODE, keySpec);
16output = cipher.doFinal(input)
17
18SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
19KeySpec spec = new PBEKeySpec(password, salt, 1024, 256);
20SecretKey tmp = factory.generateSecret(spec);
21SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
22
23Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
24cipher.init(Cipher.ENCRYPT_MODE, secret);
25AlgorithmParameters params = cipher.getParameters();
26byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
27byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));
28
29Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
30cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
31String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8");
32System.out.println(plaintext);
33
34package sec.util;
35
36import java.io.InputStream;
37import java.io.OutputStream;
38import java.io.FileInputStream;
39import java.io.FileOutputStream;
40import java.security.MessageDigest;
41
42
43import javax.crypto.Cipher;
44import javax.crypto.SecretKey;
45import javax.crypto.spec.IvParameterSpec;
46import javax.crypto.CipherInputStream;
47import javax.crypto.CipherOutputStream;
48
49import java.security.spec.AlgorithmParameterSpec;
50import javax.crypto.KeyGenerator;
51import javax.crypto.spec.SecretKeySpec;
52
53public class Crypto {
54 Cipher ecipher;
55 Cipher dcipher;
56
57 /**
58 * Input a string that will be md5 hashed to create the key.
59 * @return void, cipher initialized
60 */
61
62 public Crypto(){
63 try{
64 KeyGenerator kgen = KeyGenerator.getInstance("AES");
65 kgen.init(128);
66 this.setupCrypto(kgen.generateKey());
67 } catch (Exception e) {
68 e.printStackTrace();
69 }
70 }
71 public Crypto(String key){
72 SecretKeySpec skey = new SecretKeySpec(getMD5(key), "AES");
73 this.setupCrypto(skey);
74 }
75
76 private void setupCrypto(SecretKey key){
77 // Create an 8-byte initialization vector
78 byte[] iv = new byte[]
79 {
80 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
81 };
82
83 AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
84 try
85 {
86 ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
87 dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
88
89 // CBC requires an initialization vector
90 ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
91 dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
92 }
93 catch (Exception e)
94 {
95 e.printStackTrace();
96 }
97 }
98
99 // Buffer used to transport the bytes from one stream to another
100 byte[] buf = new byte[1024];
101
102 public void encrypt(InputStream in, OutputStream out){
103 try {
104 // Bytes written to out will be encrypted
105 out = new CipherOutputStream(out, ecipher);
106
107 // Read in the cleartext bytes and write to out to encrypt
108 int numRead = 0;
109 while ((numRead = in.read(buf)) >= 0){
110 out.write(buf, 0, numRead);
111 }
112 out.close();
113 }
114 catch (java.io.IOException e){
115 e.printStackTrace();
116 }
117 }
118
119 /**
120 * Input is a string to encrypt.
121 * @return a Hex string of the byte array
122 */
123 public String encrypt(String plaintext){
124 try{
125 byte[] ciphertext = ecipher.doFinal(plaintext.getBytes("UTF-8"));
126 return this.byteToHex(ciphertext);
127 } catch (Exception e){
128 e.printStackTrace();
129 return null;
130 }
131
132 }
133
134 public void decrypt(InputStream in, OutputStream out){
135 try {
136 // Bytes read from in will be decrypted
137 in = new CipherInputStream(in, dcipher);
138
139 // Read in the decrypted bytes and write the cleartext to out
140 int numRead = 0;
141 while ((numRead = in.read(buf)) >= 0) {
142 out.write(buf, 0, numRead);
143 }
144 out.close();
145 } catch (java.io.IOException e) {
146 e.printStackTrace();
147 }
148 }
149
150 /**
151 * Input encrypted String represented in HEX
152 * @return a string decrypted in plain text
153 */
154 public String decrypt(String hexCipherText){
155 try{
156 String plaintext = new String(dcipher.doFinal(this.hexToByte(hexCipherText)), "UTF-8");
157 return plaintext;
158 } catch (Exception e){
159 e.printStackTrace();
160 return null;
161 }
162 }
163
164 public String decrypt(byte[] ciphertext){
165 try{
166 String plaintext = new String(dcipher.doFinal(ciphertext), "UTF-8");
167 return plaintext;
168 } catch (Exception e){
169 e.printStackTrace();
170 return null;
171 }
172 }
173
174 private static byte[] getMD5(String input){
175 try{
176 byte[] bytesOfMessage = input.getBytes("UTF-8");
177 MessageDigest md = MessageDigest.getInstance("MD5");
178 return md.digest(bytesOfMessage);
179 } catch (Exception e){
180 return null;
181 }
182 }
183
184 static final String HEXES = "0123456789ABCDEF";
185
186 public static String byteToHex( byte [] raw ) {
187 if ( raw == null ) {
188 return null;
189 }
190 final StringBuilder hex = new StringBuilder( 2 * raw.length );
191 for ( final byte b : raw ) {
192 hex.append(HEXES.charAt((b & 0xF0) >> 4))
193 .append(HEXES.charAt((b & 0x0F)));
194 }
195 return hex.toString();
196 }
197
198 public static byte[] hexToByte( String hexString){
199 int len = hexString.length();
200 byte[] ba = new byte[len / 2];
201 for (int i = 0; i < len; i += 2) {
202 ba[i/2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i+1), 16));
203 }
204 return ba;
205 }
206
207 public static void main(String args[]){
208 try {
209 String key = "I like cookies";
210 Crypto encrypter = new Crypto(key);
211 //Crypto encrypter = new Crypto();
212
213 // Encrypt
214 encrypter.encrypt(new FileInputStream("C:/temp/one.txt"),new FileOutputStream("C:/temp/Encrypted.txt"));
215 // Decrypt
216 encrypter.decrypt(new FileInputStream("c:/temp/Encrypted.txt"),new FileOutputStream("c:/temp/Decrypted.txt"));
217
218 String cyphertext = encrypter.encrypt("ABCDEFG");
219 System.out.println(cyphertext);
220
221 String plaintext = encrypter.decrypt(cyphertext);
222 System.out.println(plaintext);
223 }
224 catch (Exception e) {
225 e.printStackTrace();
226 }
227 }
228}
229
230SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
231Cipher cipher = Cipher.getInstance("AES");
232cipher.init(Cipher.ENCRYPT_MODE, key);
233byte[] encryptedBytes = cipher.doFinal(clearText.getBytes());
234
235byte[] raw = ...; // 32 bytes in size for a 256 bit key
236Key skey = new javax.crypto.spec.SecretKeySpec(raw, "AES");
237
238Cipher cipher = Cipher.getInstance("AES");
239cipher.init(Cipher.ENCRYPT_MODE, skey);
240byte[] encrypted = cipher.doFinal(plainText.getBytes());