KeyWorker.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Cn\Ubingo\Security\RSA\Data;
  3. include "KeyFormat.php";
  4. use Cn\Ubingo\Security\RSA\Core as core;
  5. /*
  6. 陈服建(fochen,j@ubingo.cn)
  7. 2015-01-23
  8. */
  9. class KeyWorker{
  10. private $key;
  11. private $isPrivate;
  12. private $keyFormat;
  13. private $keyProvider;
  14. function __construct($key,$keyFormat=core\KeyFormat::PEM){
  15. $this->KeyWorker($key,$keyFormat);
  16. }
  17. function KeyWorker($key,$keyFormat=core\KeyFormat::PEM)
  18. {
  19. $this->key = $key;
  20. $this->keyFormat = $keyFormat;
  21. }
  22. function encrypt($data){
  23. $this->_makesure_provider();
  24. $encrypted = '';
  25. if($this->isPrivate){
  26. foreach (str_split($data, 117) as $chunk) {
  27. $r= openssl_private_encrypt($chunk, $encryptData, $this->keyProvider,OPENSSL_PKCS1_PADDING);
  28. $encrypted .= $encryptData;
  29. }
  30. //$r= openssl_private_encrypt($data,$encrypted,$this->keyProvider,OPENSSL_PKCS1_PADDING);
  31. }
  32. else{
  33. foreach (str_split($data, 117) as $chunk) {
  34. $r= openssl_public_encrypt($chunk, $encryptData, $this->keyProvider,OPENSSL_PKCS1_PADDING);
  35. $encrypted .= $encryptData;
  36. }
  37. //$r= openssl_public_encrypt($data,$encrypted,$this->keyProvider,OPENSSL_PKCS1_PADDING);
  38. }
  39. return $r?$data = base64_encode($encrypted):null;
  40. }
  41. function decrypt($data){
  42. $this->_makesure_provider();
  43. $data = base64_decode($data);
  44. $crypto = '';
  45. foreach (str_split($data, 128) as $chunk) {
  46. if($this->isPrivate){
  47. $r= openssl_private_decrypt($chunk,$decrypted,$this->keyProvider,OPENSSL_PKCS1_PADDING);
  48. }
  49. else{
  50. $r= openssl_public_decrypt($chunk,$decrypted,$this->keyProvider,OPENSSL_PKCS1_PADDING);
  51. }
  52. $crypto .= $decrypted;
  53. }
  54. return $crypto;
  55. }
  56. function _makesure_provider(){
  57. if($this->keyProvider==null){
  58. $this->isPrivate = strlen($this->key)>500;
  59. switch($this->keyFormat){
  60. case core\KeyFormat::ASN:{
  61. $this->key = chunk_split($this->key,64,"\r\n");//转换为pem格式的公钥
  62. if($this->isPrivate){
  63. $this->key = "-----BEGIN PRIVATE KEY-----\r\n".$this->key."-----END PRIVATE KEY-----";
  64. }
  65. else{
  66. $this->key = "-----BEGIN PUBLIC KEY-----\r\n".$this->key."-----END PUBLIC KEY-----";
  67. }
  68. break;
  69. }
  70. }
  71. $this->keyProvider = $this->isPrivate?openssl_pkey_get_private($this->key):openssl_pkey_get_public($this->key);
  72. }
  73. }
  74. }
  75. ?>