gpt4 book ai didi

c# - 将 Python 代码转换为 C# 代码(生成 HMAC)

转载 作者:行者123 更新时间:2023-11-30 22:10:20 27 4
gpt4 key购买 nike

在 C# 中,我必须根据以下 python 代码创建 MD5 hmac token 。

from hashlib import md5 

trans_5C = "".join(chr(x ^ 0x5c) for x in xrange(256))
trans_36 = "".join(chr(x ^ 0x36) for x in xrange(256))
blocksize = md5().block_size

def hmac_md5(key, msg):
if len(key) > blocksize:
key = md5(key).digest()
key += chr(0) * (blocksize - len(key))
o_key_pad = key.translate(trans_5C)
i_key_pad = key.translate(trans_36)
return md5(o_key_pad + md5(i_key_pad + msg).digest())

if __name__ == "__main__":
h = hmac_md5("9T5zhB4sTNGxMJ-iDdO-Ow"+"8rdp7erdig0m6aa72lhanvuk01"+"pizza1", "1387797294")
print h.hexdigest() # 9036a1a3f654aefeab426e9f7e17288e

因为在 windowsphone8 中我们没有 MD5 实现所以我从 here 下载了 MD5 类感谢杰夫。它可以生成 MD5,但我的问题仍然存在。上面的 Python 代码生成了所需的确切 token 9036a1a3f654aefeab426e9f7e17288e,但我生成的是 8280c9a3804b53792324b62363fc22fd。

谁能把python代码翻译成c#?

我下面的 C# 代码非常简单。

string token = string.Empty;
string key = "9T5zhB4sTNGxMJ-iDdO-Ow" + "8rdp7erdig0m6aa72lhanvuk01" + "pizza1";
string message = "1387797294";
Encoding encoding = Encoding.UTF8;

//token 9036a1a3f654aefeab426e9f7e17288e
Debug.WriteLine(MD5.GetMd5String(message + key));

最佳答案

首先,在python中,你可以简单地使用hmac模块:

>>> import hmac
>>> hmac.new("9T5zhB4sTNGxMJ-iDdO-Ow"+"8rdp7erdig0m6aa72lhanvuk01"+"pizza1", "1387797294").hexdigest()
'9036a1a3f654aefeab426e9f7e17288e'

其次,你的C#代码没有实现HMAC算法,只是简单的返回了一个MD5哈希值。python 等价物将是简单的

>>> import md5
>>> md5.new("1387797294" + "9T5zhB4sTNGxMJ-iDdO-Ow"+"8rdp7erdig0m6aa72lhanvuk01"+"pizza1").hexdigest()
'8280c9a3804b53792324b62363fc22fd'

您可以在 C# 中找到 HMAC 算法的实现,例如在 CodePlex .

来自项目页面:

Project Description
This is a simple implementation of the MD5 cryptographic hashing algorithm and HMAC-MD5. This class consists of fully transparent C# code, suitable for use in .NET, Silverlight and WP7 applications.


此外,这是我想出的另一个简单实现:

string key = "9T5zhB4sTNGxMJ-iDdO-Ow" + "8rdp7erdig0m6aa72lhanvuk01" + "pizza1";
string message = "1387797294";

var encoding = Encoding.UTF8;
var md = System.Security.Cryptography.MD5CryptoServiceProvider.Create();
var trans_5C = new byte[64];
var trans_36 = new byte[64];

var b_key = encoding.GetBytes(key);
// TODO: also check if key is to short
if (b_key.Length > 64)
b_key = md.ComputeHash(b_key);

for (int i = 0; i < 64; i++)
{
trans_5C[i] = 92;
trans_36[i] = 54;
if (i < key.Length)
{
trans_5C[i] ^= b_key[i];
trans_36[i] ^= b_key[i];
}
}

byte[] inner = md.ComputeHash(trans_36.Concat(encoding.GetBytes(message)).ToArray());
var hash = md.ComputeHash(trans_5C.Concat(inner).ToArray());

StringBuilder sb = new StringBuilder();
foreach (byte b in hash)
sb.Append(b.ToString("x2"));
var result = sb.ToString(); // = 9036a1a3f654aefeab426e9f7e17288e

关于c# - 将 Python 代码转换为 C# 代码(生成 HMAC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20879059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com