Skip to content

Instantly share code, notes, and snippets.

@alcidesfp
Last active December 13, 2022 19:09
Show Gist options
  • Save alcidesfp/d28060cb56462db49ff9 to your computer and use it in GitHub Desktop.
Save alcidesfp/d28060cb56462db49ff9 to your computer and use it in GitHub Desktop.
Kawa: File checksum with MD5
(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))
""))
;;--------------------------------------------------------------------
@alcidesfp
Copy link
Author

La función s8vector->hexstr se puede simplificar muchísimo utilizando el format de Lisp

@alcidesfp
Copy link
Author

(format "~2,'0X" (bitwise-and #xFF e))

@alcidesfp
Copy link
Author

alcidesfp commented Dec 13, 2022

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