Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create SHA256 HMAC using Ironclad in Common Lisp?

Tags:

common-lisp

There is a python function I am trying to port to Common Lisp:

HEX(HMAC_SHA256(apiSecret, 'stupidstupid'))

How do I go about this with Ironclad?

The closest I've come is:

(ironclad:make-hmac apiSecret :sha256)

But it's not working; it says that apiSecret

The value "V0mn1LLQIc6GNSiBpDfDmRo3Ji8leBZWqMIolNBsnaklScgI"
is not of type
  (SIMPLE-ARRAY (UNSIGNED-BYTE 8) (*)).
like image 831
pebblexe Avatar asked Feb 24 '17 18:02

pebblexe


1 Answers

Ironclad internally works with arrays of bytes.

But it provides tools to convert from ascii strings to such arrays and from bytes to "hex" strings. Here is an interactive session (note that I don't know much about crypto algorithms):

CL-USER> (in-package :ironclad)
#<PACKAGE "IRONCLAD">

Converting the secret:

CRYPTO> (ascii-string-to-byte-array "V0mn1LLQIc6GNSiBpDfDmRo3Ji8leBZWqMIolNBsnaklScgI")
#(86 48 109 110 49 76 76 81 73 99 54 71 78 83 105 66 112 68 102 68 109 82 111
  51 74 105 56 108 101 66 90 87 113 77 73 111 108 78 66 115 110 97 107 108 83
  99 103 73)

Building the HMAC from previous value:

CRYPTO> (make-hmac * :sha256)
#<HMAC(SHA256) {1006214D93}>

Now, I am not sure this is what you want, but according to the documentation, you are supposed to update the hmac with one or more sequences:

CRYPTO> (update-hmac * (ascii-string-to-byte-array "stupidstupid"))
#<HMAC(SHA256) {1006214D93}>

... and then compute a digest:

CRYPTO> (hmac-digest *)
#(178 90 228 244 244 45 109 163 51 222 77 235 244 173 249 208 144 43 116 130
  210 188 62 247 145 153 100 198 119 86 207 163)

The resulting array can be converted to an hex string:

CRYPTO> (byte-array-to-hex-string *)
"b25ae4f4f42d6da333de4debf4adf9d0902b7482d2bc3ef7919964c67756cfa3"

For completeness, here is how you could wrap those functions to replicate the original code, assuming you are in a package that imports the right symbols:

(defun hex (bytes)
  (byte-array-to-hex-string bytes))

(defun hmac_sha256 (secret text)
  (let ((hmac (make-hmac (ascii-string-to-byte-array secret) :sha256)))
    (update-hmac hmac (ascii-string-to-byte-array text))
    (hmac-digest hmac)))

Finally:

(HEX (HMAC_SHA256 "V0mn1LLQIc6GNSiBpDfDmRo3Ji8leBZWqMIolNBsnaklScgI"
                  "stupidstupid"))

=> "b25ae4f4f42d6da333de4debf4adf9d0902b7482d2bc3ef7919964c67756cfa3"
like image 122
coredump Avatar answered Oct 18 '22 00:10

coredump