· 7 years ago · Jul 28, 2018, 08:52 AM
1Generate a key that is consistent over time
2// I use String.getBytes() as a convenince a lot. I specify the encoding
3// to ensure that the result is consistent.
4final String utf8 = "utf-8";
5
6String password = "It's a secret! Make sure it's long enough (24 bytes)";
7byte[] keyBytes = Arrays.copyOf(password.getBytes(utf8), 24);
8SecretKey key = new SecretKeySpec(keyBytes, "DESede");
9
10// Your vector must be 8 bytes long
11String vector = "ABCD1234";
12IvParameterSpec iv = new IvParameterSpec(vector.getBytes(utf8));
13
14// Make an encrypter
15Cipher encrypt = Cipher.getInstance("DESede/CBC/PKCS5Padding");
16encrypt.init(Cipher.ENCRYPT_MODE, key, iv);
17
18// Make a decrypter
19Cipher decrypt = Cipher.getInstance("DESede/CBC/PKCS5Padding");
20decrypt.init(Cipher.DECRYPT_MODE, key, iv);
21
22// Example use
23String message = "message";
24byte[] messageBytes = message.getBytes(utf8);
25byte[] encryptedByted = encrypt.doFinal(messageBytes);
26byte[] decryptedBytes = decrypt.doFinal(encryptedByted);
27
28// You can re-run the exmaple to see taht the encrypted bytes are consistent
29System.out.println(new String(messageBytes, utf8));
30System.out.println(new String(encryptedByted, utf8));
31System.out.println(new String(decryptedBytes, utf8));