phaedrus0

Apex Crypto AES Encrypt

Mar 11th, 2014
497
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     public String encryptWithManagedIV(String data) throws Exception {
  2.         byte[] random = new byte[IV_LENGTH];
  3.         new Random().nextBytes(random);
  4.         return encrypt(data.getBytes(), random);
  5.     }
  6.    
  7.     protected String encrypt(byte[] data, byte[] initialVector) throws Exception {
  8.         Cipher c = Cipher.getInstance(AES_CIPHER);
  9.         IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
  10.         c.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
  11.         byte[] encVal = c.doFinal(data);
  12.         byte[] encValWithIv = new byte[encVal.length + IV_LENGTH];
  13.         System.arraycopy(initialVector, 0, encValWithIv, 0, IV_LENGTH);
  14.         System.arraycopy(encVal, 0, encValWithIv, IV_LENGTH, encVal.length);
  15.         String encryptedValue = Base64.encodeBase64String(encValWithIv);
  16.         return encryptedValue;
  17.     }
RAW Paste Data