PHP
将JAVA的SHA-256算法计算HASH值转换成PHP
本篇博客将为大家分享如何将JAVA的SHA-256算法计算HASH值转换成PHP
昨天博主在帮前端同事做接口,需要从银联卡API调取一个接口,遇到了需要SHA-256算法计算HASH值传过去,博主也是百度了一番,最后在一篇不起眼的文章中找到了思路,所以记录下来,分享给大家。
JAVA版的:
/**
* 签名算法
*
* @param body
* 报文体
* @param ts
* 时间戳
* @param signature
* 密钥
* @return
*/
public static String sign(String body, String ts, String signature) {
String sign = EncodeUtils.encodeBySHA256(signature + body + ts);
return sign;
}
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* encode By SHA-256
*
* @param str
* @return
*/
public static String encodeBySHA256(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.reset();
messageDigest.update(str.getBytes(“UTF-8”));
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes
* the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}PHP版本的:
$sign=hash('sha256', $string);以上就是转换实现过程,是不是简单得不可思议,起初博主也是有点怀疑,不过后面还真的可以,所以PHP还是很方便的,以上就是博主跟大家分享的内容。
0条评论