· 6 years ago · Aug 21, 2019, 05:00 AM
1import java.io.UnsupportedEncodingException;
2import java.security.MessageDigest;
3import java.security.NoSuchAlgorithmException;
4import java.util.Arrays;
5import java.util.Base64;
6
7import javax.crypto.Cipher;
8import javax.crypto.spec.SecretKeySpec;
9
10/**
11 * Ejemplo para aes
12 *
13 * @author Camilo Contreras - Banco Consorcio
14 *
15 */
16public class AES {
17
18 /***********************************************/
19 public static void main(String[] args) {
20 final String secretKey = "9`<S3 0G92l22>5dHL\"x26|90160I@S#0'94}y!m(2464208aSEy2Ln1499ay*3^09\\5~mNn47P4)4^ :GJ42-C2q193S4qZ1c,58ZKfImHQ70z$074K0{5SdZP*OA4v";
21
22 String originalString = "howtodoinjava.com";
23 System.out.println("Original: " + originalString);
24
25 String encryptedString = AES.encrypt(originalString, secretKey);
26 System.out.println("Encriptado: " + encryptedString);
27
28 String decryptedString = AES.decrypt(encryptedString, secretKey);
29 System.out.println("Desencriptado: " + decryptedString);
30
31 }
32
33 /***********************************************/
34
35 private static SecretKeySpec secretKey;
36 private static byte[] key;
37
38 /**
39 * Setear key
40 *
41 * @param myKey
42 */
43 public static void setKey(String myKey) {
44 MessageDigest sha = null;
45 try {
46 key = myKey.getBytes("UTF-8");
47 sha = MessageDigest.getInstance("SHA-1");
48 key = sha.digest(key);
49 key = Arrays.copyOf(key, 16);
50 secretKey = new SecretKeySpec(key, "AES");
51 } catch (NoSuchAlgorithmException e) {
52 e.printStackTrace();
53 } catch (UnsupportedEncodingException e) {
54 e.printStackTrace();
55 }
56 }
57
58 /**
59 * Encriptar
60 *
61 * @param strToEncrypt
62 * @param secret
63 * @return
64 */
65 public static String encrypt(String strToEncrypt, String secret) {
66 try {
67 setKey(secret);
68 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
69 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
70 return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
71 } catch (Exception e) {
72 System.out.println("Error while encrypting: " + e.toString());
73 }
74 return null;
75 }
76
77 /**
78 * Desencriptar
79 *
80 * @param strToDecrypt
81 * @param secret
82 * @return
83 */
84 public static String decrypt(String strToDecrypt, String secret) {
85 try {
86 setKey(secret);
87 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
88 cipher.init(Cipher.DECRYPT_MODE, secretKey);
89 return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
90 } catch (Exception e) {
91 System.out.println("Error while decrypting: " + e.toString());
92 }
93 return null;
94 }
95}