SHA-256: Difference between revisions
Content added Content deleted
(→{{Header|Python}}: Python 3 as well as 2) |
(→{{header|Racket}}: More compact code) |
||
Line 429: | Line 429: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<lang racket> |
||
#lang racket/base |
|||
(require ffi/unsafe |
|||
openssl/libcrypto |
|||
⚫ | |||
;; define a quick SH256 FFI interface, similar to the Racket's default |
;; define a quick SH256 FFI interface, similar to the Racket's default |
||
;; SHA1 interface |
;; SHA1 interface |
||
(require ffi/unsafe ffi/unsafe/define openssl/libcrypto |
|||
⚫ | |||
(define _SHA256_CTX-pointer _pointer) |
|||
(define-ffi-definer defcrypto libcrypto) |
|||
( |
(defcrypto SHA256_Init (_fun _pointer -> _int)) |
||
(defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int)) |
|||
(and libcrypto |
|||
(defcrypto SHA256_Final (_fun _pointer _pointer -> _int)) |
|||
(get-ffi-obj 'SHA256_Init libcrypto |
|||
⚫ | |||
(_fun _SHA256_CTX-pointer -> _int) |
|||
⚫ | |||
(lambda () #f)))) |
|||
⚫ | |||
⚫ | |||
(define SHA256_Update |
|||
(SHA256_Update ctx bytes (bytes-length bytes)) |
|||
(and libcrypto |
|||
⚫ | |||
(get-ffi-obj 'SHA256_Update libcrypto |
|||
⚫ | |||
(_fun _SHA256_CTX-pointer _pointer _long -> _int) |
|||
(lambda () #f)))) |
|||
(define SHA256_Final |
|||
(and libcrypto |
|||
(get-ffi-obj 'SHA256_Final libcrypto |
|||
(_fun _pointer _SHA256_CTX-pointer -> _int) |
|||
(lambda () #f)))) |
|||
⚫ | |||
(if SHA256_Init |
|||
⚫ | |||
[tmp (make-bytes 4096)] |
|||
⚫ | |||
⚫ | |||
(let loop () |
|||
(let ([n (read-bytes-avail! tmp in)]) |
|||
(unless (eof-object? n) |
|||
(SHA256_Update ctx tmp n) |
|||
(loop)))) |
|||
⚫ | |||
result) |
|||
(error 'sha256-bytes "ffi SHA256 functionality not available"))) |
|||
(define (sha256 in) |
|||
⚫ | |||
;; use the defined wrapper to solve the task |
;; use the defined wrapper to solve the task |
||
(displayln (sha256 #"Rosetta code")) |
|||
</lang> |
|||
(printf "~a\n" (sha256 (open-input-string "Rosetta code")))</lang> |
|||
{{out}} |
{{out}} |