Skip to content

Instantly share code, notes, and snippets.

@huzemin
Created August 19, 2016 15:02
Show Gist options
  • Save huzemin/349cf48fc4c7912c059bfde5000b5ed0 to your computer and use it in GitHub Desktop.
Save huzemin/349cf48fc4c7912c059bfde5000b5ed0 to your computer and use it in GitHub Desktop.
<?php
/**
* 使用openssl进行加密解密范例
* @author 胡泽民<[email protected]>
*/
$data = "Hello world";
// 加密
$public_pem_str = file_get_contents("./openssl_key/public.pem");
$public_key = openssl_pkey_get_public($public_key_str);
if(openssl_public_encrypt($data, $encrypt_data, $public_key )) {
echo base64_encode($encrypt_data);
}
// 解密
$private_pem_str = file_get_contents("./openssl_key/private.pem");
$private_key = openssl_pkey_get_private($private_pem_str, 'pass phrase');
echo openssl_private_decrypt($encrypt_data, $decrypt_data, $private_key);
echo $decrypt_data;

操作步骤

  1. 创建私钥
openssl genrsa -des3 -out private.pem 2048
  1. 创建公钥
openssl rsa -in private.pem -outform PEM -pubout -out public.pem    

注意

在创建密钥的时候,曾尝试使用ssh-keygen进行出rsa公钥和密钥,然后使用PHP的openssl模块进行加密和解密,但是都是以失败告终。 因为创建出来的密钥rsa公钥格式不是pem或者cer格式。 解决方法

Warning: openssl_public_encrypt(): key parameter is not a valid public key in

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment