-
Notifications
You must be signed in to change notification settings - Fork 0
/
DES.java
58 lines (45 loc) · 2.24 KB
/
DES.java
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
import java.util.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
class DES{
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
//String we we want to encrypt
String message="This is a confidential message.";
byte[] myMessage =message.getBytes(); //string to byte array as DES works on bytes
//If you want to use your own key
// SecretKeyFactory MyKeyFactory = SecretKeyFactory.getInstance("DES");
// String Password = "My Password";
// byte[] mybyte =Password.getBytes();
// DESKeySpec myMaterial = new DESKeySpec(mybyte);
// SecretKey myDESKey = MyKeyFactory.generateSecret(myMaterial);
//Generating Key
KeyGenerator Mygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = Mygenerator.generateKey();
//initializing crypto algorithm
Cipher myCipher = Cipher.getInstance("DES");
//setting encryption mode
myCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] myEncryptedBytes=myCipher.doFinal(myMessage);
//setting decryption mode
myCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] myDecryptedBytes=myCipher.doFinal(myEncryptedBytes);
//print message in byte format
//System.out.println(Arrays.toString(myEncryptedBytes));
//System.out.println(Arrays.toString(myDecryptedBytes));
String encrypteddata=new String(myEncryptedBytes);
String decrypteddata=new String(myDecryptedBytes);
System.out.println("Message : "+ Arrays.toString(myMessage));
System.out.println("Encrypted - "+ encrypteddata);
System.out.println("Decrypted Message - "+ decrypteddata);
}
}