如何将Java代码转换为PHP?

时间:2018-07-29 07:56:29

标签: php

我有这段代码在Java中,但是我想要在php中。 有一个将十六进制转换为字节的函数。和主要代码:

public static byte[] ConvertHexStringToByteArray(String s)
{
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}

这是主要代码:

public static String hmacSha1(String value, String key)
{
try
{
// Get an hmac_sha1 key from the raw key bytes byte[]
keyBytes = ConvertHexStringToByteArray(key);
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(StandardCharsets.US_ASCII));
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
return new String(hexBytes, "UTF-8");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}

1 个答案:

答案 0 :(得分:0)

你好

您在php中的Java代码与blow相同:

$key = strtolower($CPCode.$service_id.$price.$timestamp.$request_id);
$authKey = $CPCode;
$sign = hash_hmac("sha1",$key,$authKey);

祝你好运