|
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- import javax.xml.bind.DatatypeConverter;
-
-
- public class AES {
-
-
- public static void main(String[] args) throws Exception {
-
- String plainText = "Secret Message";
- SecretKey secKey = getSecretEncryptionKey();
- byte[] cipherText = encryptText(plainText, secKey);
- String decryptedText = decryptText(cipherText, secKey);
-
-
-
- System.out.println("Original Text:" + plainText);
- System.out.println("AES Key (Hex Form):"+bytesToHex(secKey.getEncoded()));
- System.out.println("Encrypted Text (Hex Form):"+bytesToHex(cipherText));
- System.out.println("Descrypted Text:"+decryptedText);
- }
- //End of main class
-
-
- //Gets encryption key. Would normally be stored differently in a real world situation.
- public static SecretKey getSecretEncryptionKey() throws Exception{
-
- KeyGenerator generator = KeyGenerator.getInstance("AES");
- generator.init(128); // AES key size. More secure than the 56 bit DES
- SecretKey secKey = generator.generateKey();
- return secKey;
- }
-
-
- //ENCRYPT our text using the secret key to byte array
- public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
-
- Cipher aesCipher = Cipher.getInstance("AES");
- aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
- byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
- return byteCipherText;
- }
-
-
- //DECRYPTS the byte array using the key
- public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
-
- Cipher aesCipher = Cipher.getInstance("AES");
- aesCipher.init(Cipher.DECRYPT_MODE, secKey);
- byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
- return new String(bytePlainText);
-
- }
-
-
-
- //Converts binary byte array into readable hex
- private static String bytesToHex(byte[] hash) {
-
- return DatatypeConverter.printHexBinary(hash);
-
- }
-
- }
|