You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

AES.java 2.2 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import javax.crypto.Cipher;
  2. import javax.crypto.KeyGenerator;
  3. import javax.crypto.SecretKey;
  4. import javax.xml.bind.DatatypeConverter;
  5. public class AES {
  6. public static void main(String[] args) throws Exception {
  7. String plainText = "Secret Message";
  8. SecretKey secKey = getSecretEncryptionKey();
  9. byte[] cipherText = encryptText(plainText, secKey);
  10. String decryptedText = decryptText(cipherText, secKey);
  11. System.out.println("Original Text:" + plainText);
  12. System.out.println("AES Key (Hex Form):"+bytesToHex(secKey.getEncoded()));
  13. System.out.println("Encrypted Text (Hex Form):"+bytesToHex(cipherText));
  14. System.out.println("Descrypted Text:"+decryptedText);
  15. }
  16. //End of main class
  17. //Gets encryption key. Would normally be stored differently in a real world situation.
  18. public static SecretKey getSecretEncryptionKey() throws Exception{
  19. KeyGenerator generator = KeyGenerator.getInstance("AES");
  20. generator.init(128); // AES key size. More secure than the 56 bit DES
  21. SecretKey secKey = generator.generateKey();
  22. return secKey;
  23. }
  24. //ENCRYPT our text using the secret key to byte array
  25. public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
  26. Cipher aesCipher = Cipher.getInstance("AES");
  27. aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
  28. byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
  29. return byteCipherText;
  30. }
  31. //DECRYPTS the byte array using the key
  32. public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
  33. Cipher aesCipher = Cipher.getInstance("AES");
  34. aesCipher.init(Cipher.DECRYPT_MODE, secKey);
  35. byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
  36. return new String(bytePlainText);
  37. }
  38. //Converts binary byte array into readable hex
  39. private static String bytesToHex(byte[] hash) {
  40. return DatatypeConverter.printHexBinary(hash);
  41. }
  42. }

No Description

Contributors (1)