· 9 years ago · Aug 28, 2016, 06:54 PM
1public class AES2 {
2 private static final String algo = "AES/CBC/PKCS5Padding";
3 private static final byte[] keyValue =
4 new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't','S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
5
6 public static String encrypt(String Data) throws Exception {
7
8 //KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
9 //KeyGen.init(128);
10
11 //SecretKey SecKey = KeyGen.generateKey();
12 Key key=generateKey();
13
14 //generar IV
15 byte[] iv = new byte[16];
16 SecureRandom random = new SecureRandom();
17 random.nextBytes(iv);
18 IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
19
20 //cifrar
21 Cipher c = Cipher.getInstance(algo);
22 c.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
23
24 byte[] encVal = c.doFinal(Data.getBytes());
25 String encryptedValue = new BASE64Encoder().encode(encVal);
26 return encryptedValue;
27 }
28
29 public static String decrypt(String encryptedData) throws Exception {
30 Key key = generateKey();
31
32 byte[] iv = new byte[16];
33 SecureRandom random = new SecureRandom();
34 random.nextBytes(iv);
35 IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
36
37 Cipher c = Cipher.getInstance(algo);
38 c.init(Cipher.DECRYPT_MODE, key,ivParameterSpec);
39
40 byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
41 byte[] decValue = c.doFinal(decordedValue);
42 String decryptedValue = new String(decValue);
43 return decryptedValue;
44 }
45
46 private static Key generateKey() throws Exception {
47 Key key = new SecretKeySpec(keyValue, "AES");
48 return key;
49}
50}
51
52Main class:
53
54public class aesMain {
55
56 /**
57 * @param args the command line arguments
58 */
59 public static void main(String[] args) throws Exception {
60
61 String texto = "hola mama";
62 String encryptedText=AES2.encrypt(texto);
63 String decryptedText=AES2.decrypt(encryptedText);
64
65
66 System.out.println("Plain text : " + texto);
67 System.out.println("Encrypted Text : " + encryptedText);
68 System.out.println("Decrypted Text : " + decryptedText);
69 }
70
71}