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
<lang racket>
#lang racket/base
(require ffi/unsafe
openssl/libcrypto
(only-in file/sha1 bytes->hex-string))



;; 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

(only-in openssl/sha1 bytes->hex-string))
(define _SHA256_CTX-pointer _pointer)
(define-ffi-definer defcrypto libcrypto)

(define SHA256_Init
(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
(define (sha256 bytes)
(_fun _SHA256_CTX-pointer -> _int)
(define ctx (malloc 128))
(lambda () #f))))
(define result (make-bytes 32))

(SHA256_Init ctx)
(define SHA256_Update
(SHA256_Update ctx bytes (bytes-length bytes))
(and libcrypto
(SHA256_Final result ctx)
(get-ffi-obj 'SHA256_Update libcrypto
(bytes->hex-string result))
(_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))))

(define (sha256-bytes in)
(if SHA256_Init
(let ([ctx (malloc 128)]
[tmp (make-bytes 4096)]
[result (make-bytes 32)])
(SHA256_Init ctx)
(let loop ()
(let ([n (read-bytes-avail! tmp in)])
(unless (eof-object? n)
(SHA256_Update ctx tmp n)
(loop))))
(SHA256_Final result ctx)
result)
(error 'sha256-bytes "ffi SHA256 functionality not available")))

(define (sha256 in)
(bytes->hex-string (sha256-bytes 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}}