· 6 years ago · Oct 23, 2019, 11:00 AM
1package cviko5;
2
3import java.security.NoSuchAlgorithmException;
4
5import javax.crypto.*;
6import javax.crypto.spec.IvParameterSpec;
7
8public class DES {
9
10 public static enum PBM {
11 PB_ASCII, PB_HEX, PB_HEX_UPPER;
12 };
13
14 public static final int PB_TAB = 8;
15 public static final int PB_LENGTH = 25;
16
17 public static void PrintBytes(byte[] bytes, PBM mode) {
18 String modestr;
19 switch (mode) {
20 case PB_ASCII:
21 modestr = "%c";
22 break;
23 case PB_HEX:
24 modestr = "%02x";
25 break;
26 case PB_HEX_UPPER:
27 default:
28 modestr = "%02X";
29 }
30 for (int ind = 0; ind < bytes.length; ind++) {
31 try {
32 System.out.printf(modestr, bytes[ind]);
33 } catch (Exception e) {
34 System.out.printf("%%%02X%%", bytes[ind]);
35 }
36 if ((ind + 1) % PB_LENGTH == 0)
37 System.out.println("\\");
38 else if ((ind + 1) % PB_TAB == 0)
39 System.out.print(" ");
40 }
41 System.out.println();
42 }
43
44 public static void main(String[] args) throws Exception {
45
46 String pole[] = { "DES/CBC/PKCS5Padding", "DES/OFB/PKCS5Padding", "DES/CFB/PKCS5Padding",
47 "DES/CFB32/PKCS5Padding", "DES/CFB8/PKCS5Padding" };
48
49 for (String s : pole) {
50 System.out.println(s);
51 System.out.println();
52 Cipher desCipher = Cipher.getInstance(s); // Create the cipher
53
54 KeyGenerator keygen = KeyGenerator.getInstance("DES");
55 SecretKey desKey = keygen.generateKey();
56 desCipher.init(Cipher.ENCRYPT_MODE, desKey); // Initialize the cipher for encryption; IvParameterSpec
57 byte[] iv = desCipher.getIV();
58
59 Cipher desCipher2 = Cipher.getInstance(s);
60
61 byte[] cleartext = "ABCDEFGHXXXXXXXXABCDEFGH".getBytes();
62 PrintBytes(cleartext, PBM.PB_ASCII);
63 byte[] ciphertext = desCipher.doFinal(cleartext); // Encrypt the cleartext
64 ciphertext[10] = (byte) (ciphertext[5] ^ 128);
65 PrintBytes(ciphertext, PBM.PB_HEX);
66
67 desCipher2.init(Cipher.DECRYPT_MODE, desKey, new IvParameterSpec(iv)); // Initialize the same cipher for
68 // decryption
69 byte[] decryptedtext = desCipher2.doFinal(ciphertext); // Decrypt the ciphertext
70 PrintBytes(decryptedtext, PBM.PB_ASCII);
71 System.out.println();
72 }
73
74 }
75
76}