Created
April 24, 2014 15:06
-
-
Save kurogelee/11258117 to your computer and use it in GitHub Desktop.
ClojureでAES暗号化をしてみる&AESのちょっと細かい話 ref: http://qiita.com/kurogelee/items/8f74caf44d4224e63dea
This file contains hidden or 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
(import '[java.security SecureRandom Key] | |
'[javax.crypto KeyGenerator Cipher] | |
'[javax.crypto.spec IvParameterSpec] | |
'[java.security.spec AlgorithmParameterSpec]) | |
(defn ^bytes rand-bytes [n] | |
(let [b (byte-array n)] | |
(.. (SecureRandom.) (nextBytes b)) | |
b)) | |
(defn ^Key aes-genkey [^long bits] | |
{:pre[(#{128 192 256} bits)]} | |
(let [kg (KeyGenerator/getInstance "AES")] | |
(.init kg bits) | |
(.generateKey kg))) | |
(def ^:dynamic *aes-mode* "AES/CBC/PKCS5Padding") | |
(defn- ^bytes aes-*code [^long mode ^bytes bytes ^Key key ^AlgorithmParameterSpec spec] | |
(let [c (Cipher/getInstance *aes-mode*)] | |
(if spec | |
(.init c mode key spec) | |
(.init c mode key)) | |
(.doFinal c bytes))) | |
(defn ^bytes aes-encode [^bytes bytes ^Key key & [^AlgorithmParameterSpec spec]] | |
(aes-*code Cipher/ENCRYPT_MODE bytes key spec)) | |
(defn ^bytes aes-decode [^bytes bytes ^Key key & [^AlgorithmParameterSpec spec]] | |
(aes-*code Cipher/DECRYPT_MODE bytes key spec)) |
This file contains hidden or 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
(def k (aes-genkey 128)) | |
(def iv (rand-bytes 16)) | |
(def encoded (aes-encode (byte-array 2) k (IvParameterSpec. iv))) | |
(def decoded (aes-decode encoded k (IvParameterSpec. iv))) | |
(binding [*aes-mode* "AES/ECB/NoPadding"] | |
(let [e (aes-encode (byte-array 16) k)] | |
(seq (aes-decode e k)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment