· 5 years ago · Jan 28, 2020, 05:24 AM
1import java.util.*;
2import java.io.BufferedReader;
3import java.io.InputStreamReader;
4import java.security.spec.KeySpec;
5import javax.crypto.Cipher;
6import javax.crypto.SecretKey;
7import javax.crypto.SecretKeyFactory;
8import javax.crypto.spec.DESedeKeySpec;
9//import sun.misc.BASE64Decoder;
10//import sun.misc.BASE64Encoder;
11import java.util.Base64;
12public class DES {
13private static final String UNICODE_FORMAT = "UTF8";
14public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
15private KeySpec myKeySpec;
16private SecretKeyFactory mySecretKeyFactory;
17private Cipher cipher;
18byte[] keyAsBytes;
19private String myEncryptionKey;
20private String myEncryptionScheme;
21SecretKey key;
22static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
23public DES() throws Exception {
24// TODO code application logic here
25myEncryptionKey="ThisIsSecretEncryptionKey";
26myEncryptionScheme=DESEDE_ENCRYPTION_SCHEME;
27keyAsBytes=myEncryptionKey.getBytes(UNICODE_FORMAT);
28myKeySpec=new DESedeKeySpec(keyAsBytes);
29mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
30cipher = Cipher.getInstance(myEncryptionScheme);
31key = mySecretKeyFactory.generateSecret(myKeySpec);
32}
33public String encrypt(String unencryptedString)
34{ String encryptedString = null;
35try {
36cipher.init(Cipher.ENCRYPT_MODE, key);
37byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
38byte[] encryptedText = cipher.doFinal(plainText);
39encryptedString = Base64.getEncoder().encodeToString(encryptedText);
40}
41catch (Exception e)
42{
43e.printStackTrace();
44}
45return encryptedString;
46}
47DES.java 06-02-2019 10:29
48public String decrypt(String encryptedString)
49{ String decryptedText=null;
50try {
51cipher.init(Cipher.DECRYPT_MODE, key);
52byte[] encryptedText = Base64.getDecoder().decode(encryptedString);
53byte[] plainText = cipher.doFinal(encryptedText);
54decryptedText=bytes2String(plainText); }
55catch (Exception e)
56{
57e.printStackTrace();
58}
59return decryptedText;
60}
61private static String bytes2String(byte[] bytes)
62{ StringBuffer stringBuffer = new StringBuffer();
63for (int i = 0; i <bytes.length;i++)
64{ stringBuffer.append((char) bytes[i]); }
65return stringBuffer.toString();
66}
67public static void main(String args []) throws Exception
68{
69DES myEncryptor= new DES();
70System.out.print("Enter the string: ");
71String stringToEncrypt = br.readLine();
72String encrypted = myEncryptor.encrypt(stringToEncrypt);
73String decrypted = myEncryptor.decrypt(encrypted);
74System.out.println("\nString To Encrypt: " +stringToEncrypt);
75System.out.println("\nEncrypted Value : " +encrypted);
76System.out.println("\nDecrypted Value : " +decrypted); System.out.