base64 java php,Base64_en code Java和PHP之间的不同

本文讨论了在Java和PHP中使用HMAC-SHA256生成签名时遇到的问题。作者指出,尽管两个函数在生成密钥阶段结果相同,但在Base64编码前,PHP的`hash_hmac`函数默认输出的是十六进制形式,而Java则是原始二进制数据。为使结果一致,需在PHP中将`hash_hmac`的第三个参数设为`true`以获取二进制输出。
摘要由CSDN通过智能技术生成

Here is my problem :

I have a JAVA function to generate an encrypted string. I have to do the same thing in PHP.

My Java function :

String generateSignature () {

byte[] Sequence = ("hello").getBytes("UTF-8");

Mac HMAC = Mac.getInstance("HMACSHA256");

HMAC.init("SECRET_KEY");

byte[] Hash = HMAC.doFinal(Sequence);

String Signature = new String(Base64.encodeBase64(Hash));

return Signature;

}

My PHP function :

function generateSignature() {

$sequence = "hello";

$encrypted = hash_hmac('sha256', $sequence, "SECRET_KEY");

return base64_encode($encrypted);

}

The return value of the two functions are not the same. What I noticed is that before the encoding to base 64, both functions have the same result. So, for me the problem is not on the generation of the key but on the encoding.

Anybody able to help please ?

解决方案

The answer is in the documentation for the PHP function hash_hmac.

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Pass "true" as the final argument. Hashes are binary. When turning them into strings, they are often encoded in hexadecimal. But in this case you are going to base-64 encode it, so you want the raw binary form.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值