Add a libgcrypt-based implementation of `sha256'.

* guix/utils.scm (sha256): Add a libgcrypt-based implementation using
  the FFI.
This commit is contained in:
Ludovic Courtès 2012-06-29 22:58:27 +02:00
parent f68b089361
commit 39b9372ca7

View file

@ -30,6 +30,7 @@ (define-module (guix utils)
#:autoload (ice-9 rdelim) (read-line)
#:use-module (ice-9 regex)
#:use-module (ice-9 match)
#:autoload (system foreign) (pointer->procedure)
#:export (bytevector-quintet-length
bytevector->base32-string
bytevector->nix-base32-string
@ -381,14 +382,36 @@ (define bv
;;; Hash.
;;;
(define (sha256 bv)
(define sha256
(cond
((compile-time-value
(false-if-exception (dynamic-link "libgcrypt")))
;; Using libgcrypt.
(let ((hash (pointer->procedure void
(dynamic-func "gcry_md_hash_buffer"
(dynamic-link "libgcrypt"))
`(,int * * ,size_t)))
(sha256 8)) ; GCRY_MD_SHA256, as of 1.5.0
(lambda (bv)
"Return the SHA256 of BV as a bytevector."
(if (compile-time-value
(let ((digest (make-bytevector (/ 256 8))))
(hash sha256 (bytevector->pointer digest)
(bytevector->pointer bv) (bytevector-length bv))
digest))))
((compile-time-value
(false-if-exception (resolve-interface '(chop hash))))
;; Using libchop.
(let ((bytevector-hash (@ (chop hash) bytevector-hash))
(hash-method/sha256 (@ (chop hash) hash-method/sha256)))
(bytevector-hash hash-method/sha256 bv))
;; XXX: Slow, poor programmer's implementation that uses Coreutils.
(lambda (bv)
"Return the SHA256 of BV as a bytevector."
(bytevector-hash hash-method/sha256 bv))))
(else
;; Slow, poor programmer's implementation that uses Coreutils.
(lambda (bv)
"Return the SHA256 of BV as a bytevector."
(let ((in (pipe))
(out (pipe))
(pid (primitive-fork)))
@ -410,7 +433,7 @@ (define (sha256 bv)
(close (car out))
(and (and=> (status:exit-val (cdr (waitpid pid)))
zero?)
(base16-string->bytevector line))))))))
(base16-string->bytevector line))))))))))