C#实现php的hash_hmac函数

简介:

PHP代码示例如下

<?php

复制代码
$res1 = hash_hmac( " sha1 ", " signatureString ", " secret ");
echo $res1. " \n ";
// ee1b654aa861c41fd5813dc365ef106c9801f8f6
echo base64_encode($res1). " \n ";
// ZWUxYjY1NGFhODYxYzQxZmQ1ODEzZGMzNjVlZjEwNmM5ODAxZjhmNg==

$res2 = hash_hmac( " sha1 ", " signatureString ", " secret ", true);
// echo "$res2\n"; // binary byte[]
$data = unpack( ' C* ', $res2);
print_r($data);
/*
Array
(
[1] => 238
[2] => 27
[3] => 101
[4] => 74
[5] => 168
[6] => 97
[7] => 196
[8] => 31
[9] => 213
[10] => 129
[11] => 61
[12] => 195
[13] => 101
[14] => 239
[15] => 16
[16] => 108
[17] => 152
[18] => 1
[19] => 248
[20] => 246
)

*/

echo base64_encode( " $res2\n ");
// 7htlSqhhxB/VgT3DZe8QbJgB+PYK
?>
复制代码

C#代码示例如下

using System;

复制代码
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace ConsoleApplication1
{
class Program
{
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();
}
}

static void Main( string[] args)
{
Program p = new Program();
String res1 = (String)p.hash_hmac( " signatureString ", " secret ");
Console.WriteLine(res1);
// ee1b654aa861c41fd5813dc365ef106c9801f8f6
Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(res1)));
// ZWUxYjY1NGFhODYxYzQxZmQ1ODEzZGMzNjVlZjEwNmM5ODAxZjhmNg==

byte[] ret = ( byte[])p.hash_hmac( " signatureString ", " secret ", true);
for ( int i = 0; i < ret.Length; i++) {
Console.Write(ret[i] + " ");
}
// 238 27 101 74 168 97 196 31 213 129 61 195 101 239 16 108 152 1 248 246
Console.WriteLine();

Console.WriteLine(Convert.ToBase64String(ret));
// 7htlSqhhxB/VgT3DZe8QbJgB+PY=
}
}
}
复制代码



本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/5743517.html,如需转载请自行联系原作者
相关文章
|
4月前
|
Shell PHP Windows
PHP代码审计(四)PHP文件操作函数(2)
改变文件所有者。如果成功则返回 TRUE,如果失败则返回 FALSE。 语法:chown(file,owner)
37 0
|
4月前
|
安全 Unix Shell
PHP代码审计(四)PHP文件操作函数(1)
改变文件所有者。如果成功则返回 TRUE,如果失败则返回 FALSE。 语法:chown(file,owner)
38 0
|
4月前
|
小程序 PHP 数据安全/隐私保护
php图片加水印函数
这里分享下php给图片加水印的几个自定义函数 给图片加水印首先需要开启GD库。 用到的php函数是imagecopymerge () 和 imagecopy () imagecopymerge 函数可以支持两个图像叠加时,设置叠加的透明度
45 0
|
7月前
|
PHP
PHP 常用系统函数
PHP 常用系统函数
39 0
|
2月前
|
PHP
从建站到拿站 -- PHP判断循环及函数
从建站到拿站 -- PHP判断循环及函数
12 0
|
2月前
|
PHP
从PHP开始学渗透 -- 函数
从PHP开始学渗透 -- 函数
8 0
php案例:判断这个是繁体字还是简体字(满足绝大部分字符)用php函数
php案例:判断这个是繁体字还是简体字(满足绝大部分字符)用php函数
php案例:判断这个是繁体字还是简体字(满足绝大部分字符)用php函数
|
3月前
|
PHP 数据安全/隐私保护
|
8月前
|
PHP 数据安全/隐私保护
php获取随机不重复数字(封装函数直接拿来用)
在PHP中获取随机值这种操作非常常见,比如订单号,密码加密,以及验证码等,那么在本文介绍一种获取随机不重复数字的函数。
56 0
|
4月前
|
小程序 Shell PHP
PHP代码审计(四)PHP文件操作函数(3)
改变文件所有者。如果成功则返回 TRUE,如果失败则返回 FALSE。 语法:chown(file,owner)
20 0