Last active
November 25, 2016 21:31
-
-
Save paxan/c9e1d12f8ea223dde0bf to your computer and use it in GitHub Desktop.
AEAD decryption process using AWS KMS & AES/GCM/NoPadding cipher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; CAVEAT: Ensure your JDK/JRE is configured with Java Cryptography | |
;; Extension (JCE) Unlimited Strength Jurisdiction Policy Files. | |
;; Visit http://www.oracle.com/technetwork/java/javase/downloads/index.html | |
;; and look for "JCE". | |
;; Given a ciphertext (produced by AES/GCM/NoPadding cipher), a nonce, | |
;; and a KMS-encrypted content encrypting key (cek), here is the | |
;; process for producing the plaintext: | |
(defn b64dec [x] (javax.xml.bind.DatatypeConverter/parseBase64Binary x)) | |
(defn b64enc [x] (javax.xml.bind.DatatypeConverter/printBase64Binary x)) | |
(def kms (com.amazonaws.services.kms.AWSKMSClient.)) | |
(def gcm-param (javax.crypto.spec.GCMParameterSpec. 128 (b64dec "nonceNONCEnonceN"))) | |
(def cek-ciphertext-bytes (b64dec "... elided base64 chars of encrypted CEK ...")) | |
(def cek-bytes | |
(.array | |
(.getPlaintext | |
(.decrypt kms (doto (com.amazonaws.services.kms.model.DecryptRequest.) | |
(.setCiphertextBlob (java.nio.ByteBuffer/wrap cek-ciphertext-bytes))))))) | |
(def cek (javax.crypto.spec.SecretKeySpec. cek-bytes "AES")) | |
(def cipher (javax.crypto.Cipher/getInstance "AES/GCM/NoPadding")) | |
(.init cipher javax.crypto.Cipher/DECRYPT_MODE cek gcm-param) | |
;; successful decryption: | |
(def ciphertext (b64dec "p2D6qwsnyqdUKYB7db8Gzj6WmxxRYrt11B81/06JcO8rG/AK/Tk5SLtkLNh/C6DL5XVP0LgQNOBGV52KJmbzuEzzLu4B+Bdmjs13vLxq8LnNHIH9NCcnxp4DkE+iNVv3N+qEoALmAxXxIi1W73QG4UeHJwWrdvJpm5bu/w/t3fpvoOdKYNCgiZZOEH9XPkNtSnWsPdJZoL6FSHU0qKNQyC/fvTk/o4+lsPGL+eMwLgPMDahIRoZAz5eoQU2gkWLNC+arY76sFjim")) | |
(.doFinal cipher ciphertext) | |
;; corrupted ciphertext by changing one character in the base64 repr: | |
(def ciphertext (b64dec "p2D6qwsnyqdUKYB7db8Gzj6WmxxRYrt11B81/06JcO8rG/AK/Tk5SLtkLNh/C6DL5XVP0LgQNOBGV52KJmbzuEzzLu4B+Bdmjs13vLxq8LnNHIH9NCcnxp4DkE+iNVv3N+qEoALmAxXxIi1W73QG4UeHJwWrdvJpm5bu/w/t3fpvoOdKYNCgiZZOEH9XPkNtSnWsPdJZoL6FSHU0qKNQyC/fvTk/o4+lsPGL+eMwLgPMDahIRoZAz5eoQU2gkWLNC+arY76sFjiM")) | |
(.doFinal cipher ciphertext) | |
> AEADBadTagException Tag mismatch! com.sun.crypto.provider.GaloisCounterMode.decryptFinal (GaloisCounterMode.java:524) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment