php hmacsha1加密,PHP的HMAC_SHA1算法实现

PHP的HMAC_SHA1算法实现

2018-09-05

267

function getSignature($str, $key) {

$signature = "";

if (function_exists('hash_hmac')) {

$signature = bin2hex(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 = bin2hex($hmac);

}

return $signature;

}

分享到:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HMAC-SHA1是一种常用的加密算法,可以使用Java中的javax.crypto库来实现。以下是Java实现HMAC-SHA1加密的示例代码: ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; public class HmacSha1 { public static void main(String[] args) { String text = "hello world"; String key = "secret_key"; String hmacSha1 = hmacSha1(text, key); System.out.println(hmacSha1); } public static String hmacSha1(String text, String key) { try { Mac hmac = Mac.getInstance("HmacSHA1"); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); hmac.init(secretKey); byte[] digest = hmac.doFinal(text.getBytes()); StringBuilder sb = new StringBuilder(); for (byte b : digest) { sb.append(String.format("%02x", b)); } return sb.toString(); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); return null; } } } ``` 在这个示例中,我们首先定义了一个字符串text和一个密钥key,然后调用hmacSha1方法来获取HMAC-SHA1加密后的结果。在hmacSha1方法中,我们首先使用"javax.crypto.Mac"类获取HmacSHA1算法实例,然后使用密钥初始化该对象。接着,我们调用doFinal方法来计算HMAC-SHA1值,并将结果转换成十六进制字符串返回。 需要注意的是,HMAC-SHA1算法需要一个密钥来进行计算,密钥的长度应该不小于160位(20字节)。在实际应用中,密钥的生成和管理也是非常重要的,需要特别注意。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值