SHA-256: Difference between revisions

Content added Content deleted
(→‎{{header|Perl 6}}: just use constant for K (might fail on PIR compilation, though))
(Added ffi-based Racket solution.)
Line 424: Line 424:
'764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'
'764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'
>>> </lang>
>>> </lang>

=={{header|Racket}}==
<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
;; SHA1 interface

(define _SHA256_CTX-pointer _pointer)

(define SHA256_Init
(and libcrypto
(get-ffi-obj 'SHA256_Init libcrypto
(_fun _SHA256_CTX-pointer -> _int)
(lambda () #f))))

(define SHA256_Update
(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))))

(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

(printf "~a\n" (sha256 (open-input-string "Rosetta code")))</lang>

{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==