Is there an AES library for clojure?

。_饼干妹妹 提交于 2020-02-01 02:21:09

问题


Is there an AES encryption library for clojure? should I use a java libray available through maven or clojars? Thank your for your time and consideration.


回答1:


Here is a perhaps more idiomatic example using the available java crypto libraries. encrypt and decrypt here each simply take input text and the encryption key, both as Strings.

(import (javax.crypto Cipher KeyGenerator SecretKey)
        (javax.crypto.spec SecretKeySpec)
        (java.security SecureRandom)
        (org.apache.commons.codec.binary Base64))

(defn bytes [s]
  (.getBytes s "UTF-8"))

(defn base64 [b]
  (Base64/encodeBase64String b))

(defn debase64 [s]
  (Base64/decodeBase64 (bytes s)))

(defn get-raw-key [seed]
  (let [keygen (KeyGenerator/getInstance "AES")
        sr (SecureRandom/getInstance "SHA1PRNG")]
    (.setSeed sr (bytes seed))
    (.init keygen 128 sr)
    (.. keygen generateKey getEncoded)))

(defn get-cipher [mode seed]
  (let [key-spec (SecretKeySpec. (get-raw-key seed) "AES")
        cipher (Cipher/getInstance "AES")]
    (.init cipher mode key-spec)
    cipher))

(defn encrypt [text key]
  (let [bytes (bytes text)
        cipher (get-cipher Cipher/ENCRYPT_MODE key)]
    (base64 (.doFinal cipher bytes))))

(defn decrypt [text key]
  (let [cipher (get-cipher Cipher/DECRYPT_MODE key)]
    (String. (.doFinal cipher (debase64 text)))))

Used suchwise:

(def key "secret key")
(def encrypted (encrypt "My Secret" key)) ;; => "YsuYVJK+Q6E36WjNBeZZdg=="
(decrypt encrypted key) ;; => "My Secret"



回答2:


Java's AES implementation is well-tested and included in the JDK…any Clojure library would likely use that impl itself.

See Java 256-bit AES Password-Based Encryption for a decent discussion of the Java API. Also, http://jyliao.blogspot.com/2010/08/exploring-java-aes-encryption-algorithm.html has an example of using the API from Clojure (though the code there isn't entirely idiomatic).




回答3:


Tinklj is a great library that is wrapping Clojure around the Google Tink Java API. Google Tink supports all forms of encryption/decryption using streaming or deterministic. AES is supported AeadKeyTemplates.AES128_GCM.

It also offers MAC and Digital Signatures well worth checking out and getting involved.

For example:

(:require [tinklj.keys.keyset-handle :as keyset-handles])

(keyset-handles/generate-new :aes128-gcm)

(:require [tinklj.encryption.aead :refer [encrypt decrypt])

(encrypt aead (.getBytes data-to-encrypt) aad)
(decrypt aead encrypted aad)


来源:https://stackoverflow.com/questions/10221257/is-there-an-aes-library-for-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!