最近和一保险公司对接接口,对方要求RSA加密,并给一个*.jks的文件,网上搜索一番均无答案,最后在谷歌上偶然看到一个人说需要转成.pem进行读取,折腾一番直接上代码:

 /**
* 获取RSA加密key
*
* @author RTS 2015年12月24日15:55:09
* @return string || bool
*/
static public function getRSAprivateKey() {
extension_loaded ( 'openssl' ) or die ( 'php no extension openssl' );
$privateKeyFilePath = API_ROOT . DIRECTORY_SEPARATOR . 'Data' . DIRECTORY_SEPARATOR . 'key.pem';
$publicKeyFilePath = $privateKeyFilePath;
(file_exists ( $privateKeyFilePath )) or die ( 'key path err' );
$privateKey = openssl_pkey_get_private ( file_get_contents ( $privateKeyFilePath ), '' );
($privateKey) or die ( "key get failure" );
return $privateKey;
}
openssl_pkey_get_private 第二个参数是读取密码,为这个被坑了很久,上面是获取私钥,下面是进行数据加密:
 /**
* ssl_encrypt
*
* @param unknown $source
* @param unknown $type
* @param unknown $key
* @author RTS 2015年12月24日15:40:46
* @return Ambigous <string, unknown>
*/
public static function sslEncrypt($source, $type, $key) {
$maxlength = ;
$output = '';
while ( $source ) {
$input = substr ( $source, , $maxlength );
$source = substr ( $source, $maxlength );
if ($type == 'private') {
$ok = openssl_private_encrypt ( $input, $encrypted, $key );
} else {
$ok = openssl_public_encrypt ( $input, $encrypted, $key );
}
$output .= $encrypted;
}
return $output;
}

有问题请留言。

05-11 11:09