| 1 |
;;; |
| 2 |
;;; bcrypt - blowfish password hashing interface |
| 3 |
;;; |
| 4 |
;;; This is a binding for a public-domain implementation of blowfish crypt |
| 5 |
;;; routine (crypt_blowfish). |
| 6 |
;;; I also put this file in public domain. |
| 7 |
;;; |
| 8 |
|
| 9 |
(define-module crypt.bcrypt |
| 10 |
(use gauche.uvector) |
| 11 |
(use math.mt-random) |
| 12 |
(export bcrypt-hashpw bcrypt-gensalt)) |
| 13 |
(select-module crypt.bcrypt) |
| 14 |
|
| 15 |
(inline-stub |
| 16 |
(.include "gauche/priv/configP.h") |
| 17 |
|
| 18 |
(declare-cfn gauche_crypt_ra (key::(const char *) |
| 19 |
setting::(const char *) |
| 20 |
data::void** |
| 21 |
size::int*) ::char*) |
| 22 |
(declare-cfn gauche_crypt_gensalt_ra (prefix::(const char *) |
| 23 |
count::(unsigned long) |
| 24 |
input::(const char *) |
| 25 |
size::int) ::char*) |
| 26 |
|
| 27 |
(define-cproc crypt-ra (pass::<const-cstring> setting::<const-cstring>) |
| 28 |
(let* ([data::void* NULL] [size::int 0] |
| 29 |
[c::char* (gauche_crypt_ra pass setting (& data) (& size))]) |
| 30 |
(when (== c NULL) |
| 31 |
(free data) |
| 32 |
(Scm_SysError "crypt_ra failed")) |
| 33 |
(let* ([r (SCM_MAKE_STR_COPYING c)]) |
| 34 |
(free data) |
| 35 |
(return r)))) |
| 36 |
|
| 37 |
(define-cproc crypt-gensalt-ra (prefix::<const-cstring> |
| 38 |
count::<ulong> |
| 39 |
randomsrc::<u8vector>) |
| 40 |
(let* ([c::char* |
| 41 |
(gauche_crypt_gensalt_ra prefix count |
| 42 |
(cast (const char*) |
| 43 |
(SCM_U8VECTOR_ELEMENTS randomsrc)) |
| 44 |
(SCM_U8VECTOR_SIZE randomsrc))]) |
| 45 |
(when (== c NULL) (Scm_SysError "crypt_gensalt_ra failed")) |
| 46 |
(let* ([r (SCM_MAKE_STR_COPYING c)]) |
| 47 |
(free c) |
| 48 |
(return r)))) |
| 49 |
) |
| 50 |
|
| 51 |
(define (bcrypt-hashpw pass :optional (setting #f)) |
| 52 |
(crypt-ra pass (or setting (bcrypt-gensalt)))) |
| 53 |
|
| 54 |
(define (bcrypt-gensalt :key (prefix "$2b$") (count 10) (entropy-source #f)) |
| 55 |
(crypt-gensalt-ra prefix count (or entropy-source (get-entropy)))) |
| 56 |
|
| 57 |
(define-constant +esize+ 16) |
| 58 |
|
| 59 |
(define (get-entropy) |
| 60 |
(or (call-with-input-file "/dev/urandom" |
| 61 |
(^p (and p |
| 62 |
(rlet1 v (make-u8vector +esize+ 0) |
| 63 |
(dotimes [i +esize+] |
| 64 |
(set! (u8vector-ref v i) (read-byte p)))))) |
| 65 |
:if-does-not-exist #f) |
| 66 |
(let1 mt (make <mersenne-twister> :seed (* (sys-time) (sys-getpid))) |
| 67 |
(rlet1 v (make-u8vector +esize+ 0) |
| 68 |
(dotimes [i +esize+] |
| 69 |
(set! (u8vector-ref v i) (mt-random-integer mt 256))))))) |