Skip to content

Instantly share code, notes, and snippets.

@eu90h
Last active September 15, 2015 21:08
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 eu90h/e687d208a1a3dc141d0e to your computer and use it in GitHub Desktop.
Save eu90h/e687d208a1a3dc141d0e to your computer and use it in GitHub Desktop.
Generating primes with OpenSSL & Racket
#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))))
@eu90h
Copy link
Author

eu90h commented Sep 15, 2015

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment