如何在Common Lisp中使用Ironclad创建SHA256 HMAC?

时间:2017-02-24 18:09:23

标签: common-lisp

我正在尝试移植到Common Lisp的python函数:

HEX(HMAC_SHA256(apiSecret, 'stupidstupid'))

我如何与Ironclad一起解决这个问题?

我最接近的是:

(ironclad:make-hmac apiSecret :sha256)

但它不起作用;它说apiSecret

The value "V0mn1LLQIc6GNSiBpDfDmRo3Ji8leBZWqMIolNBsnaklScgI"
is not of type
  (SIMPLE-ARRAY (UNSIGNED-BYTE 8) (*)).

1 个答案:

答案 0 :(得分:11)

Ironclad内部使用字节数组。

但它提供了从ascii字符串转换为此类数组并从字节转换为" hex"字符串。这是一个交互式会话(请注意,我对加密算法了解不多):

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

转换秘密:

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)

从之前的值构建HMAC:

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

现在,我不确定这是你想要的,但根据the documentation,你应该用一个或多个序列来更新hmac:

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

...然后计算摘要:

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)

生成的数组可以转换为十六进制字符串:

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

为了完整性,假设您在一个导入正确符号的包中,可以使用以下方法包装这些函数以复制原始代码:

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

最后:

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

=> "b25ae4f4f42d6da333de4debf4adf9d0902b7482d2bc3ef7919964c67756cfa3"