post icon

Encriptar / Desencriptar con Java en AES-256

Muchas veces necesitamos encriptar o desencriptar ficheros con nuestras aplicaciones, siempre el dilema es a la hora de elegir cual método utilizar para esto. Hoy día uno de los más seguros y complejos, pero sencillos de implementar es AES (Advanced Encryptation Standard) tambien conocido en la práctica como el algoritmo Rijndael (aunque estrictamente no son el mismo algoritmo) el cual “reemplazo” a su predecesor DES, y está catalogado entre los algoritmos de criptografía simétrica. AES tiene un tamaño de bloque fijo de 128 bits y tamaños de llave de 128, 192 ó 256 bits, en este caso mostraré un ejemplo de como implementar esto en Java con 256 bits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.NetworkInterface;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Enumeration;
 
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
/**
 * @author Vócali Sistemas Inteligentes
 */
public class AESCrypt {
	private static final String JCE_EXCEPTION_MESSAGE = "Por favor asegurate de tener instalado el "
		+ "\"Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files\" "
		+ "(http://java.sun.com/javase/downloads/index.jsp) de aqui puedes descargarlo.";
	private static final String RANDOM_ALG = "SHA1PRNG";
	private static final String DIGEST_ALG = "SHA-256";
	private static final String HMAC_ALG = "HmacSHA256";
	private static final String CRYPT_ALG = "AES";
	private static final String CRYPT_TRANS = "AES/CBC/NoPadding";
	private static final byte[] DEFAULT_MAC =
		{0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef};
	private static final int KEY_SIZE = 32;
	private static final int BLOCK_SIZE = 16;
	private static final int SHA_SIZE = 32;
 
	private final boolean DEBUG;
	private byte[] password;
	private Cipher cipher;
	private Mac hmac;
	private SecureRandom random;
	private MessageDigest digest;
	private IvParameterSpec ivSpec1;
	private SecretKeySpec aesKey1;
	private IvParameterSpec ivSpec2;
	private SecretKeySpec aesKey2;
 
	/*******************
	 * PRIVATE METHODS *
	 *******************/
 
	/**
	 * Prints a debug message on standard output if DEBUG mode is turned on.
	 */
	protected void debug(String message) {
		if (DEBUG) {
			System.out.println("[DEBUG] " + message);
		}
	}
 
	/**
	 * Prints a debug message on standard output if DEBUG mode is turned on.
	 */
	protected void debug(String message, byte[] bytes) {
		if (DEBUG) {
			StringBuilder buffer = new StringBuilder("[DEBUG] ");
			buffer.append(message);
			buffer.append("[");
			for (int i = 0; i < bytes.length; i++) {
				buffer.append(bytes[i]);
				buffer.append(i < bytes.length - 1 ? ", " : "]");
			}
			System.out.println(buffer.toString());
		}
	}
 
	/**
	 * Generates a pseudo-random byte array.
	 * @return pseudo-random byte array of <tt>len</tt> bytes.
	 */
	protected byte[] generateRandomBytes(int len) {
		byte[] bytes = new byte[len];
		random.nextBytes(bytes);
		return bytes;
	}
 
	/**
	 * SHA256 digest over given byte array and random bytes.
 
	 * <tt>bytes.length</tt> * <tt>num</tt> random bytes are added to the digest.
	 *
 
	 * The generated hash is saved back to the original byte array.
 
	 * Maximum array size is {@link #SHA_SIZE} bytes.
	 */
	protected void digestRandomBytes(byte[] bytes, int num) {
		assert bytes.length &lt;= SHA_SIZE;
 
		digest.reset();
		digest.update(bytes);
		for (int i = 0; i &lt; num; i++) {
			random.nextBytes(bytes);
			digest.update(bytes);
		}
		System.arraycopy(digest.digest(), 0, bytes, 0, bytes.length);
	}
 
	/**
	 * Generates a pseudo-random IV based on time and this computer's MAC.
	 *
 
	 * This IV is used to crypt IV 2 and AES key 2 in the file.
	 * @return IV.
	 */
	protected byte[] generateIv1() {
		byte[] iv = new byte[BLOCK_SIZE];
		long time = System.currentTimeMillis();
		byte[] mac = null;
		try {
			Enumeration ifaces = NetworkInterface.getNetworkInterfaces();
			while (mac == null &amp;&amp; ifaces.hasMoreElements()) {
				mac = ifaces.nextElement().getHardwareAddress();
			}
		} catch (Exception e) {
			// Ignore.
		}
		if (mac == null) {
			mac = DEFAULT_MAC;
		}
 
		for (int i = 0; i &lt; 8; i++) { 			iv[i] = (byte) (time &gt;&gt; (i * 8));
		}
		System.arraycopy(mac, 0, iv, 8, mac.length);
		digestRandomBytes(iv, 256);
		return iv;
	}
 
