· 9 years ago · Nov 30, 2016, 04:08 PM
1 PBEKeySpec pbeKeySpec;
2 PBEParameterSpec pbeParamSpec;
3 SecretKeyFactory keyFac;
4
5 // Salt
6 byte[] salt = {
7 (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
8 (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
9 };
10
11 // Iteration count
12 int count = 20;
13
14 // Create PBE parameter set
15 pbeParamSpec = new PBEParameterSpec(salt, count);
16
17 // Prompt user for encryption password.
18 // Collect user password as char array (using the
19 // "readPassword" method from above), and convert
20 // it into a SecretKey object, using a PBE key
21 // factory.
22 System.out.print("Enter encryption password: ");
23 System.out.flush();
24 pbeKeySpec = new PBEKeySpec(readPassword(System.in));
25 keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
26 SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
27
28 // Create PBE Cipher
29 Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
30
31 // Initialize PBE Cipher with key and parameters
32 pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
33
34 // Our cleartext
35 byte[] cleartext = "This is another example".getBytes();
36
37 // Encrypt the cleartext
38 byte[] ciphertext = pbeCipher.doFinal(cleartext);