PHP生成公私鑰,加密解密,簽名驗籤
阿新 • • 發佈:2020-11-03
1 /** 2 * 生成公私鑰 3 */ 4 $config = array( 5 "digest_alg" => "sha512",//加密模式 sha256 sha512 md5 6 "private_key_bits" => 2048,//指定應該使用多少位來生成私鑰 512 1024 2048 4096等 7 "private_key_type" => OPENSSL_KEYTYPE_RSA,////選擇在建立CSR時應該使用哪些擴充套件。可選值有 OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_RSA 或 OPENSSL_KEYTYPE_EC. 預設值是 OPENSSL_KEYTYPE_RSA.8 ); 9 //建立金鑰對 10 $res = openssl_pkey_new($config); 11 //生成私鑰 12 openssl_pkey_export($res, $privKey); 13 //生成公鑰 14 $pubKey = openssl_pkey_get_details($res); 15 $pubKey = $pubKey["key"]; 16 17 // print_r($privKey); 18 // print_r($pubKey); 19 //輸出公私鑰檔案 20 // file_put_contents('private.key',$privKey); 21 // file_put_contents('public.key',$pubKey);22 23 24 25 /** 26 * 公鑰加密私鑰解密 27 */ 28 $data = '公鑰加密內容'; 29 //公鑰加密 30 openssl_public_encrypt($data, $encrypted, $pubKey); 31 //私鑰解密 32 openssl_private_decrypt($encrypted, $decrypted, $privKey); 33 // echo $decrypted; 34 35 36 37 /** 38 * 私鑰簽名公鑰驗籤 39 */ 40 $priStr = '私鑰簽名內容'; 41 //私鑰簽名 42 $signature = "";43 openssl_sign($priStr, $signature, $privKey, OPENSSL_ALGO_SHA256); 44 $signature = base64_encode($signature); 45 // var_dump($signature); 46 //公鑰驗籤 47 /**如果簽名正確返回 1, 簽名錯誤返回 0, 內部發生錯誤則返回-1. */ 48 $result = (bool)openssl_verify($priStr, base64_decode($signature), $pubKey,OPENSSL_ALGO_SHA256); 49 var_dump($result); 50 // var_dump($signature); 51 52 53 54 /** 55 * 封裝簽名function 56 */ 57 /**私鑰簽名 */ 58 function getRSA2Sign($paramsArr,$privateKey) { 59 uksort($paramsArr, "strcmp"); 60 $Arr = []; 61 foreach ($paramsArr as $key => $value) { 62 $Arr[] = $key . "=" . rawurlencode($value); 63 } 64 $str = implode("&", $Arr); 65 $signature = ""; 66 openssl_sign($str, $signature, $privateKey, OPENSSL_ALGO_SHA256); 67 return base64_encode($signature); 68 } 69 70 /**公鑰驗籤 */ 71 function checkRSA2($checkArr,$sign,$publicKey){ 72 ksort($checkArr); 73 $Arr = []; 74 foreach ($checkArr as $key => $value) { 75 $Arr[] = $key . '=' . rawurlencode($value); 76 } 77 $str = implode('&', $Arr); 78 $rsaPubKeyStr = chunk_split($publicKey, 64, "\n"); 79 $pubKey = openssl_pkey_get_public($rsaPubKeyStr); 80 $result = (bool)openssl_verify($str, base64_decode($sign), $pubKey,OPENSSL_ALGO_SHA256); 81 openssl_free_key($pubKey); 82 /**如果簽名正確返回 1, 簽名錯誤返回 0, 內部發生錯誤則返回-1. */ 83 return $result; 84 }