将以下JAVA代码转为PHP代码:import java.security.spec.*; import java.security.*; import java.util.*; import org.apache.commons.lang3.StringUtils; public class SignUtils { public static String signSHA256(byte[] message, byte[] privateKeyBytes) throws Exception { PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBytes)); KeyFactory keyf = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyf.generatePrivate(priPKCS8); Signature sign = Signature.getInstance("SHA256withRSA"); sign.initSign(privateKey); sign.update(message); return Base64.getEncoder().encodeToString(sign.sign()); } public static String makeSignStr(Map<String, String> params) { List<String> keys = Lists.newArrayList(); for (Map.Entry<String, String> entry : params.entrySet()) { if ("sign".equals(entry.getKey())) { continue; } if (StringUtils.isNotBlank(entry.getValue())) { keys.add(entry.getKey()); } } Collections.sort(keys); List<String> temp = Lists.newArrayList(); for (String key : keys) { String value = params.get(key); temp.add(key + "=" + value); } return StringUtils.join(temp, "&"); } public static void main(String[] args) { try { //读取私钥 byte[] privateKeyBytes = null; Map<String, String> params = new HashMap<>(); params.put("mch_id", "商户编号"); params.put("app_id", "应用ID"); params.put("timestamp", "1541661668"); params.put("nonce_str", "aiz04enx0a2"); params.put("sign_type", "SHA"); params.put("version", "2.0"); params.put("content", "VBDExvz6/k56B1S5n7n3uOvI2sxZixcsV0Tdld92ym0CpnN8ooiCkXPgg0N1z8NC"); //签名 String sign = SignUtils.signSHA256(makeSignStr(params).getBytes("UTF-8"), privateKeyBytes); } catch (Exception e) { e.printStackTrace(); } } }
时间: 2024-02-14 09:17:57 浏览: 109
java 序列化成PHP格式。
以下是将JAVA代码转为PHP代码的结果:
```php
<?php
use phpseclib\Crypt\RSA;
use phpseclib\Math\BigInteger;
class SignUtils {
public static function signSHA256($message, $privateKeyBytes) {
$rsa = new RSA();
$rsa->loadKey($privateKeyBytes);
$rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
$signature = $rsa->sign($message);
return base64_encode($signature);
}
public static function makeSignStr($params) {
$keys = array();
foreach ($params as $key => $value) {
if ($key === 'sign' || empty($value)) {
continue;
}
$keys[] = $key;
}
sort($keys);
$temp = array();
foreach ($keys as $key) {
$value = $params[$key];
$temp[] = $key . '=' . $value;
}
return implode('&', $temp);
}
public static function main() {
try {
// 读取私钥
$privateKeyBytes = null;
$params = array(
'mch_id' => '商户编号',
'app_id' => '应用ID',
'timestamp' => '1541661668',
'nonce_str' => 'aiz04enx0a2',
'sign_type' => 'SHA',
'version' => '2.0',
'content' => 'VBDExvz6/k56B1S5n7n3uOvI2sxZixcsV0Tdld92ym0CpnN8ooiCkXPgg0N1z8NC'
);
// 签名
$sign = SignUtils::signSHA256(
utf8_encode(SignUtils::makeSignStr($params)),
$privateKeyBytes
);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
```
阅读全文