RSA.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace extend;
  3. class RSA
  4. {
  5. /**
  6. * 生成秘钥
  7. */
  8. public static function getSecretKey(){
  9. $config = [
  10. 'digest_alg' => "sha512",
  11. 'private_key_bits' => 4096,
  12. 'private_key_type' => OPENSSL_KEYTYPE_RSA,
  13. ];
  14. $resources = openssl_pkey_new($config);
  15. openssl_pkey_export($resources, $private_key, null, $config);
  16. $public_key = openssl_pkey_get_details($resources);
  17. if (empty($private_key) || empty($public_key)) return error(-1, 'API_SECRET_KEY_CREATE_ERROR');
  18. $data = [
  19. 'public_key' => $public_key['key'],
  20. 'private_key' => $private_key
  21. ];
  22. return success(0, '', $data);
  23. }
  24. /**
  25. * 私钥解密
  26. * @param string $encrypted
  27. * @param string $private_key
  28. */
  29. public static function decrypt($encrypted, $private_key, $public_key){
  30. $private_check = openssl_pkey_get_private($private_key);
  31. if (!$private_check) return error(-1, 'PRIVATE_KEY_ERROR');
  32. $public_check = openssl_pkey_get_public($public_key);
  33. if (!$public_check) return error(-1, 'PUBLIC_KEY_ERROR');
  34. $details = openssl_pkey_get_details($public_check);
  35. $bits = $details['bits'];
  36. $decrypted = '';
  37. $base64_decoded = self::safe_base64_decode($encrypted);
  38. // 分段解密
  39. $parts = str_split($base64_decoded, ($bits / 8));
  40. foreach ($parts as $part) {
  41. $decrypted_temp = '';
  42. $decrypt_res = openssl_private_decrypt($part, $decrypted_temp, $private_key);
  43. if (!$decrypt_res) return error(-1, 'DECRYPT_FAIL');
  44. $decrypted .= $decrypted_temp;
  45. }
  46. return success(0, '', $decrypted);
  47. }
  48. /**
  49. * base64解码
  50. * @param unknown $string
  51. */
  52. private static function safe_base64_decode($string){
  53. $base_64 = str_replace(array( '-', '_' ), array( '+', '/' ), $string);
  54. return base64_decode($base_64);
  55. }
  56. }