我得到略有不同的hmac签名出clojure和python [英] I'm getting slightly different hmac signatures out of clojure and python

查看:137
本文介绍了我得到略有不同的hmac签名出clojure和python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HMAC SHA1签名我从我的python实现和我的clojure实现略有不同。

The HMAC SHA1 signatures I'm getting from my python implementation and my clojure implementation are slightly different. I'm stumped as to what would cause that.

Python实现:

import hashlib
import hmac

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

Clojure实现:

Clojure implementation:

(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


推荐答案

Clojure代码的一部分,

The part of your Clojure code that translates bytes to hex strings drops leading zeros.

您可以使用保持前导零的格式字符串(%02x ),或使用正确的十六进制编码库,例如 Guava 公司编解码器

You could use a format string that maintains a leading zero ("%02x"), or use a proper hex encoding library, such as Guava or Commons Codec.

这篇关于我得到略有不同的hmac签名出clojure和python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