Skip to content

Instantly share code, notes, and snippets.

@fukamachi fukamachi/keys.lisp
Created Aug 17, 2018

Embed
What would you like to do?
Generating RSA key pairs in DER format
(in-package :cl-user)
(ql:quickload '(:ironclad :asn1))
(defun generate-rsa-key-pair (num-bits)
"Same as (ironclad:generate-key-pair :rsa :num-bits num-bits) except returning in DER format."
(check-type num-bits integer)
(let ((l (floor num-bits 2)))
(multiple-value-bind (p q n)
(loop for a = (ironclad:generate-prime (- num-bits l))
for b = (ironclad:generate-prime l)
for c = (* a b)
until (and (/= a b) (= num-bits (ironclad::integer-length c)))
finally (return (values a b c)))
(let* ((phi (* (1- p) (1- q)))
(e (loop for e = (+ 2 (ironclad:strong-random (- phi 2)))
until (= 1 (ironclad::gcd e phi))
finally (return e)))
(d (ironclad::modular-inverse-with-blinding e phi)))
(values (asn1:encode
`((:sequence
. ((:integer . 0)
(:integer . ,n)
(:integer . ,e)
(:integer . ,d)
(:integer . ,p)
(:integer . ,q)
(:integer . ,(mod d (1- p)))
(:integer . ,(mod d (1- q)))
(:integer . ,(ironclad::expt-mod q (- p 2) p))))))
(asn1:encode
`((:sequence
. ((:sequence . ((:object-identifier . #(1 2 840 113549 1 1 1))
(:null)))
(:bit-string . ,(asn1:encode
`((:sequence . ((:integer . ,n)
(:integer . ,e)))))))))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.