· 7 years ago · Jun 01, 2018, 04:24 PM
1import java.security.*;
2import javax.crypto.*;
3
4public class DES {
5 public static void main(String[] argv) {
6
7 try {
8// KeyGenerator keyGen = KeyGenerator.getInstance("DES");
9// keyGen.init(56);
10// SecretKey secretKey = keyGen.generateKey();
11 SecretKey secretKey = KeyGenerator.getInstance("DES").generateKey();
12
13 Cipher des;
14 des = Cipher.getInstance("DES/ECB/PKCS5Padding");
15 des.init(Cipher.ENCRYPT_MODE, secretKey);
16
17 // cipher message
18 byte[] plainText = "This is my private message no.12, Hello world".getBytes();
19
20 System.out.println("Text [Byte Format] : " + plainText);
21 System.out.println("Text : " + new String(plainText));
22
23 // Encrypt
24 byte[] textEncrypted = des.doFinal(plainText);
25
26 System.out.println("Text Encryted : " + textEncrypted);
27
28 // Initialize the same cipher for decryption
29 des.init(Cipher.DECRYPT_MODE, secretKey);
30
31 // Decrypt the text
32 byte[] textDecrypted = des.doFinal(textEncrypted);
33
34 System.out.println("Text Decryted : " + new String(textDecrypted));
35
36 } catch (NoSuchAlgorithmException e) {
37 e.printStackTrace();
38 } catch (NoSuchPaddingException e) {
39 e.printStackTrace();
40 } catch (InvalidKeyException e) {
41 e.printStackTrace();
42 } catch (IllegalBlockSizeException e) {
43 e.printStackTrace();
44 } catch (BadPaddingException e) {
45 e.printStackTrace();
46 }
47 }
48}