	/**
	 * Generates an AES key starting with an IV and applying the supplied user password.
	 *
 
	 * This AES key is used to crypt IV 2 and AES key 2.
	 * @return AES key of {@link #KEY_SIZE} bytes.
	 */
	protected byte[] generateAESKey1(byte[] iv, byte[] password) {
		byte[] aesKey = new byte[KEY_SIZE];
		System.arraycopy(iv, 0, aesKey, 0, iv.length);
		for (int i = 0; i &lt; 8192; i++) {
			digest.reset();
			digest.update(aesKey);
			digest.update(password);
			aesKey = digest.digest();
		}
		return aesKey;
	}
 
	/**
	 * Generates the random IV used to crypt file contents.
	 * @return IV 2.
	 */
	protected byte[] generateIV2() {
		byte[] iv = generateRandomBytes(BLOCK_SIZE);
		digestRandomBytes(iv, 256);
		return iv;
	}
 
	/**
	 * Generates the random AES key used to crypt file contents.
	 * @return AES key of {@link #KEY_SIZE} bytes.
	 */
	protected byte[] generateAESKey2() {
		byte[] aesKey = generateRandomBytes(KEY_SIZE);
		digestRandomBytes(aesKey, 32);
		return aesKey;
	}
 
	/**
	 * Utility method to read bytes from a stream until the given array is fully filled.
	 * @throws IOException if the array can't be filled.
	 */
	protected void readBytes(InputStream in, byte[] bytes) throws IOException {
		if (in.read(bytes) != bytes.length) {
			throw new IOException("Fin de archivo inesperado");
		}
	}
 
	/**************
	 * PUBLIC API *
	 **************/
 
	/**
	 * Builds an object to encrypt or decrypt files with the given password.
	 * @throws GeneralSecurityException if the platform does not support the required cryptographic methods.
	 * @throws UnsupportedEncodingException if UTF-16 encoding is not supported.
	 */
	public AESCrypt(String password) throws GeneralSecurityException, UnsupportedEncodingException {
		this(false, password);
	}
 
	/**
	 * Builds an object to encrypt or decrypt files with the given password.
	 * @throws GeneralSecurityException if the platform does not support the required cryptographic methods.
	 * @throws UnsupportedEncodingException if UTF-16 encoding is not supported.
	 */
	public AESCrypt(boolean debug, String password) throws GeneralSecurityException, UnsupportedEncodingException {
		try {
			DEBUG = debug;
			setPassword(password);
			random = SecureRandom.getInstance(RANDOM_ALG);
			digest = MessageDigest.getInstance(DIGEST_ALG);
			cipher = Cipher.getInstance(CRYPT_TRANS);
			hmac = Mac.getInstance(HMAC_ALG);
		} catch (GeneralSecurityException e) {
			throw new GeneralSecurityException(JCE_EXCEPTION_MESSAGE, e);
		}
	}
 
	/**
	 * Changes the password this object uses to encrypt and decrypt.
	 * @throws UnsupportedEncodingException if UTF-16 encoding is not supported.
	 */
	public void setPassword(String password) throws UnsupportedEncodingException {
		this.password = password.getBytes("UTF-16LE");
		debug("Password usado: ", this.password);
	}
 
