· 6 years ago · May 21, 2019, 04:46 PM
1package symmetric;
2
3import javax.crypto.Cipher;
4import javax.crypto.NoSuchPaddingException;
5import javax.crypto.SecretKey;
6import javax.crypto.spec.IvParameterSpec;
7import javax.crypto.spec.SecretKeySpec;
8import java.security.InvalidKeyException;
9import java.security.NoSuchAlgorithmException;
10import java.security.SecureRandom;
11import java.util.Base64;
12
13public class DES {
14
15 private SecretKey secretKey;
16 private String cryptoMode;
17 private IvParameterSpec initVector;
18 private Cipher cipher;
19
20
21 public DES(String key, String cryptoMode) throws Exception {
22 this.cryptoMode = cryptoMode;
23 byte[] base64Key = Base64.getDecoder().decode(key);
24 this.secretKey = new SecretKeySpec(base64Key,0,base64Key.length,"DESede");
25 this.cipher = Cipher.getInstance("DESede/"+ cryptoMode +"/PKCS5Padding");
26
27 SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
28 byte[] iv = new byte[cipher.getBlockSize()];
29 randomSecureRandom.nextBytes(iv);
30 this.initVector = new IvParameterSpec(iv);
31
32 }
33
34
35 public String encrypt(String text) throws Exception {
36
37 if (cryptoMode.equals("ECB")) {
38 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
39 } else {
40 cipher.init(Cipher.ENCRYPT_MODE, secretKey, initVector);
41 }
42
43 byte[] encrypted = cipher.doFinal(text.getBytes());
44 return Base64.getEncoder().encodeToString(encrypted);
45 }
46
47 public String decrypt(String cipherText) throws Exception {
48
49 if (cryptoMode.equals("ECB")) {
50 cipher.init(Cipher.DECRYPT_MODE, secretKey);
51 } else {
52 cipher.init(Cipher.DECRYPT_MODE, secretKey, initVector);
53 }
54
55 byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
56 return new String(decrypted);
57 }
58
59
60 public static void main(String[] args) throws Exception{
61 DES des = new DES("133457799AAA","ECB");
62
63 String encrpyted = des.encrypt("kurac");
64
65 String dectrpyted = des.decrypt(encrpyted);
66
67 System.out.println(dectrpyted);
68
69 }
70
71
72}