EncryptUtil.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: BF100311
  5. * Date: 2018/7/29
  6. * Time: 17:59
  7. */
  8. class EncryptUtil
  9. {
  10. private $private_key;
  11. private $public_key;
  12. function __construct($private_key_path, $public_key_path, $private_key_password, $Debug = FALSE)
  13. {
  14. if (!$Debug) {
  15. ob_start();
  16. }
  17. // 初始化商户私钥
  18. $pkcs12 = file_get_contents($private_key_path);
  19. $private_key = array();
  20. openssl_pkcs12_read($pkcs12, $private_key, $private_key_password);
  21. //echo "私钥是否可用:", empty($private_key) == true ? '不可用':'可用', "\n";
  22. $this->private_key = $private_key["pkey"];
  23. /**
  24. * $keyFile = file_get_contents($public_key_path);
  25. * $this->public_key = openssl_get_publickey($keyFile);
  26. * LOG::LogWirte(empty($this->public_key) == true ? "公钥是否可用:不可用" : "公钥是否可用:可用");
  27. */
  28. if (!$Debug) {
  29. ob_end_clean();
  30. }
  31. }
  32. // 私钥加密
  33. function encryptedByPrivateKey($data_content)
  34. {
  35. $data_content = base64_encode($data_content);
  36. $encrypted = "";
  37. $totalLen = strlen($data_content);
  38. $encryptPos = 0;
  39. while ($encryptPos < $totalLen) {
  40. openssl_private_encrypt(substr($data_content, $encryptPos, 117), $encryptData, $this->private_key);
  41. $encrypted .= bin2hex($encryptData);
  42. $encryptPos += 117;
  43. }
  44. return $encrypted;
  45. }
  46. // 公钥解密
  47. function decryptByPublicKey($encrypted)
  48. {
  49. if (!function_exists('hex2bin')) {
  50. throw new Exception("请启用hex2bin方法");
  51. }
  52. $decrypt = "";
  53. $totalLen = strlen($encrypted);
  54. $decryptPos = 0;
  55. while ($decryptPos < $totalLen) {
  56. openssl_public_decrypt(hex2bin(substr($encrypted, $decryptPos, 256)), $decryptData, $this->public_key);
  57. $decrypt .= $decryptData;
  58. $decryptPos += 256;
  59. }
  60. $decrypt = base64_decode($decrypt);
  61. return $decrypt;
  62. }
  63. /**
  64. * function hex2bin( $str ) {
  65. * $sbin = "";
  66. * $len = strlen( $str );
  67. * for ( $i = 0; $i < $len; $i += 2 ) {
  68. * $sbin .= pack( "H*", substr( $str, $i, 2 ) );
  69. * }
  70. * return $sbin;
  71. * } */
  72. }

开始调用

  1. // **** 先BASE64进行编码再RSA加密 *** $pfx_pwd私钥路径 $pfx_pwd私钥密码
  2. $encryptUtil = new EncryptUtil($pfxpath, "", $pfx_pwd, TRUE); //实例化加密类。
  3. $data_content = $encryptUtil->encryptedByPrivateKey($data_content);
  4. echo $data_content;
文档更新时间: 2019-06-17 15:47   作者:support