码迷,mamicode.com
首页 > Web开发 > 详细

RSA For PHP

时间:2016-05-09 18:39:47      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

最近和一保险公司对接接口,对方要求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     }

有问题请留言。

RSA For PHP

标签:

原文地址:http://www.cnblogs.com/renren/p/5474830.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!