Recently and an insurance company docking interface, the other side requires RSA encryption, and to a *.jks file, online search has no answer, and finally on Google accidentally saw a person said need to turn into. Pem to read, toss some directly on the code:
1 /**2 * Get RSA encryption key3 *4 * @author RTS December 24, 2015 15:55:095 * @return String | | bool6 */7 Static Publicfunction Getrsaprivatekey () {8Extension_loaded ('OpenSSL') or Die ('php no extension OpenSSL' );9$privateKeyFilePath = Api_root. Directory_separator.'Data'. Directory_separator.'Key.pem';Ten$publicKeyFilePath =$privateKeyFilePath; One(File_exists ($privateKeyFilePath)) or Die ('Key Path Err' ); A$privateKey = Openssl_pkey_get_private (file_get_contents ($privateKeyFilePath),'123456' ); -($privateKey) or Die ("Key Get Failure" ); - return$privateKey; the}
Openssl_pkey_get_private The second parameter is to read the password, for this has been pit for a long time, above is to get the private key, the following is the data encryption:
1 /**2 * Ssl_encrypt3 *4 * @param unknown $source5 * @param unknown $type6 * @param unknown $key7 * @author RTS December 24, 2015 15:40:468 * @return ambigous <string, unknown>9 */Ten Public Staticfunction Sslencrypt ($source, $type, $key) { One$maxlength =117; A$output ="'; - while($source) { -$input = substr ($source,0, $maxlength); the$source =substr ($source, $maxlength); - if($type = ='Private') { -$ok =Openssl_private_encrypt ($input, $encrypted, $key); -}Else { +$ok =Openssl_public_encrypt ($input, $encrypted, $key); - } +$output. =$encrypted; A } at return$output; -}
Please leave a message if you have questions.
RSA for PHP