001 (ns clj-activitypub.internal.crypto
002 "copied from [Jahfer's clj-activitypub library](https://github.com/jahfer/clj-activitypub).
003 If and when Jahfer issues a release of that library, this directory will be deleted and a
004 dependency on that library will be added to the project."
005 (:require [clojure.java.io :as io])
006 (:import (java.util Base64)
007 (java.security MessageDigest SecureRandom Signature)))
008
009 (java.security.Security/addProvider
010 (org.bouncycastle.jce.provider.BouncyCastleProvider.))
011
012 (defn- keydata [reader]
013 (->> reader
014 (org.bouncycastle.openssl.PEMParser.)
015 (.readObject)))
016
017 (defn- pem-string->key-pair [string]
018 (let [kd (keydata (io/reader (.getBytes string)))]
019 (.getKeyPair (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter.) kd)))
020
021 (defn private-key [private-pem-str]
022 (-> private-pem-str
023 (pem-string->key-pair)
024 (.getPrivate)))
025
026 (defn base64-encode [bytes]
027 (.encodeToString (Base64/getEncoder) bytes))
028
029 (defn sha256-base64 [data]
030 (let [digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes data))]
031 (base64-encode digest)))
032
033 (defn sign [data private-key]
034 (let [bytes (.getBytes data)
035 signer (doto (Signature/getInstance "SHA256withRSA")
036 (.initSign private-key (SecureRandom.))
037 (.update bytes))]
038 (.sign signer)))
039