	/**
	 * The file at <tt>fromPath</tt> is encrypted and saved at <tt>toPath</tt> location.
	 *
 
	 * <tt>version</tt> can be either 1 or 2.
	 * @throws IOException when there are I/O errors.
	 * @throws GeneralSecurityException if the platform does not support the required cryptographic methods.
	 */
	public void encrypt(int version, String fromPath, String toPath)
	throws IOException, GeneralSecurityException {
		InputStream in = null;
		OutputStream out = null;
		byte[] text = null;
		try {
			ivSpec1 = new IvParameterSpec(generateIv1());
			aesKey1 = new SecretKeySpec(generateAESKey1(ivSpec1.getIV(), password), CRYPT_ALG);
			ivSpec2 = new IvParameterSpec(generateIV2());
			aesKey2 = new SecretKeySpec(generateAESKey2(), CRYPT_ALG);
			debug("IV1: ", ivSpec1.getIV());
			debug("AES1: ", aesKey1.getEncoded());
			debug("IV2: ", ivSpec2.getIV());
			debug("AES2: ", aesKey2.getEncoded());
 
			in = new FileInputStream(fromPath);
			debug("Abierto para la lectura: " + fromPath);
			out = new FileOutputStream(toPath);
			debug("Abierto para la escritura: " + toPath);
 
			out.write("AES".getBytes("UTF-8"));	// Heading.
			out.write(version);	// Version.
			out.write(0);	// Reserved.
			if (version == 2) {	// No extensions.
				out.write(0);
				out.write(0);
			}
			out.write(ivSpec1.getIV());	// Initialization Vector.
 
			text = new byte[BLOCK_SIZE + KEY_SIZE];
			cipher.init(Cipher.ENCRYPT_MODE, aesKey1, ivSpec1);
			cipher.update(ivSpec2.getIV(), 0, BLOCK_SIZE, text);
			cipher.doFinal(aesKey2.getEncoded(), 0, KEY_SIZE, text, BLOCK_SIZE);
			out.write(text);	// Crypted IV and key.
			debug("IV2 + AES2 ciphertext: ", text);
 
			hmac.init(new SecretKeySpec(aesKey1.getEncoded(), HMAC_ALG));
			text = hmac.doFinal(text);
			out.write(text);	// HMAC from previous cyphertext.
			debug("HMAC1: ", text);
 
			cipher.init(Cipher.ENCRYPT_MODE, aesKey2, ivSpec2);
			hmac.init(new SecretKeySpec(aesKey2.getEncoded(), HMAC_ALG));
			text = new byte[BLOCK_SIZE];
			int len, last = 0;
			while ((len = in.read(text)) &gt; 0) {
				cipher.update(text, 0, BLOCK_SIZE, text);
				hmac.update(text);
				out.write(text);	// Crypted file data block.
				last = len;
			}
			last &amp;= 0x0f;
			out.write(last);	// Last block size mod 16.
			debug("Último bloque de tamaño mod 16: " + last);
 
			text = hmac.doFinal();
			out.write(text);	// HMAC from previous cyphertext.
			debug("HMAC2: ", text);
		} catch (InvalidKeyException e) {
			throw new GeneralSecurityException(JCE_EXCEPTION_MESSAGE, e);
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}
 
	/**
	 * The file at <tt>fromPath</tt> is decrypted and saved at <tt>toPath</tt> location.
	 *
 
	 * Source file can be encrypted using version 1 or 2 of aescrypt.
	 * @throws IOException when there are I/O errors.
	 * @throws GeneralSecurityException if the platform does not support the required cryptographic methods.
	 */
	public void decrypt(String fromPath, String toPath)
	throws IOException, GeneralSecurityException {
		InputStream in = null;
		OutputStream out = null;
		byte[] text = null, backup = null;
		long total = 3 + 1 + 1 + BLOCK_SIZE + BLOCK_SIZE + KEY_SIZE + SHA_SIZE + 1 + SHA_SIZE;
		int version;
		try {
			in = new FileInputStream(fromPath);
			debug("Opened for reading: " + fromPath);
			out = new FileOutputStream(toPath);
			debug("Opened for writing: " + toPath);
 
			text = new byte[3];
			readBytes(in, text);	// Heading.
			if (!new String(text, "UTF-8").equals("AES")) {
				throw new IOException("Encabezado de archivo no válido");
			}
 
			version = in.read();	// Version.
			if (version &lt; 1 || version &gt; 2) {
				throw new IOException("El número de versión no compatible: " + version);
			}
			debug("Version: " + version);
 
			in.read();	// Reserved.
 
			if (version == 2) {	// Extensions.
				text = new byte[2];
				int len;
				do {
					readBytes(in, text);
					len = ((0xff &amp; (int) text[0]) &lt;&lt; 8) | (0xff &amp; (int) text[1]); 					if (in.skip(len) != len) { 						throw new IOException("Fin inesperado de la extensión"); 					} 					total += 2 + len; 					debug("Skipped extension sized: " + len); 				} while (len != 0); 			} 			 			text = new byte[BLOCK_SIZE]; 			readBytes(in, text);	// Initialization Vector. 			ivSpec1 = new IvParameterSpec(text); 			aesKey1 = new SecretKeySpec(generateAESKey1(ivSpec1.getIV(), password), CRYPT_ALG); 			debug("IV1: ", ivSpec1.getIV()); 			debug("AES1: ", aesKey1.getEncoded()); 			 			cipher.init(Cipher.DECRYPT_MODE, aesKey1, ivSpec1); 			backup = new byte[BLOCK_SIZE + KEY_SIZE]; 			readBytes(in, backup);	// IV and key to decrypt file contents. 			debug("IV2 + AES2 ciphertext: ", backup); 			text = cipher.doFinal(backup); 			ivSpec2 = new IvParameterSpec(text, 0, BLOCK_SIZE); 			aesKey2 = new SecretKeySpec(text, BLOCK_SIZE, KEY_SIZE, CRYPT_ALG); 			debug("IV2: ", ivSpec2.getIV()); 			debug("AES2: ", aesKey2.getEncoded()); 			 			hmac.init(new SecretKeySpec(aesKey1.getEncoded(), HMAC_ALG)); 			backup = hmac.doFinal(backup); 			text = new byte[SHA_SIZE]; 			readBytes(in, text);	// HMAC and authenticity test. 			if (!Arrays.equals(backup, text)) { 				throw new IOException("El mensaje ha sido alterado o contraseña incorrecta"); 			} 			debug("HMAC1: ", text); 			 			total = new File(fromPath).length() - total;	// Payload size. 			if (total % BLOCK_SIZE != 0) { 				throw new IOException("Archivo de entrada está dañado"); 			} 			if (total == 0) {	// Hack: empty files won't enter block-processing for-loop below.  				in.read();	// Skip last block size mod 16. 			} 			debug("Payload size: " + total); 			cipher.init(Cipher.DECRYPT_MODE, aesKey2, ivSpec2); 			hmac.init(new SecretKeySpec(aesKey2.getEncoded(), HMAC_ALG)); 			backup = new byte[BLOCK_SIZE]; 			text = new byte[BLOCK_SIZE]; 			for (int block = (int) (total / BLOCK_SIZE); block &gt; 0; block--) {
				int len = BLOCK_SIZE;
				if (in.read(backup, 0, len) != len) {	// Cyphertext block.
					throw new IOException("Fin inesperado de contenido del archivo");
				}
				cipher.update(backup, 0, len, text);
				hmac.update(backup, 0, len);
				if (block == 1) {
					int last = in.read();	// Last block size mod 16.
					debug("Last block size mod 16: " + last);
					len = (last &gt; 0 ? last : BLOCK_SIZE);
				}
				out.write(text, 0, len);
			}
			out.write(cipher.doFinal());
 
			backup = hmac.doFinal();
			text = new byte[SHA_SIZE];
			readBytes(in, text);	// HMAC and authenticity test.
			if (!Arrays.equals(backup, text)) {
				throw new IOException("El mensaje ha sido alterado o contraseña incorrecta");
			}
			debug("HMAC2: ", text);
		} catch (InvalidKeyException e) {
			throw new GeneralSecurityException(JCE_EXCEPTION_MESSAGE, e);
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}
 
	public static void main(String[] args) {
		try {
			if (args.length &lt; 4) {
				System.out.println("AESCrypt e|d password fromPath toPath");
				return;
			}
			AESCrypt aes = new AESCrypt(true, args[1]);
			switch (args[0].charAt(0)) {
			case 'e':
				aes.encrypt(2, args[2], args[3]);
				break;
			case 'd':
				aes.decrypt(args[2], args[3]);
				break;
			default:
				System.out.println("Operación no válida: debe ser (e)ncrypt o (d)ecrypt.");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

@author Vacali Sistemas Inteligentes

Comentarios desde Facebook:

  1. Jonathan Mozilla Firefox Linux
    28 octubre 2012 at 20:30 #

    Los navegadores distorsionan tu codigo seria bueno que le pusieras un link de descarga o lo compartieras vía dropbox para chekarlo

  2. Jotremar SPAIN Internet Explorer Windows
    5 octubre 2011 at 10:41 #

    Corrección a generatiIv1 (123):

    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
  3. Birguei SPAIN Mozilla Firefox Windows
    4 abril 2011 at 21:47 #

    acabo de ver esto en la red… manos a la obra xDD no conocia el segurode vida del colega, pero seré el primero en rrevvennttarrlo ^^

Responder