AdaTools.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace AdaPay;
  3. class AdaTools
  4. {
  5. public $rsaPrivateKeyFilePath = "";
  6. public $rsaPublicKeyFilePath = "";
  7. public $rsaPrivateKey = "";
  8. public $rsaPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwN6xgd6Ad8v2hIIsQVnbt8a3JituR8o4Tc3B5WlcFR55bz4OMqrG/356Ur3cPbc2Fe8ArNd/0gZbC9q56Eb16JTkVNA/fye4SXznWxdyBPR7+guuJZHc/VW2fKH2lfZ2P3Tt0QkKZZoawYOGSMdIvO+WqK44updyax0ikK6JlNQIDAQAB";
  9. public function generateSignature($url, $params){
  10. if (is_array($params)){
  11. $Parameters = array();
  12. foreach ($params as $k => $v)
  13. {
  14. $Parameters[$k] = $v;
  15. }
  16. $data = $url . json_encode($Parameters);
  17. }else{
  18. $data = $url . $params;
  19. }
  20. $sign = $this->SHA1withRSA($data);
  21. return $sign;
  22. }
  23. public function SHA1withRSA($data){
  24. if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
  25. $priKey=$this->rsaPrivateKey;
  26. $key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($priKey, 64, "\n", true)."\n-----END PRIVATE KEY-----";
  27. }else {
  28. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  29. $key = openssl_get_privatekey($priKey);
  30. }
  31. try {
  32. openssl_sign($data, $signature, $key);
  33. } catch (\Exception $e) {
  34. echo $e->getMessage();
  35. }
  36. return base64_encode($signature);
  37. }
  38. public function verifySign($signature, $data){
  39. if($this->checkEmpty($this->rsaPublicKeyFilePath)){
  40. $pubKey=$this->rsaPublicKey;
  41. $key = "-----BEGIN PUBLIC KEY-----\n".wordwrap($pubKey, 64, "\n", true)."\n-----END PUBLIC KEY-----";
  42. }else {
  43. $pubKey = file_get_contents($this->rsaPublicKeyFilePath);
  44. $key = openssl_get_publickey($pubKey);
  45. }
  46. if (openssl_verify($data, base64_decode($signature), $key)){
  47. return true;
  48. }else{
  49. return false;
  50. }
  51. }
  52. public function checkEmpty($value) {
  53. if (!isset($value))
  54. return true;
  55. if ($value === null)
  56. return true;
  57. if (trim($value) === "")
  58. return true;
  59. return false;
  60. }
  61. public function get_array_value($data, $key){
  62. if (isset($data[$key])){
  63. return $data[$key];
  64. }
  65. return "";
  66. }
  67. function createLinkstring($params)
  68. {
  69. $arg = "";
  70. foreach ($params as $key=> $val){
  71. if($val){
  72. $arg .= $key . "=" . $val . "&";
  73. }
  74. }
  75. $arg = substr($arg,0, -1);
  76. return $arg;
  77. }
  78. }