Jump to content

SHA-256: Difference between revisions

704 bytes removed ,  11 years ago
→‎{{header|Racket}}: More compact code
(→‎{{Header|Python}}: Python 3 as well as 2)
(→‎{{header|Racket}}: More compact code)
Line 429:
 
=={{header|Racket}}==
<lang Racket>#lang racket/base>
#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
(require ffi/unsafe ffi/unsafe/define openssl/libcrypto
 
(only-in fileopenssl/sha1 bytes->hex-string))
(define _SHA256_CTX-pointer _pointer)
(define-ffi-definer defcrypto libcrypto)
 
(definedefcrypto 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 inbytes)
(_fun _SHA256_CTX-pointer -> _int)
(letdefine ([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 (sha256-bytes in)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
(displayln (sha256 #"Rosetta code"))
 
</lang>
(printf "~a\n" (sha256 (open-input-string "Rosetta code")))</lang>
 
{{out}}
Cookies help us deliver our services. By using our services, you agree to our use of cookies.