-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptoDES.java
More file actions
81 lines (59 loc) · 2.51 KB
/
CryptoDES.java
File metadata and controls
81 lines (59 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package DES;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Scanner;
public class CryptoDES {
private static Cipher encryptCipher;
private static Cipher decryptCipher;
private static Cipher encrypter;
public static void main(String args[]) throws UnsupportedEncodingException{
Scanner sc = new Scanner(System.in);
String string = sc.nextLine();
try{
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
SecretKey secretKey = keyGenerator.generateKey();
SecureRandom secureRandom = new SecureRandom();
byte[] bytes = new byte[8];
secureRandom.nextBytes(bytes);
SecretKeySpec secretKeySpec = new SecretKeySpec(bytes, "DES");
encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
encrypter = Cipher.getInstance("DES");
encrypter.init(Cipher.ENCRYPT_MODE, secretKey);
decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE,secretKeySpec);
byte[] encryptedData = encrypt(string, true);
byte[] encryptData = encrypt("ABCDEFG", false);
System.out.println("Encrypted " + Arrays.toString(encryptedData) + " " + encryptedData.length);
System.out.println("Encrypted " + Arrays.toString(encryptData) + " " + encryptData.length);
decrypt(encryptedData);
}
catch (java.security.InvalidKeyException e){
e.printStackTrace();
}
catch (NoSuchAlgorithmException e){
e.printStackTrace();
}
catch (NoSuchPaddingException e){
e.printStackTrace();
}
catch (IllegalBlockSizeException e){
e.printStackTrace();
}
catch (BadPaddingException e){
e.printStackTrace();
}
}
private static byte[] encrypt(String data, boolean flag) throws BadPaddingException, IllegalBlockSizeException,
UnsupportedEncodingException {
byte[] byteData = data.getBytes();
return encryptCipher.doFinal(byteData);
}
private static void decrypt(byte[] data) throws BadPaddingException, IllegalBlockSizeException {
System.out.println("Decrypted: " + new String(decryptCipher.doFinal(data)));
}
}