zoukankan      html  css  js  c++  java
  • 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     }

    有问题请留言。

  • 相关阅读:
    2014/7/24
    POJ 3414 Pots BFS
    hdu5119 Happy Matt Friends(dp)
    hdu1285 拓扑排序+优先队列
    串口參数具体解释:波特率,数据位,停止位,奇偶校验位
    浅谈软件销售工作
    设计模式及其学习方法的个人理解
    Apache + Tomcat + JK 集群
    SpringMVC案例2----基于spring2.5的注解实现
    poj
  • 原文地址:https://www.cnblogs.com/renren/p/5474830.html
Copyright © 2011-2022 走看看