Java Sha1 in PHP

不问归期 提交于 2021-02-07 11:11:33

问题


How to get the this Java SHA1 Result in PHP ?

    // Generating the Signature - Java
// import java.security.MessageDigest;
// import org.apache.commons.codec.binary.Base64;

String userId; 
String applicationKey; // E.g. "196087a1-e815-4bc4-8984-60d8d8a43f1d";
String applicationSecret; // E.g. "oYdgGRXoxEuJhGDY2KQ/HQ==";
long sequence; // fetch and increment last used sequence

String toSign = userId + applicationKey + sequence + applicationSecret;

MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] hash = messageDigest.digest(toSign.getBytes("UTF-8"));

String signature = Base64.encodeBase64String(hash).trim();

I need the UTF-8 Sha1 On PHP, thank you

These code output different result than java utf-8 sha-1:

1:

$toSign_base64 = trim(base64_encode($toSign));
$toSign_digest = trim(hash_hmac('sha1', base64_decode($toSign_base64), "", true));
$signature = trim(base64_encode($toSign_digest));

2:

$signature = trim(sha1($toSign));

3:

$signature = trim(base64_encode(sha1($toSign)));

Result:

"raw": "849165ca-7af7-4951-6969-e19fc9f50b66",
"java_utf8_sha1": "1kBtMaSGLLiUfoSh9qJaxQGZTiQ=",
"code_1": "07PGV/+gMgCylXyA2qPJ92y1eSo=",
"code_2": "d6406d31a4862cb8947e84a1f6a25ac501994e24",
"code_3": "ZDY0MDZkMzFhNDg2MmNiODk0N2U4NGExZjZhMjVhYzUwMTk5NGUyNA=="

回答1:


I am 90% sure the php function sha1(); does it with utf8 encoding, Output as raw, then base64_encode it, so

<?php  base64_encode( sha1("849165ca-7af7-4951-6969-e19fc9f50b66", true) ); ?>

and see if it gives you the same as java ( I do not know java, only php )



来源:https://stackoverflow.com/questions/43659283/java-sha1-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!