使用PHP进行HMAC-SHA1签名,并通过Authorization头认证Deom

$app_id = 'id';
$host = "test.abc.com";
$port = "80";
$app_Key = "key";
$app_timestamp = time();
$app_nonce = "8FINtYTUsKbSZGfl".time().rand(10,1000);
$uri = "/account/ass/verify.do"; //build string
$arr = array($app_timestamp, $app_nonce, "POST", $uri, $host, $port);
$text = join("\n", $arr) . "\n\n";
var_dump($text);
$sig = get_signature($text, $app_Key);
var_dump($sig); $headers=array();
$headers[] = "Authorization: MAC id=\"$app_id\",ts=\"$app_timestamp\",nonce=\"$app_nonce\",mac=\"$sig\"";
$headers[]="Content-Type: application/json"; $data='{"h":"2D4D9BE245FC4172989BC5FAD7EC8784","n":"97C5237B","t":"1428462620","v":"8F2ACF569FCBFDA9081248486240170B325AFF6D"}'; $result = curlPost('http://t-id.gionee.com'.$uri, $headers, $data); /**
* @使用HMAC-SHA1算法生成oauth_signature签名值
*
* @param $key 密钥
* @param $str 源串
*
* @return 签名值
*/ function get_signature($str, $key) {
$signature = "";
if (function_exists('hash_hmac')) {
$signature = base64_encode(hash_hmac("sha1", $str, $key, true));
} else {
$blocksize = 64;
$hashfunc = 'sha1';
if (strlen($key) > $blocksize) {
$key = pack('H*', $hashfunc($key));
}
$key = str_pad($key, $blocksize, chr(0x00));
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
$hmac = pack(
'H*', $hashfunc(
($key ^ $opad) . pack(
'H*', $hashfunc(
($key ^ $ipad) . $str
)
)
)
);
$signature = base64_encode($hmac);
}
return $signature;
} function curlPost($url, $headers = array(), $data = array()) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //设置不验证ssl, 发送https接口请求时需要加此行
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //设置不验证ssl, 发送https接口请求时需要加此行
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
var_dump('set header');
var_dump($headers);
}
$output = curl_exec($ch);
curl_close($ch);
return $output;
}

附:java算法示例:

package net.svr.cas.test.demo;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import net.iharder.Base64; public class sig_demo_app {
private static final String MAC_NAME = "HmacSHA1";
private static final String UTF8 = "UTF-8";
private static final byte[] BYTEARRAY = new byte[0]; public static void main(String[] args) {
String host = "id.test.cn";
String port = "443";
String app_Key = "请填写你的AppKey";
String app_timestamp = "1369732102";
String app_nonce = "8FINtYTUsKbSZGfl";
String uri = "/account/verify.do"; String sig = macSig(host, port, app_Key, app_timestamp, app_nonce, "POST", uri);
System.out.println(sig);
} public static String macSig(String host, String port, String macKey, String timestamp, String nonce, String method, String uri) {
// 1. build mac string
// 2. hmac-sha1
// 3. base64-encoded StringBuffer buffer = new StringBuffer();
buffer.append(timestamp).append("\n");
buffer.append(nonce).append("\n");
buffer.append(method.toUpperCase()).append("\n");
buffer.append(uri).append("\n");
buffer.append(host.toLowerCase()).append("\n");
buffer.append(port).append("\n");
buffer.append("\n");
String text = buffer.toString(); System.out.println(text); byte[] ciphertext = null;
try {
ciphertext = hmacSHA1Encrypt(macKey, text);
} catch (Throwable e) {
return null;
} String sigString = Base64.encodeBytes(ciphertext);
return sigString;
} public static byte[] hmacSHA1Encrypt(String encryptKey, String encryptText) throws InvalidKeyException, NoSuchAlgorithmException {
Mac mac = Mac.getInstance(MAC_NAME);
mac.init(new SecretKeySpec(getBytes(encryptKey), MAC_NAME));
return mac.doFinal(getBytes(encryptText));
} public static byte[] getBytes(String value) {
return getBytes(value, UTF8);
} public static byte[] getBytes(String value, String charset) {
if (isNullOrEmpty(value))
return BYTEARRAY;
if (isNullOrEmpty(charset))
charset = UTF8;
try {
return value.getBytes(charset);
} catch (UnsupportedEncodingException e) {
return BYTEARRAY;
}
} public static boolean isNullOrEmpty(String s) {
if (s == null || s.isEmpty() || s.trim().isEmpty())
return true;
return false;
}
}

HMAC-SHA1算法签名及Authorization头认证的更多相关文章

  1. 可以进行SHA-1,SHA-224,SHA-256,SHA-384,SHA-512五种算法签名的工具类,以及简单说明

    import java.security.MessageDigest; public class SignatureSHA { public static String signSHA(String ...

  2. 安全体系(三)——SHA1算法详解

    本文主要讲述使用SHA1算法计算信息摘要的过程. 安全体系(零)—— 加解密算法.消息摘要.消息认证技术.数字签名与公钥证书 安全体系(一)—— DES算法详解 安全体系(二)——RSA算法详解 为保 ...

  3. LoadRunner中调用SHA1算法加密字符串

    参考<SHA-1 hash for LoadRunner>: http://ptfrontline.wordpress.com/2010/03/02/sha-1-hash-for-load ...

  4. asp.net core 自定义认证方式--请求头认证

    asp.net core 自定义认证方式--请求头认证 Intro 最近开始真正的实践了一些网关的东西,最近写几篇文章分享一下我的实践以及遇到的问题. 本文主要介绍网关后面的服务如何进行认证. 解决思 ...

  5. SHA1算法原理【转】

    转自:https://www.cnblogs.com/scu-cjx/p/6878853.html 一.SHA1与MD5差异 SHA1对任意长度明文的预处理和MD5的过程是一样的,即预处理完后的明文长 ...

  6. SHA1算法原理

    一.SHA1与MD5差异 SHA1对任意长度明文的预处理和MD5的过程是一样的,即预处理完后的明文长度是512位的整数倍,但是有一点不同,那就是SHA1的原始报文长度不能超过2的64次方,然后SHA1 ...

  7. delphi自带的SHA1算法

    delphi自带的SHA1算法 uses IdHashSHA, IdGlobal; function SHA1(Input: String): String; begin with TIdHashSH ...

  8. SHA1算法实现及详解

    1 SHA1算法简介 安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准(Digital Signature Standard DSS)里面定义的数字签名算法(Digit ...

  9. javascript实现SHA1算法

    web里面密码直接传到后台是不安全的,有时候需要进行加密,找到一个不错的javascript SHA1算法: <!DOCTYPE html> <html lang="en& ...

随机推荐

  1. IOS开发-表视图LV3导航控制器

    学到这里感觉有点难了,其实这篇文章再草稿箱里放了好久了~ 最近对于学习的热情下降了.这不行-抓紧学习走起! 在这一章节的学习中主要针对导航控制器及表视图来建立多视图的应用, 首先要了解一些概念-- 1 ...

  2. [Windows Phone] 地图控制项的经纬度

    原文:[Windows Phone] 地图控制项的经纬度 前言 本文主要示范如何使用地图经纬度以及显示地标和行人街道,并透过卷轴控制地图缩放比例的功能. ? 实作 step1 建立专案. ? step ...

  3. singleton pattern

    1 normal mode class Singleton { private Singleton(){}; Singleton singleton; static Singleton getInst ...

  4. Android 屏幕实现水龙头事件

    在android下,事件的发生是在监听器下进行,android系统能够响应按键事件和触摸屏事件.事件说明例如以下: onClick(View v)一个普通的点击button事件 boolean onK ...

  5. or1200中IMMU分析(续)

    下面内容摘自<步步惊芯--软核处理器内部设计分析>一书 2 IMMU中的特殊寄存器 OR1200处理器中的IMMU包括第2组特殊寄存器,如表10.1所看到的. ITLBW0MRx是指令TL ...

  6. 乐在其中设计模式(C#) - 适配器模式(Adapter Pattern)

    原文:乐在其中设计模式(C#) - 适配器模式(Adapter Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 适配器模式(Adapter Pattern) 作者:webabc ...

  7. 编译命令行终端 swift

    So, this is where swift lives, after you've installed XCode 6 Beta: /Applications/Xcode6-Beta.app/Co ...

  8. PowerDesigner创建物理模型

    原文:PowerDesigner创建物理模型 Using PowerDesigner Create PDM 1.打开PowerDesigner 按Ctrl+N 创建物理模型 2.创建后修改名称,并在工 ...

  9. 上curl java 模拟http请求

    最近,我的项目要求java模拟http请求,获得dns解决 tcp处理过的信息特定的连接. java api提供urlConnection apache提供的httpClient都不能胜任该需求,二次 ...

  10. Objective C Runtime 开发介绍

    简介 Objective c 语言尽可能的把决定从编译推迟到链接到运行时.只要可能,它就会动态的处理事情.这就意味着它不仅仅需要一个编译器,也需要一个运行时系统来执行变异好的代码.运行时系统就好像是O ...