Advertisement
Guest User

Untitled

a guest
Jul 24th, 2014
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. import java.security.MessageDigest;
  2. import java.util.Arrays;
  3. import javax.crypto.KeyGenerator;
  4. import javax.crypto.SecretKey;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import javax.crypto.spec.IvParameterSpec;
  7.  
  8. import javax.crypto.Cipher;
  9. import javax.crypto.spec.IvParameterSpec;
  10. import javax.crypto.spec.SecretKeySpec;
  11.  
  12. public class AES {
  13.   static String IV = "AAAAAAAAAAAAAAAA";
  14.   static String plaintext = "test text 123\0\0\0"; /*Note null padding*/
  15.   static String encryptionKey = "0123456789abcdef";
  16.   public static void main(String [] args) {
  17.     try {
  18.      
  19.       System.out.println("==Java==");
  20.       System.out.println("plain:   " + plaintext);
  21.  
  22.       byte[] cipher = encrypt(plaintext, encryptionKey);
  23.  
  24.       System.out.print("cipher:  ");
  25.       for (int i=0; i<cipher.length; i++)
  26.         System.out.print(new Integer(cipher[i])+" ");
  27.       System.out.println("");
  28.  
  29.       String decrypted = decrypt(cipher, encryptionKey);
  30.  
  31.       System.out.println("decrypt: " + decrypted);
  32.  
  33.     } catch (Exception e) {
  34.       e.printStackTrace();
  35.     }
  36.   }
  37.  
  38.   public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
  39.     Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
  40.     SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
  41.     cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
  42.     return cipher.doFinal(plainText.getBytes("UTF-8"));
  43.   }
  44.  
  45.   public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception{
  46.     Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
  47.     SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
  48.     cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
  49.     return new String(cipher.doFinal(cipherText),"UTF-8");
  50.   }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement