编辑这个页面须要登录或更高权限!
openssl_public_encrypt()函数用于使用公钥加密数据。
openssl_public_encrypt()函数将使用公共密钥加密数据。
使用openssl_public_encrypt()函数将对数据进行加密,并且可以使用openssl_private_decrypt()将其解密。
openssl_public_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool
序号 | 参数 | 描述 |
---|---|---|
1 | data | . |
2 | encrypted | 它将拥有加密的数据。 |
3 | key | 公钥。 |
4 | padding | 您可以应用的填充为:OPENSSL_PKCS1_PADDING,OPENSSL_SSLV23_PADDING,OPENSSL_PKCS1_OAEP_PADDING,OPENSSL_NO_PADDING。 |
PHP openssl_public_encrypt()函数成功时返回TRUE,失败时返回FALSE。
此函数将从大于5.0.0的PHP版本开始工作。
使用openssl_public_encrypt() 使用公钥加密数据:
<?php //保存私钥 $privkey = openssl_pkey_new(); openssl_pkey_export_to_file($privkey, 'C:/xampp/htdocs/modules/openssl/privatekey.pem'); //保存公钥 $dn = array( "countryName" => "IN", "stateOrProvinceName" => "Karnataka", "localityName" => "test1", "organizationName" => "test2", "organizationalUnitName" => "test3", "commonName" => "www.test.com", "emailAddress" => "xyz@test.com" ); $cert = openssl_csr_new($dn, $privkey); $cert = openssl_csr_sign($cert, null, $privkey, 365); openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/publickey.pem'); //加密数据 $data = 'Welcome To TuorialsPoint'; $isvalid = openssl_public_encrypt ($data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING); echo "Data encryption : ".$crypted; ?>
这将产生以下结果:
Data encryption : ��E �wC�ݭ�+c��f*��o���W�7�EW��$�p�.rng�_N��A1���2Uݴ~s�ap۳)w��=� ��#���g;���u��_%�Z�bb�&��m��v&����q��k
要使用openssl_public_encrypt()加密数据并使用openssl_private_decrypt()解密:
<?php //保存私钥 $privkey = openssl_pkey_new(); openssl_pkey_export_to_file($privkey, 'C:/xampp/htdocs/modules/openssl/privatekey.pem'); //保存公钥 $dn = array( "countryName" => "IN", "stateOrProvinceName" => "Karnataka", "localityName" => "test1", "organizationName" => "test2", "organizationalUnitName" => "test3", "commonName" => "www.test.com", "emailAddress" => "xyz@test.com" ); $cert = openssl_csr_new($dn, $privkey); $cert = openssl_csr_sign($cert, null, $privkey, 365); openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/publickey.pem'); //加密数据 $data = 'Welcome To (cainiaojc.com)'; $isvalid = openssl_public_encrypt ($data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING); echo "Data encryption : ".$crypted; echo ">br/<>br/<"; if ($isvalid) { openssl_private_decrypt ($crypted, $decrypted , file_get_contents('C:/xampp/htdocs/modules/openssl/privatekey.pem'),OPENSSL_PKCS1_PADDING); echo "Data decryption : ".$decrypted; } ?>
这将产生以下结果:
Data encryption : L�_}{�E*?���9[w����7p �\ϸI�?ݟ'��ݹ�n��!����ɿ�*����Xcw�����Ւ�)��/��{��!j�L��I*Ï"9eV�9�=Y\�m�i䁦�M(�0PJ���Ԇ�9��C�`�a�ݧ�b���a��?�m�G$i��eU/[�eU����\=�zLdŌn"��:[\�UA��ԭ�ힲ2@-"d��s�=2�nˣ�h��q5U��浿���9�{ݼ��|�NE�a! Data decryption : Welcome To (cainiaojc.com)