Last active
December 13, 2022 19:09
-
-
Save alcidesfp/d28060cb56462db49ff9 to your computer and use it in GitHub Desktop.
Kawa: File checksum with MD5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define-alias FileInputStream java.io.FileInputStream) | |
(define-alias MessageDigest java.security.MessageDigest) | |
(define-alias Integer java.lang.Integer) | |
(require 'srfi-13) | |
;;-------------------------------------------------------------------- | |
(define (md5vector file-name ::java.lang.String) | |
(let ((md (MessageDigest:getInstance "MD5")) | |
(fis (FileInputStream file-name)) | |
(data-bytes ::byte[] ((primitive-array-new byte) 1024))) | |
(do ((nread 0 (*:read fis data-bytes))) | |
((= nread -1) (make s8vector (*:digest md))) | |
(*:update md data-bytes 0 nread)))) | |
;;-------------------------------------------------------------------- | |
(define (s8vector->hexstr mdbytes ::gnu.lists.S8Vector) | |
(string-join | |
(map (lambda(e) | |
(let((str (Integer:toHexString (bitwise-and #xff e)))) | |
(if (= (string-length str) 1) | |
(string-append "0" str) | |
str))) | |
(s8vector->list mdbytes)) | |
"")) | |
;;-------------------------------------------------------------------- |
(format "~2,'0X" (bitwise-and #xFF e))
Muchísimo mas de hecho sin necesidad del bitwise-and
para quitar el signo utilizando un U8Vector
:
(import (class java.security MessageDigest))
(import (class gnu.lists U8Vector))
(set! dv2 (U8Vector (*:digest (MessageDigest:get-instance "md5") (*:get-bytes (String "hello")))))
(format #f "~{~2,'0X~}" (vector->list dv2))
O también utilizando directamente la función bytevector
y el operador splice @
:
(let ((bv1 (bytevector @(*:digest (MessageDigest:get-instance "md5") (*:get-bytes (String "hello"))))))
(format #f "~{~2,'0X~}" (vector->list bv1)))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
La función
s8vector->hexstr
se puede simplificar muchísimo utilizando elformat
de Lisp