如何在Python 3中从R复制基于SHA256的HMAC [英] How to reproduce an SHA256-based HMAC from R in Python 3

查看:221
本文介绍了如何在Python 3中从R复制基于SHA256的HMAC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Python中的R代码重现盐腌的sha256输出:

I am trying to reproduce salted sha256 output from R code in Python:

library(openssl)
res = sha256("test@gmail.com", key = "111")  
res
# [1] "172f052058445afd9fe3afce05bfec573b5bb4c659bfd4cfc69a59d1597a0031"

import hashlib, binascii
dk = hashlib.pbkdf2_hmac(='sha256', b'test@gmail.com', b'111', 0)
binascii.hexlify(dk)
# b'494c86307ffb9e9e31c4ec8782af6498e91272c011a316c242d9164d765be257'

如何在python中匹配R?

How can I make output in python match R?

推荐答案

我不太清楚您的问题.以下键匹配

I can't quite reproduce your issue. The following keys match

在R中:

library(openssl)
sha256("test@gmail.com")
#[1] "87924606b4131a8aceeeae8868531fbb9712aaa07a5d3a756b26ce0f5d6ca674"

在Python3中:

import hashlib
print(hashlib.sha256(b"test@gmail.com").hexdigest())
#87924606b4131a8aceeeae8868531fbb9712aaa07a5d3a756b26ce0f5d6ca674


根据您的评论进行更新

首先要注意的是,在带有非NULL key参数的R sha256中,将计算


Update in response to your comment

The first thing to notice is that in R sha256 with a non-NULL key argument will calculate the hash-based message authentication code (HMAC). From ?sha256:

所有哈希函数要么为'key ==计算哈希摘要 如果为"key",则为NULL或HMAC(哈希消息身份验证代码) 不是"NULL".

All hash functions either calculate a hash-digest for ‘key == NULL’ or HMAC (hashed message authentication code) when ‘key’ is not ‘NULL’.

因此,如果要使用密钥,则需要将R中生成的HMAC与Python中基于SHA2556的HMAC进行比较.

So if you want to use a key you will need to compare the resulting HMAC in R with the SHA2556-based HMAC in Python.

在R中:

library(openssl)
sha256("test@gmail.com", key = "111")
#[1] "172f052058445afd9fe3afce05bfec573b5bb4c659bfd4cfc69a59d1597a0031"

在Python 3中:

In Python 3:

import hmac
import hashlib
print(hmac.new(b"111", b"test@gmail.com", hashlib.sha256).hexdigest())
#172f052058445afd9fe3afce05bfec573b5bb4c659bfd4cfc69a59d1597a0031

这篇关于如何在Python 3中从R复制基于SHA256的HMAC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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