Skip to content

Instantly share code, notes, and snippets.

@sohalloran
Last active May 26, 2020 17:50
Show Gist options
  • Save sohalloran/018873c5614d31a3a2fb2693e9aacd89 to your computer and use it in GitHub Desktop.
Save sohalloran/018873c5614d31a3a2fb2693e9aacd89 to your computer and use it in GitHub Desktop.
/*
Apex encryption
String clearText = 'A sample message';
String key = 'b7zfYEKhkmVrl9P3yGN/p+3AOkjWK5D6s2JOJzW6lpo=';
Blob cipherText = Crypto.encryptWithManagedIV('AES256', EncodingUtil.base64Decode(key), Blob.valueOf(clearText));
String encodedCipherText = EncodingUtil.base64Encode(cipherText);
System.debug(key);
System.debug(encodedCipherText);
*/
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import java.util.Arrays;
public class AESDecrypt {
private static final String characterEncoding = "UTF-8";
private static final String cipherTransformation = "AES/CBC/PKCS5Padding";
private static final String aesEncryptionAlgorithm = "AES";
public static byte[] decryptBase64EncodedWithManagedIV(String encryptedText, String key) throws Exception {
byte[] cipherText = Base64.decodeBase64(encryptedText.getBytes());
byte[] keyBytes = Base64.decodeBase64(key.getBytes());
return decryptWithManagedIV(cipherText, keyBytes);
}
public static byte[] decryptWithManagedIV(byte[] cipherText, byte[] key) throws Exception {
byte[] initialVector = Arrays.copyOfRange(cipherText, 0, 16);
byte[] trimmedCipherText = Arrays.copyOfRange(cipherText, 16, cipherText.length);
return decrypt(trimmedCipherText, key, initialVector);
}
public static byte[] decrypt(byte[] cipherText, byte[] key, byte[] initialVector) throws Exception {
Cipher cipher = Cipher.getInstance(cipherTransformation);
SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
cipherText = cipher.doFinal(cipherText);
return cipherText;
}
public static void main(String args[]) throws Exception {
byte[] clearText = decryptBase64EncodedWithManagedIV(
"shZiijRRaNy8HSDcZeAwYELhBltiBrInSz0MH/F7Ol23VHmJmm3QD1xOMQqaN4FP",
"b7zfYEKhkmVrl9P3yGN/p+3AOkjWK5D6s2JOJzW6lpo=");
System.out.println("ClearText:" + new String(clearText, characterEncoding));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment