· 6 years ago · Jun 27, 2019, 05:36 AM
1Encrypt, decrypt data in java:
2
3package TEST.Encryption;
4
5import java.security.MessageDigest;
6import java.security.NoSuchAlgorithmException;
7import java.security.spec.KeySpec;
8
9import javax.crypto.Cipher;
10import javax.crypto.SecretKey;
11import javax.crypto.SecretKeyFactory;
12import javax.crypto.spec.DESKeySpec;
13import javax.crypto.spec.DESedeKeySpec;
14
15import sun.misc.BASE64Decoder;
16import sun.misc.BASE64Encoder;
17
18/**
19 * Use encryption algorithm with DESede Cipher and Base64/MD5 Base64 encryption for Java.
20 */
21public class Encryption {
22
23 /*
24 * Output:
25 * Encrypted Data : fxqeTkmii3BzPEEXTlhfMKeC4AZRAaBV1gAAPiROEyo=
26 * Vl3P0kxGTj5phbg+S9C/mQ==
27 * Decrypted Data: MyData=1&endt=1354221317
28 */
29
30 /**
31 * Serial version id.
32 */
33 private static final long serialVersionUID = 1L;
34
35 private static final String ENCRYPTION_KEY = "YNYNWKLIJLKJFJALJLAJFJFJY";
36 private static final String DIGEST_KEY = "UHUWKJLSJDKLFJSKJDFJKSLJY";
37
38 public static void main(final String [] args) {
39 System.out.println("Running");
40 final Encryption e = new Encryption();
41 String o [] = e.encrypt("MyData=1");
42 System.out.println("Encrypted Data : " + o[0]);
43 System.out.println(o[1]);
44 // Now decrypt the string
45 final Encrypter dencrypter = new Encrypter("DESede", ENCRYPTION_KEY);
46 final String decryptedData = dencrypter.decrypt(o[0]);
47 System.out.println("Decrypted Data: " + decryptedData);
48 System.out.println("Done");
49 }
50 public String [] encrypt(final String plainText) {
51 try {
52 final int waitTimeValidRequest = 100;
53 long endTimeSeconds = (System.currentTimeMillis() / 1000) + waitTimeValidRequest;
54 final String param1 = plainText + "&endt=" + endTimeSeconds;
55 final Encrypter encrypter = new Encrypter("DESede", ENCRYPTION_KEY);
56 final String encryptedParam1 = encrypter.encrypt(param1);
57 // Use a one-way hash, we cannot determine the original message but
58 // we can verify against the original message.
59 final String param2hashed = this.makeHash(param1);
60 return new String [] {
61 encryptedParam1, param2hashed
62 };
63 } catch (final Exception e) {
64 e.printStackTrace();
65 } // End of the try - catch block //
66 return null;
67 } // End of the method //
68
69 protected String makeHash(final String param) {
70 String hash = "";
71 try {
72 final String toBeHashed = param + DIGEST_KEY;
73 final MessageDigest digest;
74 digest = MessageDigest.getInstance("MD5");
75 digest.reset();
76 digest.update(toBeHashed.getBytes());
77 final byte[] encrypted = digest.digest();
78 final BASE64Encoder base64encoder = new BASE64Encoder();
79 hash = base64encoder.encode(encrypted);
80 } catch (final NoSuchAlgorithmException ex) {
81 ex.printStackTrace();
82 } // End of the try - catch //
83 return hash;
84 } // End of the method make hash //
85
86 public static class Encrypter {
87 public static final String ENC_DEFAULT_KEY = "YUNWEUYSKHWKHFABCUEKWYRNUI";
88 public static final String DES_ENCRYPTION_SCHEME = "DES";
89 public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
90 private KeySpec keySpec;
91 private SecretKeyFactory keyFactory;
92 private Cipher cipher;
93 private static final String ENCODING = "UTF8";
94
95 public Encrypter(String encryptionScheme) {
96 this(encryptionScheme, ENC_DEFAULT_KEY);
97 }
98 public Encrypter(String encryptionScheme, String encryptionKey) {
99 if (encryptionKey == null)
100 throw new IllegalArgumentException("encryption key was invalid");
101 try {
102 final byte[] keyAsBytes = encryptionKey.getBytes(ENCODING);
103 if (encryptionScheme.equals(DESEDE_ENCRYPTION_SCHEME)) {
104 keySpec = new DESedeKeySpec(keyAsBytes);
105 } else if (encryptionScheme.equals(DES_ENCRYPTION_SCHEME)) {
106 keySpec = new DESKeySpec(keyAsBytes);
107 } else {
108 throw new IllegalArgumentException("Encryption scheme not supported: " + encryptionScheme);
109 }
110 keyFactory = SecretKeyFactory.getInstance(encryptionScheme);
111 cipher = Cipher.getInstance(encryptionScheme);
112 } catch (Exception e) {
113 e.printStackTrace();
114 }
115 }
116 private static String bytes2String(byte[] bytes) {
117 final StringBuffer buf = new StringBuffer();
118 for (int i = 0; i < bytes.length; i++) {
119 buf.append((char) bytes[i]);
120 }
121 return buf.toString();
122 }
123 public String decrypt(String encstr) {
124 if (encstr == null || encstr.trim().length() <= 0) {
125 throw new IllegalArgumentException("encrypted string was null or empty");
126 }
127 try {
128 final SecretKey key = keyFactory.generateSecret(keySpec);
129 cipher.init(Cipher.DECRYPT_MODE, key);
130 BASE64Decoder base64decoder = new BASE64Decoder();
131 byte[] plaintxt = base64decoder.decodeBuffer(encstr);
132 byte[] ciphertext = cipher.doFinal(plaintxt);
133 return bytes2String(ciphertext);
134 } catch (final Exception e) {
135 e.printStackTrace();
136 }
137 return "";
138 }
139 public String encrypt(String decrstr) {
140 if (decrstr == null || decrstr.trim().length() == 0) {
141 throw new IllegalArgumentException("unencrypted string was null or empty");
142 }
143 try {
144 SecretKey key = keyFactory.generateSecret(keySpec);
145 cipher.init(Cipher.ENCRYPT_MODE, key);
146 byte[] cleartext = decrstr.getBytes(ENCODING);
147 byte[] ciphertext = cipher.doFinal(cleartext);
148 BASE64Encoder base64encoder = new BASE64Encoder();
149 return base64encoder.encode(ciphertext);
150 } catch (Exception e) {
151 e.printStackTrace();
152 }
153 return "";
154 }
155 }
156} // / End of the class //