Skip to content

Instantly share code, notes, and snippets.

@fukamachi
Created August 17, 2018 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fukamachi/84759314e9e82728a83d4177769d7bff to your computer and use it in GitHub Desktop.
Save fukamachi/84759314e9e82728a83d4177769d7bff to your computer and use it in GitHub Desktop.
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