· 7 years ago · Sep 05, 2018, 05:56 PM
1Encryption in Java
2import java.security.*;
3import javax.crypto.*;
4import javax.crypto.spec.*;
5import java.io.*;
6
7/**
8 * This program generates a AES key, retrieves its raw bytes, and
9 * then reinstantiates a AES key from the key bytes.
10 * The reinstantiated key is used to initialize a AES cipher for
11 * encryption and decryption.
12 */
13public class AES
14{
15
16 /**
17 * Turns array of bytes into string
18 *
19 * @param buf Array of bytes to convert to hex string
20 * @return Generated hex string
21 */
22 public static String asHex(byte buf[])
23 {
24 StringBuilder strbuf = new StringBuilder(buf.length * 2);
25 int i;
26
27 for (i = 0; i < buf.length; i++)
28 {
29 if (((int) buf[i] & 0xff) < 0x10)
30 {
31 strbuf.append("0");
32 }
33
34 strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
35 }
36
37 return strbuf.toString();
38 }
39
40 public static void main(String[] args) throws Exception
41 {
42
43 String message = "This is just an example";
44
45 // Get the KeyGenerator
46
47 KeyGenerator kgen = KeyGenerator.getInstance("AES");
48 kgen.init(128); // 192 and 256 bits may not be available
49
50
51 // Generate the secret key specs.
52 SecretKey skey = kgen.generateKey();
53 byte[] raw = skey.getEncoded();
54
55 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
56
57
58 // Instantiate the cipher
59
60 Cipher cipher = Cipher.getInstance("AES");
61
62 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
63
64 byte[] encrypted = cipher.doFinal(message.getBytes());
65 System.out.println("encrypted string: " + asHex(encrypted));
66
67 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
68 byte[] original = cipher.doFinal(encrypted);
69 String originalString = new String(original);
70 System.out.println("Original string: " + originalString + " " + asHex(original));
71 }
72}