我从clojure和python中获得了略微不同的hmac签名

 n大牙 发布于 2023-02-11 20:13

我从我的python实现获得的HMAC SHA1签名和我的clojure实现略有不同.我很难过会导致这种情况.

Python实现:

import hashlib
import hmac

print hmac.new("my-key", "my-data", hashlib.sha1).hexdigest() # 8bcd5631480093f0b00bd072ead42c032eb31059

Clojure实施:

(ns my-project.hmac
    (:import (javax.crypto Mac)
         (javax.crypto.spec SecretKeySpec)))

(def algorithm "HmacSHA1")

(defn return-signing-key [key mac]
  "Get an hmac key from the raw key bytes given some 'mac' algorithm.
  Known 'mac' options: HmacSHA1"
    (SecretKeySpec. (.getBytes key) (.getAlgorithm mac)))

(defn sign-to-bytes [key string]
  "Returns the byte signature of a string with a given key, using a SHA1 HMAC."
  (let [mac (Mac/getInstance algorithm)
    secretKey (return-signing-key key mac)]
    (-> (doto mac
      (.init secretKey)
      (.update (.getBytes string)))
    .doFinal)))

; Formatting
(defn bytes-to-hexstring [bytes]
  "Convert bytes to a String."
  (apply str (map #(format "%x" %) bytes)))



; Public functions
(defn sign-to-hexstring [key string]
  "Returns the HMAC SHA1 hex string signature from a key-string pair."
  (bytes-to-hexstring (sign-to-bytes key string)))

(sign-to-hexstring "my-key" "my-data") ; 8bcd563148093f0b0bd072ead42c32eb31059

ntoskrnl.. 6

Clojure代码中将字节转换为十六进制字符串的部分会丢弃前导零.

您可以使用维护前导零("%02x")的格式字符串,或使用正确的十六进制编码库,例如Guava或Commons Codec.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有