首页 新闻 会员 周边

会PHP的大婶帮忙把这个函数翻译成C#的~~

0
悬赏园豆:80 [已解决问题] 解决于 2014-12-19 13:50
hash_hmac('sha256', $payload, $this->client_secret, true)
问题补充:

在C#中的SHA256算法只有一个参数,没有地方输入key参与加密。所以哪个大婶帮帮小弟啊

进击的菜鸟的主页 进击的菜鸟 | 初学一级 | 园豆:105
提问于:2014-12-17 10:04
< >
分享
最佳答案
0

The problem must be the actual representation of the key/message data.

See the following tests:

PHP

#!/usr/bin/php
<?php
print strtoupper(hash_hmac("sha256", "message", "key"));
?>

 Output (live via http://writecodeonline.com/php/): 6E9EF29B75FFFC5B7ABAE527D58FDADB2FE42E7219011976917343065F58ED4A

C#

using System;

using System.Text;

using System.Security.Cryptography;

public class Program {

private const string key = "key";

private const string message = "message";

private static readonly Encoding encoding = Encoding.UTF8;

static void Main(string[] args) {

var keyByte = encoding.GetBytes(key);

using (var hmacsha256 = new HMACSHA256(keyByte)) { hmacsha256.ComputeHash(encoding.GetBytes(message));

Console.WriteLine("Result: {0}", ByteToString(hmacsha256.Hash));

}

}

static string ByteToString(byte[] buff) {

string sbinary = "";

for (int i = 0; i < buff.Length; i++)

sbinary += buff[i].ToString("X2");

/* hex format */ return sbinary; }

}

Output (live via http://ideone.com/JdpeL): Result: 6E9EF29B75FFFC5B7ABAE527D58FDADB2FE42E7219011976917343065F58ED4A

So, check the character set/encoding of the PHP input data. Also check the actual algorithm (in $pbx_hash).

 

爱编程,不求甚解。

其实我不懂PHP,也不懂C#,看着上面的代码好象是对的,在网上试运行了一下,发现暂时也是对的,就当他是对的,等不对的时候再Google。

收获园豆:40
爱编程的大叔 | 高人七级 |园豆:30839 | 2014-12-17 10:11
其他回答(4)
0

http://php.net/manual/en/function.hash-hmac.php

收获园豆:10
幻天芒 | 园豆:37175 (高人七级) | 2014-12-17 10:22
0
  private Object hash_hmac(string signatureString, string secretKey, bool raw_output = false)
        {
            var enc = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
            hmac.Initialize();

            byte[] buffer = enc.GetBytes(signatureString);
            if (raw_output)
            {
                return hmac.ComputeHash(buffer);
            }
            else
            {
                return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
            }
        }
收获园豆:10
✎﹏ℳ๓₯㎕ღ | 园豆:1499 (小虾三级) | 2014-12-17 11:05
0

不懂php,直接把key加到‘sha256’后面不行吗?

hash_hmac('sha256'.key, $payload, $this->client_secret, true)

 哦看错。

就是把key加到你要加密的字符串后面

收获园豆:10
alone__ | 园豆:60 (初学一级) | 2014-12-17 11:53
0

LZ要利用好msdn啊。

HMACSHA256 的构造函数之一就是Key.

答案1感觉是在搞笑啊 :D

收获园豆:10
_龙猫 | 园豆:240 (菜鸟二级) | 2014-12-17 13:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册