RSA For PHP

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

 1 /**
 2      * 获取RSA加密key
 3      *
 4      * @author RTS 2015年12月24日15:55:09
 5      * @return string || bool
 6      */
 7     static public function getRSAprivateKey() {
 8         extension_loaded ( 'openssl' ) or die ( 'php no extension openssl' );
 9         $privateKeyFilePath = API_ROOT . DIRECTORY_SEPARATOR . 'Data' . DIRECTORY_SEPARATOR . 'key.pem';
10         $publicKeyFilePath = $privateKeyFilePath;
11         (file_exists ( $privateKeyFilePath )) or die ( 'key path err' );
12         $privateKey = openssl_pkey_get_private ( file_get_contents ( $privateKeyFilePath ), '123456' );
13         ($privateKey) or die ( "key get failure" );
14         return $privateKey;
15     }
openssl_pkey_get_private 第二个参数是读取密码,为这个被坑了很久,上面是获取私钥,下面是进行数据加密:

 1 /**
 2      * ssl_encrypt
 3      *
 4      * @param unknown $source            
 5      * @param unknown $type            
 6      * @param unknown $key            
 7      * @author RTS 2015年12月24日15:40:46
 8      * @return Ambigous <string, unknown>
 9      */
10     public static function sslEncrypt($source, $type, $key) {
11         $maxlength = 117;
12         $output = '';
13         while ( $source ) {
14             $input = substr ( $source, 0, $maxlength );
15             $source = substr ( $source, $maxlength );
16             if ($type == 'private') {
17                 $ok = openssl_private_encrypt ( $input, $encrypted, $key );
18             } else {
19                 $ok = openssl_public_encrypt ( $input, $encrypted, $key );
20             }
21             $output .= $encrypted;
22         }
23         return $output;
24     }

有问题请留言。

转载于:https://www.cnblogs.com/renren/p/5474830.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值