Last active
January 28, 2022 11:32
-
-
Save source-c/c4acb26492357c1f17c2c65f299aed89 to your computer and use it in GitHub Desktop.
SHA-x signature with RSA keys
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
(ns rsa-sign | |
(:require [clojure.java.io :as io]) | |
(:import (org.bouncycastle.openssl PEMParser) | |
(java.security KeyFactory Signature SecureRandom PublicKey) | |
(java.security.spec PKCS8EncodedKeySpec X509EncodedKeySpec) | |
(java.util Base64))) | |
;(java.security.Security/addProvider (org.bouncycastle.jce.provider.BouncyCastleProvider.)) | |
(def _cr "RSA") | |
(def _sh "SHA1withRSA") | |
(defn- keydata [reader] | |
(->> reader | |
(PEMParser.) | |
(.readObject))) | |
(defn- get-key-data [string] (keydata (io/reader (.getBytes string)))) | |
(defn rsa-private [string] | |
(let [kd (get-key-data string) | |
kf (KeyFactory/getInstance _cr)] | |
(.generatePrivate kf (PKCS8EncodedKeySpec. (.getEncoded kd))))) | |
(defn rsa-public [string] | |
(let [kd (get-key-data string) | |
kf (KeyFactory/getInstance _cr)] | |
(.generatePublic kf (X509EncodedKeySpec. (.getEncoded kd))))) | |
(defn- decode64 [^String s] | |
(.decode (Base64/getDecoder) s)) | |
(defn- encode64 [^bytes ba] | |
(.encodeToString (Base64/getEncoder) ba)) | |
(defn- hex [^bytes ba] | |
(->> (map #(format "%02x" %) ba) | |
(apply str))) | |
(defn- unhex [^String s] | |
(->> (partition 2 s) | |
(map #(Integer/parseInt (apply str %) 16)) | |
byte-array)) | |
(defn- ->bytes ^bytes | |
[s & [encoding]] | |
(.getBytes s (or encoding "UTF-8"))) | |
(defn sign | |
[message private-key & [hex?]] | |
((if hex? hex encode64) | |
(let [msg-data (->bytes message) | |
sig (doto (Signature/getInstance _sh) | |
(.initSign private-key (SecureRandom.)) | |
(.update msg-data))] | |
(.sign sig)))) | |
(defn verify [encoded-sig message ^PublicKey public-key & [hex?]] | |
(let [msg-data (->bytes message) | |
signature ((if hex? unhex decode64) encoded-sig) | |
sig (doto (Signature/getInstance _sh) | |
(.initVerify public-key) | |
(.update msg-data))] | |
(.verify sig signature))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment