Last active
September 15, 2015 21:08
-
-
Save eu90h/e687d208a1a3dc141d0e to your computer and use it in GitHub Desktop.
Generating primes with OpenSSL & Racket
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
#lang racket/base | |
(require ffi/unsafe | |
racket/runtime-path | |
(for-syntax racket/base) | |
"libcrypto.rkt") | |
(define _BIGNUM-ptr (_cpointer/null 'BIGNUM)) | |
(define _BN_CTX-ptr (_cpointer/null 'BN_CTX)) | |
(define _BN_GENCB-ptr (_cpointer/null 'BN_GENCB)) | |
; macro that saves tedium writing the interface to a libcrypto function | |
(define-syntax-rule (define-libcrypto x type ...) | |
(define x | |
(and libcrypto | |
(get-ffi-obj 'x libcrypto (_fun type ...) (lambda () #f))))) | |
(define-libcrypto BN_new -> _BIGNUM-ptr) | |
(define-libcrypto BN_generate_prime_ex _BIGNUM-ptr _int _bool _BIGNUM-ptr _BIGNUM-ptr _BN_GENCB-ptr -> _int) | |
(define-libcrypto BN_bn2dec _BIGNUM-ptr -> _string) | |
(define (generate-prime [bits 2048] [safe? #f]) | |
(define prime (BN_new)) | |
(if (= 1 (BN_generate_prime_ex prime bits safe? #f #f #f)) | |
(string->number (BN_bn2dec prime)) | |
(raise "OpenSSL failed to generate a prime"))) | |
(module+ test | |
(require math/number-theory rackunit) | |
(check-true (prime? (/ (sub1 (generate-prime 2048 #t)) 2)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@samth pointed out define-ffi-definer, which does the same thing as my define-libcrypto macro (except more general, obviously).
The article and gist will be accordingly updated soon.