rsa_sha256.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. class RSA{
  19. public static function generatePubKey($publicKey) {
  20. $begin_public = "-----BEGIN PUBLIC KEY-----\n";
  21. $end_public = "-----END PUBLIC KEY-----\n";
  22. $pubKey = $begin_public.chunk_split($publicKey, 64, "\n").$end_public;
  23. return $pubKey;
  24. }
  25. public static function generatePriKey($privateKey){
  26. $begin_private = "-----BEGIN RSA PRIVATE KEY-----\n";
  27. $end_private = "-----END RSA PRIVATE KEY-----\n";
  28. $priKey = $begin_private.chunk_split($privateKey, 64, "\n").$end_private;
  29. return $priKey;
  30. }
  31. //sign
  32. public static function sign($content,$privateKey){
  33. $priKey = openssl_get_privatekey(RSA::generatePriKey($privateKey));
  34. openssl_sign($content, $sign, $priKey,OPENSSL_ALGO_SHA256);
  35. openssl_free_key($priKey);
  36. $sign = base64_encode($sign);
  37. return $sign;
  38. }
  39. //verify
  40. public static function doCheck($content, $sign, $publicKey){
  41. if($sign == null){
  42. return false;
  43. }
  44. if($publicKey == null){
  45. return false;
  46. }
  47. try{
  48. $pubKey = openssl_get_publickey(RSA::generatePubKey($publicKey));
  49. $result = openssl_verify($content,base64_decode($sign),$pubKey,OPENSSL_ALGO_SHA256);
  50. openssl_free_key($pubKey);
  51. return $result;
  52. }catch (Exception $e){
  53. $e->getMessage();
  54. return false;
  55. }
  56. }
  57. }