· last year · Nov 13, 2023, 05:05 PM
1public class Main {
2 public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {
3 char[] password = "short_password".toCharArray();
4 byte[] salt = new byte[16];
5 int iteration_count = 100;
6
7 int key_size = 128;
8// set salt values to random
9
10 byte[] keyBytes = new byte[18];
11
12 SecureRandom myPRNG = new SecureRandom();
13// seed the key
14 myPRNG.nextBytes(keyBytes);
15
16
17 myPRNG.nextBytes(salt);
18
19// initialize key factory for HMAC-SHA1 derivation
20 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
21// set key specification
22 PBEKeySpec pbekSpec = new PBEKeySpec(password, salt, iteration_count, key_size);
23// generate the key
24 SecretKey myAESPBKey = new SecretKeySpec(keyFactory.generateSecret(pbekSpec).getEncoded(), "DES");
25// print the key
26 System.out.println("AES key: " + javax.xml.bind.DatatypeConverter.printHexBinary(myAESPBKey.getEncoded()));
27
28
29// build the key from random key bytes
30 SecretKeySpec myKey = new SecretKeySpec(keyBytes, "DES");
31// instantiate AES object for ECB with no padding
32 Cipher myAES = Cipher.getInstance("DES/CBC/PKCS5Padding");
33// initialize AES objecy to encrypt mode
34 myAES.init(Cipher.ENCRYPT_MODE, myKey);
35// initialize plaintext
36 byte[] plaintext = new byte[16];
37//initialize ciphertext
38 byte[] ciphertext = new byte[16];
39// update cipher with the plaintext
40 int cLength = myAES.update(plaintext, 0, plaintext.length, ciphertext, 0);
41// process remaining blocks of plaintext
42 cLength += myAES.doFinal(ciphertext, cLength);
43// print plaintext and ciphertext
44 System.out.println("plaintext: " +
45 javax.xml.bind.DatatypeConverter.printHexBinary(plaintext));
46 System.out.println("ciphertext: " +
47 javax.xml.bind.DatatypeConverter.printHexBinary(ciphertext));
48// initialize AES for decryption
49 myAES.init(Cipher.DECRYPT_MODE, myKey);
50// initialize a new array of bytes to place the decryption
51 byte[] dec_plaintext = new byte[16];
52 cLength = myAES.update(ciphertext, 0, ciphertext.length, dec_plaintext, 0);
53// process remaining blocks of ciphertext
54 cLength += myAES.doFinal(dec_plaintext, cLength);
55// print the new plaintext (hopefully identical to the initial one)
56 System.out.println("decrypted: " + javax.xml.bind.DatatypeConverter.printHexBinary(dec_plaintext));
57 }
58}