123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <?php
- namespace clue;
- class RSAUtil
- {
- public $privateKey;
- public $publicKey;
- /**
- * 构造方法
- * @access public
- */
- public function __construct($private_key,$public_key)
- {
- $this->privateKey = openssl_pkey_get_private($private_key);
- $this->publicKey = openssl_pkey_get_public($public_key);
- }
- public function __call($method, $args)
- {
- return json(['status' => '1', 'msg' => '方法不存在']);
- }
- public function privateEncrypt($data)
- {
- $crypto = '';
- foreach (str_split($data, 117) as $chunk) {
- openssl_private_encrypt($chunk, $encryptData, $this->privateKey);
- $crypto .= $encryptData;
- }
- //加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的
- $encrypted = $this->urlsafeB64encode($crypto);
- return $encrypted;
- }
- //加密码时把特殊符号替换成URL可以带的内容
- function urlsafeB64encode($string)
- {
- $data = base64_encode($string);
- $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
- return $data;
- }
- //解密码时把转换后的符号替换特殊符号
- function urlsafeB64decode($string)
- {
- $data = str_replace(array('-', '_'), array('+', '/'), $string);
- $mod4 = strlen($data) % 4;
- if ($mod4) {
- $data .= substr('====', $mod4);
- }
- return base64_decode($data);
- }
- //公钥加密
- public function publicEncrypt($data)
- {
- $crypto = '';
- foreach (str_split($data, 117) as $chunk) {
- openssl_public_encrypt($chunk, $encryptData, $this->publicKey);
- $crypto .= $encryptData;
- }
- $encrypted = $this->urlsafeB64encode($crypto);
- return $encrypted;
- }
- //私钥解密
- public function privateDecrypt($encrypted)
- {
- $crypto = '';
- foreach (str_split($this->urlsafeB64decode($encrypted), 128) as $chunk) {
- openssl_private_decrypt($chunk, $decryptData, $this->privateKey);
- $crypto .= $decryptData;
- }
- return $crypto;
- }
- }
|