需要先了解的openssl系列函數(shù)
成都創(chuàng)新互聯(lián)公司專注于企業(yè)營銷型網(wǎng)站建設(shè)、網(wǎng)站重做改版、渠縣網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5網(wǎng)站設(shè)計、商城開發(fā)、集團公司官網(wǎng)建設(shè)、外貿(mào)網(wǎng)站制作、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為渠縣等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
- openssl_pkey_get_private 從證書中解析獲取私鑰,以供使用。成功,返回真實的密鑰資源標(biāo)識符(Resource ID),否則返回false
- openssl_pkey_get_public 從證書中解析獲取公鑰,以供使用。成功,返回真實的密鑰資源標(biāo)識符(Resource ID),否則返回false
- openssl_private_encrypt($data, $encrypted, $privateKeyResourceID, OPENSSL_PKCS1_PADDING)
- //使用私鑰key加密數(shù)據(jù)data并且將結(jié)果保存至變量crypted中
- openssl_public_decrypt(base64_decode($encrypted), $decrypted, $publicKeyResourceID, OPENSSL_PKCS1_PADDING)
- //私鑰加密的內(nèi)容通過公鑰可用解密出來
<?php
/**
* Created by PhpStorm.
* User: zrj
* Date: 18-11-7
* Time: 上午10:22
*/
declare(strict_types=1);//開啟強類型模式
//私匙
$privateKeyString = <<<EOF
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAxHS1H/9uMS+waaP8vkEHx0EJWqPnRjYIzHKrXeMQ3fjZmxPG
MJmzwKVdADQlaFbA/NePu7dVFyzFo2yrAFlJD9bWs6of79OM2QGxu/AL2GqwjaOZ
/+5tSkxqU8fj+/sb35U9kGxy/k4KPwlatTaHIkXb7qebCGX1hgNw2BkRrNfXWRX+
EVs8Oy/I/d1CMQMF3mvsCFvoUAE/UJVOOAjjQ6rBX+PorWXuTIKgWgSFWwzsRWJN
hQo6P6Y/amx2Jb6Nr0rHIJIREICdYMAp2DSC+uU+jl85NqT3U89BRRG+58fe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YboLpXTgB+vC7WLwSqWIY8bqjcTawvX
NucBAoGAPGAi11FCqx5R3r/3pJkySlNoj+m/J04mdYXJpmJV6P6PczJHd0aRjvJF
6ubuKot1pExuhEivYo7dYubr5clmh3S8bs9kyS5Q2Btz5kXhxf4EGmJRVD+CAmvi
EAHNljZQgkfonOZFqRXaxqAsqEziIfQqI7IjpTkcGgts4v43Tlo=
-----END RSA PRIVATE KEY-----
EOF;
//公匙
$publicKeyString = <<<EOF
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxHS1H/9uMS+waaP8vkEH
x0EJWqPnRjYIzHKrXeMQ3fjZmxPGMJmzwKVdADQlaFbA/NePu7dVFyzFo2yrAFlJ
D9bWs6of79OM2QGxu/AL2GqwjaOZ/+5tSkxqU8fj+/sb35U9kGxy/k4KPwlatTaH
IkXb7qebCGX1hgNw2BkRrNfXWRX+EVs8Oy/I/d1CMQMF3mvsCFvoUAE/UJVOOAjj
Q6rBX+PorWXuTIKgWgSFWwzsRWJNhQo6P6Y/amx2Jb6Nr0rHIJIREICdYMAp2DSC
+uU+jl85NqT3U89BRRG+58feoUOLDGiv0hRQ7+k1e47MfiwKpCpJOkldEJjywMhl
1QIDAQAB
-----END PUBLIC KEY-----
EOF;
$data = "helloworld";
try {
//從證書中解析獲取私鑰。成功,返回真實的密鑰資源標(biāo)識符
$privateKeyResourceID = openssl_pkey_get_private($privateKeyString);
if ($privateKeyResourceID === false) throw new \Exception('private key string is wrong');
//從證書中解析獲取公鑰,以供使用。成功,返回真實的密鑰資源標(biāo)識符
$publicKeyResourceID = openssl_pkey_get_public($publicKeyString);//這個函數(shù)可用來判斷公鑰是否是可用的
if ($publicKeyResourceID === false) throw new \Exception('public key string is wrong');
//使用私鑰key加密數(shù)據(jù)data并且將結(jié)果保存至變量crypted中。
//加密后的數(shù)據(jù)可以通過openssl_public_decrypt()函數(shù)來解密。
openssl_private_encrypt($data, $encrypted, $privateKeyResourceID, OPENSSL_PKCS1_PADDING);
//私鑰加密
$encrypted = base64_encode($encrypted);//加密之后的結(jié)果,base64只是為了避免特殊字符
openssl_public_decrypt(base64_decode($encrypted), $decrypted, $publicKeyResourceID, OPENSSL_PKCS1_PADDING);//私鑰加密的內(nèi)容通過公鑰可用解密出來
echo $decrypted . PHP_EOL;
} catch (\Exception $e) {
die($e->getMessage());
}
加密、解密系列
- 公鑰加密 openssl_public_encrypt,私鑰解密 openssl_private_decrypt
- 私鑰加密 openssl_private_encrypt,公鑰解密 openssl_public_decrypt
<?php
/**
* Created by PhpStorm.
* User: zrj
* Date: 18-11-5
* Time: 下午8:32
*/
declare(strict_types=1);//開啟強類型模式
class RSA
{
private $publicKeyResourceID = false;//公鑰資源
private $privateKeyresourceID = false;//私鑰資源
private $publicKeyContent = '';
private $privateKeyContent = '';
public function __construct(string $publicKeyPath, string $privatePath)
{
$this->checkFilePath($publicKeyPath);
$this->checkFilePath($privatePath);
$this->publicKeyContent = file_get_contents($publicKeyPath);
$this->privateKeyContent = file_get_contents($privatePath);
if (empty($this->publicKeyContent)) throw new \Exception('Public key is empty');
if (empty($this->privateKeyContent)) throw new \Exception('Private key is empty');
$this->publicKeyResourceID = !empty($this->publicKeyContent) ? openssl_pkey_get_public($this->getPublicKey()) : false;
$this->privateKeyresourceID = !empty($this->privateKeyContent) ? openssl_pkey_get_private($this->getPrivatekey()) : false;
if ($this->publicKeyResourceID === false) throw new \Exception('解析公鑰內(nèi)容失敗');
if ($this->privateKeyresourceID === false) throw new \Exception('解析私鑰內(nèi)容失敗');
}
/**
* 校驗文件路徑
* @param string $filePath
* @throws Exception
*/
public function checkFilePath(string $filePath)
{
if (!is_file($filePath)) throw new \Exception($filePath . ' is not a regular file');
if (!file_exists($filePath)) throw new \Exception($filePath . ' is not exists');
}
//獲取私有key字符串,重新格式化,為保證任何key都可以識別
public function getPrivatekey(): string
{
$search = [
"-----BEGIN RSA PRIVATE KEY-----",
"-----END RSA PRIVATE KEY-----",
"\n",
"\r",
"\r\n"
];
$privateKey = str_replace($search, "", $this->privateKeyContent);
//打斷字符串為指定數(shù)量的字串
return $search[0] . PHP_EOL . wordwrap($privateKey, 64, "\n", true) . PHP_EOL . $search[1];
}
/**
*
* 獲取公共key字符串,重新格式化,為保證任何key都可以識別
*/
public function getPublicKey()
{
$search = [
"-----BEGIN PUBLIC KEY-----",
"-----END PUBLIC KEY-----",
"\n",
"\r",
"\r\n"
];
$publicKey = str_replace($search, "", $this->publicKeyContent);
//打斷字符串為指定數(shù)量的字串
return $search[0] . PHP_EOL . wordwrap($publicKey, 64, "\n", true) . PHP_EOL . $search[1];
}
public function createKey()
{
$result = openssl_pkey_new();// 生成一個新的私鑰和公鑰對,
if ($result === false) return false;
openssl_pkey_export($result, $privateKey);//將key當(dāng)作PEM編碼字符串導(dǎo)出并且將之保存到$privateKey(通過引用傳遞的)中。
$publicKey = openssl_pkey_get_details($result);//返回包含密鑰詳情的數(shù)組
return array('public_key' => $publicKey["key"], 'private_key' => $this->getPrivatekey());
}
//使用私鑰加密
public function encryptByPrivateKey(string $data): string
{
openssl_private_encrypt($data, $output, $this->privateKeyresourceID);
return base64_encode($output);
}
//使用公鑰解密
public function decryptByPublicKey(string $data): string
{
openssl_public_decrypt(base64_decode($data), $output, $this->publicKeyResourceID);
return $output;
}
//使用公鑰加密
public function encryptByPublicKey(string $data): string
{
openssl_public_encrypt($data, $output, $this->publicKeyResourceID);
return base64_encode($output);
}
//使用私鑰解密
public function decryptByPrivateKey(string $data): string
{
openssl_private_decrypt(base64_decode($data), $output, $this->privateKeyresourceID);
return $output;
}
//生成簽名
public function generateSignature(string $data, int $signType = OPENSSL_ALGO_SHA1): string
{
openssl_sign($data, $outSignature, $this->privateKeyresourceID, $signType);//Generate signature
return base64_encode($outSignature);
}
//校驗簽名 OPENSSL_ALGO_SHA256為RSA2
public function checkSignature(string $originalData, string $signature, int $signType = OPENSSL_ALGO_SHA1): bool
{
//如果簽名正確返回 1, 簽名錯誤返回 0, 內(nèi)部發(fā)生錯誤則返回-1
$result = openssl_verify($originalData, base64_decode($signature), $this->publicKeyResourceID, $signType);
return $result == 1;
}
public function __destruct()
{
openssl_free_key($this->publicKeyResourceID);
openssl_free_key($this->privateKeyresourceID);
}
}
$rsaObj = new RSA('/home/zrj/.ssh/rsa_public.key', '/home/zrj/.ssh/rsa_private.key');
$str = 'Hello world';
echo '原始數(shù)據(jù):' . $str . PHP_EOL;
echo '公鑰加密私鑰解密如下:' . PHP_EOL;
$tmpstr = $rsaObj->encryptByPublicKey($str); //用公鑰加密
echo '加密后的數(shù)據(jù):' . PHP_EOL;
echo $tmpstr . PHP_EOL;
$tmpstr = $rsaObj->decryptByPrivateKey($tmpstr); //用私鑰解密
echo '解密結(jié)果:' . $tmpstr . PHP_EOL;
echo PHP_EOL;
echo PHP_EOL;
echo '私鑰加密公鑰解密如下:' . PHP_EOL;
$tmpstr = $rsaObj->encryptByPrivateKey($str); //用私鑰加密
echo '私鑰加密后的數(shù)據(jù):' . PHP_EOL;
echo $tmpstr . PHP_EOL;
$tmpstr = $rsaObj->decryptByPublicKey($tmpstr); //用公鑰解密
echo '公鑰解密結(jié)果:' . $tmpstr . PHP_EOL;
echo PHP_EOL;
echo PHP_EOL;
$signature = $rsaObj->generateSignature($tmpstr);
echo '簽名結(jié)果為:' . $signature . PHP_EOL;
var_dump($rsaObj->checkSignature($tmpstr, $signature));
當(dāng)前題目:opensslRSA非對稱加密、解密、簽名、驗簽
鏈接分享:http://jinyejixie.com/article18/gpgcdp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、網(wǎng)站策劃、服務(wù)器托管、品牌網(wǎng)站制作、品牌網(wǎng)站設(shè)計、用戶體驗
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)