技术饭
java的非对称ItfRsa.encryptByRSA加密转换成php的openssl RSA加密
java的非对称ItfRsa.encryptByRSA加密转换成php的openssl RSA加密,之前整理了php的openssl加密扩展实现,现在项目用到了RSA加解密,在JAVA与PHP系统之间进行交互,RSA在不同语言的密钥格式不一样,所以过程中主要还是密钥转换问题,经过不断地尝试研究终于搞定了在Java、PHP的转换,可以参考。
参考:https://www.cnblogs.com/jaamy/p/6118814.html
参考:https://www.copylian.com/technology/520.html
JAVA加密代码:
// 时间
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sys_time = df.format(new Date());
String system_id = "xxxxxxx";
String sign_info = "time:"+sys_time+"@system_id:"+system_id;
byte[] sign_info_byte = sign_info.getBytes("UTF-8");
//平台企业sign_key
String sign_key = "xxxxxxxx"; // 16进制key
byte[] sign_key_byte=ItfRsa.toByteArray(sign_key);
//获取sign
byte[] sign_encrypt = ItfRsa.encryptByRSA(sign_key_byte, sign_info_byte);
String sign = ItfRsa.toHexString(sign_encrypt); //转成16进制
public static byte[] encryptByRSA(byte[] pubKeyInByte, byte[] data) {
try {
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);
PublicKey pubKey = mykeyFactory.generatePublic(pub_spec); //转成公钥:-----BEGIN PUBLIC KEY-----xxx-----END PUBLIC KEY----
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(1, pubKey);
return cipher.doFinal(data);
} catch (Exception var6) {
return null;
}
}
PHP代码:
/**
* 获取签名
* @param $reqData
* @return string
*/
protected function getSign(){
//加密信息
$sign_info = "time:".date("Y-m-d H:i:s")."@system_id:".$this->system_id;
//公钥:16进制的key转成2进制,然后将进行base64_encode加密
$pubKey = "-----BEGIN PUBLIC KEY-----\n".base64_encode(hex2bin($this->sign_key))."\n-----END PUBLIC KEY-----";
//加密
openssl_public_encrypt($sign_info, $ciphertext, $pubKey, OPENSSL_PKCS1_PADDING);
//返回
return bin2hex($ciphertext);
}
文明上网理性发言!