1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- function rsaSign($pre_str, $_private_key_path = '') {
- $_private_key = file_get_contents($_private_key_path);
- $_private_key = str_replace("-----BEGIN RSA PRIVATE KEY-----", "", $_private_key);
- $_private_key = str_replace("-----END RSA PRIVATE KEY-----", "", $_private_key);
- $_private_key = str_replace("\n", "", $_private_key);
- $_private_key = "-----BEGIN RSA PRIVATE KEY-----".PHP_EOL.wordwrap($_private_key, 64, "\n", true).PHP_EOL
- ."-----END RSA PRIVATE KEY-----";
- $_pkey_id = openssl_get_privatekey($_private_key);
- if ($_pkey_id) {
- openssl_sign($pre_str, $sign, $_pkey_id);
- } else {
- return false;
- }
- openssl_free_key($_pkey_id);
- $sign = base64_encode($sign);
- return $sign;
- }
- function rsaVerify($pre_str, $sign, $public_key_path) {
- $_public_key = file_get_contents($public_key_path);
-
- $_public_key = str_replace("-----BEGIN PUBLIC KEY-----", "", $_public_key);
- $_public_key = str_replace("-----END PUBLIC KEY-----", "", $_public_key);
- $_public_key = str_replace("\n", "", $_public_key);
- $_public_key = '-----BEGIN PUBLIC KEY-----'.PHP_EOL.wordwrap($_public_key, 64, "\n", true).PHP_EOL
- .'-----END PUBLIC KEY-----';
- $_pkey_id = openssl_get_publickey($_public_key);
- $_verify = 0;
- if ($_pkey_id) {
- $_verify = openssl_verify($pre_str, base64_decode($sign), $_pkey_id);
- openssl_free_key($_pkey_id);
- }
- if (1 == $_verify) {
- return true;
- } else {
- return false;
- }
- }
- function rsaDecrypt($content, $private_key_path) {
- $_private_key_path = $private_key_path;
- $priKey = file_get_contents($_private_key_path);
- $_pkey_id = openssl_get_privatekey($priKey);
-
- $content = base64_decode($content);
-
- $_result = '';
- for ($i = 0; $i < strlen($content) / 128; $i++) {
- $data = substr($content, $i * 128, 128);
- openssl_private_decrypt($data, $decrypt, $_pkey_id);
- $_result .= $decrypt;
- }
- openssl_free_key($_pkey_id);
- return $_result;
- }
|