RSACryptUtil.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace LdzfPay\Api\Common;
  3. use LdzfPay\Api\Common\Logger;
  4. use LdzfPay\UmfPayService\UmfService;
  5. use think\Config;
  6. /**
  7. * RSA加解密工具类
  8. */
  9. class RSACryptUtil {
  10. /**
  11. * 使用公钥对明文字符串进行加密
  12. * @param $data string 明文
  13. * @return string string 密文
  14. */
  15. public static function encrypt($data) {
  16. // $log = new Logger ();
  17. //$cert_file = UmfService::$publicKeyPath;
  18. //$log->logInfo("[UMF SDK]公钥文件绝对路径 ".$cert_file);
  19. //if(!file_exists($cert_file)){
  20. // $log->logInfo("[UMF SDK]传入的公钥文件不存在,公钥文件绝对路径 ".$cert_file);
  21. // die("[UMF SDK]传入的公钥文件不存在,公钥文件绝对路径 ".$cert_file);
  22. //}
  23. $cert_file = Config::get('ldys_pay')['public_file'];
  24. $fp = fopen($cert_file,"r");
  25. $public_key = fread($fp,8192);
  26. // $public_key = UMF_PUBLIC_KEY;
  27. fclose($fp);
  28. $public_key = openssl_get_publickey($public_key);
  29. openssl_public_encrypt($data,$crypttext,$public_key);
  30. $encryptDate = base64_encode($crypttext);
  31. //$log->logInfo ( "[UMF SDK]敏感信息加密前明文: " . $data);
  32. // $log->logInfo ( "[UMF SDK]敏感信息加密后密文: " . $encryptDate);
  33. return $encryptDate;
  34. }
  35. /**
  36. * @param $data string 密文
  37. * @param $merId string 商户号
  38. * @return string string 明文
  39. */
  40. public function decrypt($data,$merId) {
  41. // $log = new Logger ();
  42. $priv_key_file = UmfService::$privateKeyPath[$merId];
  43. // $log->logInfo("[UMF SDK]私钥文件绝对路径 ".$priv_key_file);
  44. if(!file_exists($priv_key_file)){
  45. // $log->logInfo("[UMF SDK]传入的私钥文件不存在,私钥文件绝对路径 ".$priv_key_file);
  46. die("[UMF SDK]传入的私钥文件不存在,私钥文件绝对路径 ".$priv_key_file);
  47. }
  48. $fp = fopen($priv_key_file,"r");
  49. $private_key = fread($fp,8192);
  50. fclose ($fp);
  51. $private_key = openssl_get_privatekey($private_key);
  52. openssl_private_decrypt(base64_decode($data), $decrypted, $private_key);
  53. $decryptDate = iconv("GBK", "UTF-8", $decrypted);
  54. // $log->logInfo ( "[UMF SDK]敏感信息解密前密文: " . $data);
  55. //$log->logInfo ( "[UMF SDK]敏感信息解密后明文: " . $decryptDate);
  56. return $decryptDate;
  57. }
  58. }