基本使用
代碼
<?php
/*
*
Base64是MIME郵件中常用的編碼方式之一。
主要思想:
1 將輸入的字符串或數(shù)據(jù)編碼成只含有{'A'-'Z', 'a'-'z', '0'-'9', '+', '/'}這64個(gè)可打印字符的串,故稱為“Base64”壕探。
編碼的方法:
2 將輸入數(shù)據(jù)流每次取6 bit谭网,用此6 bit的值(0-63)作為索引去查表十办,輸出相應(yīng)字符谴餐。這樣妙蔗,每3個(gè)字節(jié)將編碼為4個(gè)字符(3×8 → 4×6)蚕冬;不滿4個(gè)字符的以'='填充免猾。
*/
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 2048, //字節(jié)數(shù) 512 1024 2048 4096 等 ,不能加引號(hào),此處長(zhǎng)度與加密的字符串長(zhǎng)度有關(guān)系囤热,可以自己測(cè)試一下
"private_key_type" => OPENSSL_KEYTYPE_RSA, //加密類型
);
$resource = openssl_pkey_new($config);
//提取私鑰
openssl_pkey_export($resource, $privateKey);
//生成公鑰
$publicKey = openssl_pkey_get_details($resource)['key'];
echo '------------------創(chuàng)建私鑰---------------------' . PHP_EOL;
echo $privateKey.PHP_EOL;
echo '------------------創(chuàng)建公鑰---------------------' . PHP_EOL;
echo $publicKey.PHP_EOL;
// 加密后內(nèi)容含有特殊字符猎提,需編碼轉(zhuǎn)換
//從證書中提取公鑰
$publicKey = openssl_pkey_get_public($publicKey);
//從證書中提取私鑰
$privateKey = openssl_pkey_get_private($privateKey); // 提取成功返回資源標(biāo)識(shí),錯(cuò)誤返回false is_resource($publicKey)
//原始數(shù)據(jù)
$data = '{"name":"xiaoming","age":"23","address":"beijing"}';
//加密
$encrypted = "";
//解密
$decrypted = "";
echo '原始數(shù)據(jù):' . PHP_EOL . $data . PHP_EOL;
//私鑰加密,公鑰解密
echo '------------------私鑰加密,公鑰解密---------------------' . PHP_EOL;
//私鑰加密
openssl_private_encrypt($data, $encrypted, $privateKey);
//加密后內(nèi)容含有特殊字符,需編碼轉(zhuǎn)換
$encrypted = base64_encode($encrypted);
echo '私鑰加密:' . PHP_EOL, $encrypted . PHP_EOL;
//公鑰解密
openssl_public_decrypt(base64_decode($encrypted), $decrypted, $publicKey);
echo '公鑰解密:' . PHP_EOL, $decrypted . PHP_EOL;
//公鑰加密,私鑰解密
echo '------------------公鑰加密,私鑰解密---------------------' . PHP_EOL;
//加密后內(nèi)容含有特殊字符旁蔼,需編碼轉(zhuǎn)換
openssl_public_encrypt($data, $encrypted, $publicKey);
$encrypted = base64_encode($encrypted);
echo '公鑰加密:' . PHP_EOL, $encrypted . PHP_EOL;
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey);//私鑰解密
echo '私鑰解密:' . PHP_EOL, $decrypted . PHP_EOL;
//釋放key關(guān)聯(lián)秘鑰
openssl_free_key($publicKey);
openssl_free_key($privateKey);
打印結(jié)果
------------------創(chuàng)建私鑰---------------------
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDde+MZc3GTeyfu
PPBDBrZBv9qiMHkpl2aLO25VmVilrjIvdFoGlLO15jqfWhzmPtIok7YY6aNV7CTU
iTW/QD8KRbsFQA0AnjN8iISosTMQ7I2cQ7DOUcuQ9ZJhCsH7JdmdZ9t6JA6epl0P
SL87LJwUP/F6yStFOpDZEnqhJe7KOImp/eKjq937yrLCTP1iPF4iUFhPwakN9cOn
LE44JBVPT/snjpyDlFZPti+suXLscd0Td6KQvGmCM3MpObDmEsTdHpSSc07yMiEP
ihx3DVoicJRjOHdgBwsNcxgPCXRTm3KZ9B1bt6aIEoHMVaWUAf64AMxEo5Wk6tuV
PKUY0QjlAgMBAAECggEBAMkGN9KS2GQupMh0IPIE9olos+z/qAka9KSstXEV9MKz
/7LYnRlaAF657z1REefc3uybXOzxqiFDaw5I1zKWAmG1dpDGWMbV0A9Y7WcbJilX
OxS4z5ID5YrViR1xIS1tZj2a1Tbf4TEX+GD1+zOfQq6Sdv+l9RMpm+yZ/Bmljz2U
MMDsfi4MV4Gtt76uM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----
------------------創(chuàng)建公鑰---------------------
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3XvjGXNxk3sn7jzwQwa2
Qb/aojB5KZdmiztuVZlYpa4yL3RaBpSzteY6n1oc5j7SKJO2GOmjVewk1Ik1v0A/
CkW7BUANAJ4zfIiEqLEzEOyNnEOwzlHLkPWSYQrB+yXZnWfbeiQOnqZdD0i/Oyyc
FD/xeskrRTqQ2RJ6oSXuyjiJqf3io6vd+8qywkz9YjxeIlBYT8GpDfXDpyxOOCQV
T0/7J46cg5RWT7YvrLly7HHdE3eikLxpgjNzKTmw5hLE3R6UknNO8jIhD4ocdw1a
InCUYzh3YAcLDXMYDwl0U5tymfQdW7emiBKBzFWllAH+uADMRKOVpOrblTylGNEI
5QIDAQAB
-----END PUBLIC KEY-----
原始數(shù)據(jù):
{"name":"xiaoming","age":"23","address":"beijing"}
------------------私鑰加密,公鑰解密---------------------
私鑰加密:
JKxCYGsGshnTF9o4HaX7KfcMPGnCcNnnZrWk9lQaSJ17cJbkOO8b/n2s4S2TBLdTy7oqmyqF5+MqR0/Pn08dZNy2oJc9fScjoEzovDsXWLqFXRDrxnoy8RtqYC70B9b6WfQGFesWL6qVhVfvH0xbqhbMQ19z7vyztYd5jy22Vw1jAIgl+3P9VdH5zJJ6eTpnkW0I82c9/vY4nIeMv49dTOjTN8vEcInqBse1pUb2UcnrOsiTzhh+D+0RiGVeWJ6Vx7RYkV6s9D7C+25Zf128MiPsCcEnI6ocfoBMEX/GzaXnT+vxj6b3vqJu738n7bF+dxNJnrr2iPzLF5JzpoFaEQ==
公鑰解密:
{"name":"xiaoming","age":"23","address":"beijing"}
------------------公鑰加密,私鑰解密---------------------
公鑰加密:
kEhne7tYqjmhBJqTq5GXop9OE5FBbDVBtcCKpBONrfTjbcZa0WPqyi2meCg/gNWzk8hI6KF5V5H9UIZBE74DJMQk2s/DcYQY/0zHuxaV4zgrD7TDVhTwM/YfnpR9xlf4JBnoY27M5eULaxf0Rj70nxwW/QGldZ/lhHpN/kZBlTmonSjfiEpm1WnWvZGSZVTib75/70kGDhl8ykpTZLRt9/CFIIgpf+U0WiSoOa3FRnFx/BTiAtWWYWSiIwMs7pzxM+UWPGy9m4FPPJgAhy8/AO9GKBWfpk3WFzz38OQTCsS/X+QkuUbDO7mSSalkTsYWTXTWv4GbPdcUaUYSkB97/g==
私鑰解密:
{"name":"xiaoming","age":"23","address":"beijing"}
封裝類
class
<?php
/**
* 生成證書文件及加密解密
* Class Rsa
*/
class Rsa
{
public $publicKey = '';
public $privateKey = '';
/**
* 獲取證書文件
* @param $publicKey
* @param $privateKey
*/
public function __construct($publicKey, $privateKey)
{
$this->publicKey = $publicKey;
$this->privateKey = $privateKey;
}
/**
* 加密解密
* @param $string
* @param string $operation
* @return string
*/
public function authcode($string, $operation = 'encrypt')
{
if (!(file_exists($this->publicKey) || file_exists($this->privateKey))) {
echo '秘鑰文件不存在';
return false;
}
$publicKey = openssl_pkey_get_public(file_get_contents($this->publicKey));
$privateKey = openssl_pkey_get_private(file_get_contents($this->privateKey));
if (!($privateKey || $publicKey)) {
echo '證書錯(cuò)誤';
return false;
}
$data = "";
if ($operation == 'decrypt') {
openssl_private_decrypt(base64_decode($string), $data, $privateKey);
} else {
openssl_public_encrypt($string, $data, $publicKey);
$data = base64_encode($data);
}
return $data;
}
/**
* 生成證書
* @return bool
*/
public function exportOpenSSLFile()
{
$publicKey = $privateKey = '';
$dir = './conf';
$conf = 'openssl.cnf';
if (!is_dir($dir)) {
mkdir($dir,0700);
}
if (!file_exists($conf)) {
touch($dir . '/' . $conf);
}
//參數(shù)設(shè)置
$config = [
"digest_alg" => "sha512",
//字節(jié)數(shù) 512 1024 2048 4096 等
"private_key_bits" => 2048,
"config" => "./conf/openssl.cnf",
//加密類型
"private_key_type" => OPENSSL_KEYTYPE_RSA,
];
//創(chuàng)建私鑰和公鑰
$res = openssl_pkey_new($config);
if ($res == false) {
//創(chuàng)建失敗,請(qǐng)檢查openssl.cnf文件是否存在
echo '生成秘鑰失敗';
return false;
}
//將密鑰導(dǎo)出為PEM編碼的字符串锨苏,并輸出(通過引用傳遞)。
openssl_pkey_export($res, $privateKey, null, $config);
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey["key"];
//生成證書
$createPublicFileRet = file_put_contents($this->publicKey, $publicKey);
$createPrivateFileRet = file_put_contents($this->privateKey, $privateKey);
if (!($createPublicFileRet || $createPrivateFileRet)) {
echo '創(chuàng)建秘鑰文件失敗';
return false;
}
openssl_free_key($res);
return true;
}
}
$certPublic = "./conf/cert_public.key";
$certPrivate = "./conf/cert_private.key";
$rsaObj = new Rsa($certPublic, $certPrivate);
//生成證書
$rsaObj->exportOpenSSLFile();
//原始數(shù)據(jù)
$sourceDat = '{"name":"jack","age":"22","address":"beijing"}';
echo 'source data:' . PHP_EOL, $sourceDat . PHP_EOL;
//加密
$encryptStr = $rsaObj->authcode($sourceDat);
echo 'string encrypt:' . PHP_EOL, $encryptStr . PHP_EOL;
//解密
$decryptStr = $rsaObj->authcode($encryptStr, 'decrypt');
echo 'string decrypt:' . PHP_EOL, $decryptStr . PHP_EOL;
輸出
source data:
{"name":"jack","age":"22","address":"beijing"}
string encrypt:
hikoQAKwt9jztThG4SoepMnRsd/VqkpgUubnP6tFHqvsAEka9mPm5QLNFSW07p2l+5KJYOkNOX8IDQ+YXid2kivLnDc3RWHOsACw3nFnb28SbTsqv/QRLteRqXrj/zt/s02V9qQ/s/WZOHPRrKMqkVIbo1yrncT1YhdPWPeeY/6BBUWB7YS2a2IzN1Yo/MmGUtxqPTzXwUhdTztu7kVJnwF6sJK8Dus+2PsAdvbNSNrZGHIEKfKueaThn0QN55vzsK88wnuMpyJcpfK8O2WtwdIFVvBboZH9sNNCU80nUM3ma/Xpewash/Zac1ZX1jgxdfsNxmh73aV8eaOQyXzjCw==
string decrypt:
{"name":"jack","age":"22","address":"beijing"}
生成文件
$ tree conf/
conf/
├── cert_private.key
├── cert_public.key
└── openssl.cnf
0 directories, 3 files