首页 > 编程知识 正文

java对php服务器hmac(PHP与Java)

时间:2023-12-10 13:48:24 阅读:314077 作者:BNTA

本文目录一览:

求教PHP和JAVA大神 base64_encode(hash_hmac('sha1',$public_key,$private_key,TRUE)); 转 java

如果你的API服务安全认证协议中要求使用hmac_sha1方法对信息进行编码,

而你的服务是由PHP实现的,客户端是由JAVA实现的,那么为了对签名正确比对,就需要在两者之间建立能匹配的编码方式.

efine('ID','123456');

define('KEY','k123456');

$strToSign = "test_string";

$utf8Str = mb_convert_encoding($strToSign, "UTF-8");

$hmac_sha1_str = base64_encode(hash_hmac("sha1", $utf8Str, KEY));

$signature = urlencode($hmac_sha1_str);

print_r($signature);

JAVA侧需要注意如下几点:

1. hmac_sha1编码结果需要转换成hex格式

2. java中base64的实现和php不一致,其中java并不会在字符串末尾填补=号以把字节数补充为8的整数

3. hmac_sha1并非sha1, hmac_sha1是需要共享密钥的

参考实现如下:

[java] view plain copy

import java.io.UnsupportedEncodingException;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

import org.apache.wicket.util.crypt.Base64UrlSafe;

public class test {

public static void main(String[] args) {

String key = "f85b8b30f73eb2bf5d8063a9224b5e90";

String toHash = "GET"+"n"+"Thu, 09 Aug 2012 13:33:46 +0000"+"n"+"/ApiChannel/Report.m";

//String toHashUtf8 = URLEncoder.encode(toHash, "UTF-8");

String res = hmac_sha1(toHash, key);

//System.out.print(res+"n");

String signature;

try {

signature = new String(Base64UrlSafe.encodeBase64(res.getBytes()),"UTF-8");

signature = appendEqualSign(signature);

System.out.print(signature);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

}

public static String hmac_sha1(String value, String key) {

try {

// Get an hmac_sha1 key from the raw key bytes

byte[] keyBytes = key.getBytes();

SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

// Get an hmac_sha1 Mac instance and initialize with the signing key

Mac mac = Mac.getInstance("HmacSHA1");

mac.init(signingKey);

// Compute the hmac on input data bytes

byte[] rawHmac = mac.doFinal(value.getBytes());

// Convert raw bytes to Hex

String hexBytes = byte2hex(rawHmac);

return hexBytes;

} catch (Exception e) {

throw new RuntimeException(e);

}

}

private static String byte2hex(final byte[] b){

String hs="";

String stmp="";

for (int n=0; nb.length; n++){

stmp=(java.lang.Integer.toHexString(b[n] 0xFF));

if (stmp.length()==1) hs=hs+"0"+stmp;

else hs=hs+stmp;

}

return hs;

}

private static String appendEqualSign(String s){

int len = s.length();

int appendNum = 8 - (int)(len/8);

for (int n=0; nappendNum; n++){

s += "%3D";

}

return s;

}

}

参考:

php程序与java程序之间做数据交互,怎么做

用php的curl模拟浏览器请求是访问java服务器程序

2.用java的一个http类库同样发送http请求来访问PHP服务器

$context=stream_context_create(array('http'=array('method'="GET",'timeout'=30,)));

$string=file_get_contents('',false,$context);//换成java地址

echo '这可不是百度,只是我输出了百度的返回';

echo $string;

php hash_hmac跟java算出来的结果不一样

问题解决代码如下:

public String md5(String txt) {

try{

MessageDigest md = MessageDigest.getInstance("MD5");

md.update(txt.getBytes("GBK")); //问题主要出在这里,Java的字符串是unicode编码,不受源码文件的编码影响;而PHP的编码是和源码文件的编码一致,受源码编码影响。

StringBuffer buf=new StringBuffer();

for(byte b:md.digest()){

buf.append(String.format("%02x", b0xff));

}

return buf.toString();

}catch( Exception e ){

e.printStackTrace();

return null;

}

}

函数HMAC-SHA1

HMAC

根据RFC 2316(Report of the IAB,April 1998),HMAC(散列消息身份验证码: Hashed Message Authentication Code)以及IPSec被认为是Interact安全的关键性核心协议。它不是散列函数,而是采用了将MD5或SHA1散列函数与共享机密密钥(与公钥/私钥对不同)一起使用的消息身份验证机制。基本来说,消息与密钥组合并运行散列函数。然后运行结果与密钥组合并再次运行散列函数。这个128位的结果被截断成96位,成为MAC.

hmac主要应用在身份验证中,它的使用方法是这样的:

1. 客户端发出登录请求(假设是浏览器的GET请求)

2. 服务器返回一个随机值,并在会话中记录这个随机值

3. 客户端将该随机值作为密钥,用户密码进行hmac运算,然后提交给服务器

4. 服务器读取用户数据库中的用户密码和步骤2中发送的随机值做与客户端一样的hmac运算,然后与用户发送的结果比较,如果结果一致则验证用户合法

在这个过程中,可能遭到安全攻击的是服务器发送的随机值和用户发送的hmac结果,而对于截获了这两个值的黑客而言这两个值是没有意义的,绝无获取用户密码的可能性,随机值的引入使hmac只在当前会话中有效,大大增强了安全性和实用性。大多数的语言都实现了hmac算法,比如php的mhash、python的hmac.py、java的MessageDigest类,在web验证中使用hmac也是可行的,用js进行md5运算的速度也是比较快的。

SHA

安全散列算法SHA (Secure Hash Algorithm)是美国国家标准和技术局发布的国家标准FIPS PUB 180-1,一般称为SHA-1。其对长度不超过264二进制位的消息产生160位的消息摘要输出,按512比特块处理其输入。

SHA是一种数据加密算法,该算法经过加密专家多年来的发展和改进已日益完善,现在已成为公认的最安全的散列算法之一,并被广泛使用。该算法的思想是接收一段明文,然后以一种不可逆的方式将它转换成一段(通常更小)密文,也可以简单的理解为取一串输入码(称为预映射或信息),并把它们转化为长度较短、位数固定的输出序列即散列值(也称为信息摘要或信息认证代码)的过程。散列函数值可以说时对明文的一种“指纹”或是“摘要”所以对散列值的数字签名就可以视为对此明文的数字签名。

HMAC_SHA1

HMAC_SHA1(Hashed Message Authentication Code, Secure Hash Algorithm)是一种安全的基于加密hash函数和共享密钥的消息认证协议。它可以有效地防止数据在传输过程中被截获和篡改,维护了数据的完整性、可靠性和安全性。HMAC_SHA1消息认证机制的成功在于一个加密的hash函数、一个加密的随机密钥和一个安全的密钥交换机制。

HMAC_SHA1 其实还是一种散列算法,只不过是用密钥来求取摘要值的散列算法。

HMAC_SHA1算法在身份验证和数据完整性方面可以得到很好的应用,在目前网络安全也得到较好的实现。

怎么用java实现HMAC-SHA1

以下代码为JAVABEAN,加密用

[PHP]

package test;

/*

* Copyright 1997-2001 by Sun Microsystems, Inc.,

* 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.

* All rights reserved.

*

* This software is the confidential and proprietary information

* of Sun Microsystems, Inc. ("Confidential Information". You

* shall not disclose such Confidential Information and shall use

* it only in accordance with the terms of the license agreement

* you entered into with Sun.

*/

import java.security.*;

import javax.crypto.*;

/*

* This program demonstrates how to generate a secret-key object for

* HMAC-SHA1, and initialize an HMAC-SHA1 object with it.

*/

public class initMac {

public initMac() {

}

//定义加密算法

String Algorithm = "HmacSHA1";

public byte[] HmacSHA1(String post) throws Exception {

// Generate secret key for HMAC-SHA1

KeyGenerator kg = KeyGenerator.getInstance(Algorithm);

SecretKey sk = kg.generateKey();

// Get instance of Mac object implementing HMAC-SHA1, and

// initialize it with the above secret key

Mac mac = Mac.getInstance(Algorithm);

mac.init(sk);

byte[] result = mac.doFinal(post.getBytes());

return result;

}

}

[/PHP]

以下代码为调用上面JAVABEAN的部分

[PHP]package test;

import test.initMac;

/**

* pTitle: /p

*

* pDescription: /p

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。