PhpRAS encryption code

Source: Internet
Author: User
PhpRAS encryption code
Openssl-based signatures, signatures, and asymmetric encryption and decryption must be used with x.509 certificates (such as crt and pem) files.

  1. /**
  2. * RSA algorithm
  3. * Signature and ciphertext encoding: base64 string/hexadecimal string/binary string stream
  4. * Filling mode: PKCS1Padding (encryption and decryption)/NOPadding (decryption)
  5. *
  6. * Notice: Only accepts a single block. Block size is equal to the RSA key size!
  7. * If the key length is 1024 bits, the encrypted data size must be less than 128 bytes, and the PKCS1Padding's own 11 bytes. Therefore, the plaintext length must be less than 117 bytes.
  8. *
  9. * @ Author: linvo
  10. * @ Version: 1.0.0
  11. * @ Date: 2013/1/23
  12. */
  13. Class RSA {
  14. Private $ pubKey = null;
  15. Private $ priKey = null;
  16. /**
  17. * Custom error handling
  18. */
  19. Private function _ error ($ msg ){
  20. Die ('RSA Error: '. $ msg); // TODO
  21. }
  22. /**
  23. * Constructor
  24. *
  25. * @ Param string Public Key File (passed during signature verification and encryption)
  26. * @ Param string private key File (input during signature and decryption)
  27. */
  28. Public function _ construct ($ public_key_file = '', $ private_key_file = ''){
  29. If ($ public_key_file ){
  30. $ This-> _ getPublicKey ($ public_key_file );
  31. }
  32. If ($ private_key_file ){
  33. $ This-> _ getPrivateKey ($ private_key_file );
  34. }
  35. }
  36. /**
  37. * Generate a signature
  38. *
  39. * @ Param string signature material
  40. * @ Param string signature encoding (base64/hex/bin)
  41. * @ Return signature value
  42. */
  43. Public function sign ($ data, $ code = 'base64 '){
  44. $ Ret = false;
  45. If (openssl_sign ($ data, $ ret, $ this-> priKey )){
  46. $ Ret = $ this-> _ encode ($ ret, $ code );
  47. }
  48. Return $ ret;
  49. }
  50. /**
  51. * Verify the signature
  52. *
  53. * @ Param string signature material
  54. * @ Param string signature value
  55. * @ Param string signature encoding (base64/hex/bin)
  56. * @ Return bool
  57. */
  58. Public function verify ($ data, $ sign, $ code = 'base64 '){
  59. $ Ret = false;
  60. $ Sign = $ this-> _ decode ($ sign, $ code );
  61. If ($ sign! = False ){
  62. Switch (openssl_verify ($ data, $ sign, $ this-> pubKey )){
  63. Case 1: $ ret = true; break;
  64. Case 0:
  65. Case-1:
  66. Default: $ ret = false;
  67. }
  68. }
  69. Return $ ret;
  70. }
  71. /**
  72. * Encryption
  73. *
  74. * @ Param string plaintext
  75. * @ Param string ciphertext encoding (base64/hex/bin)
  76. * @ Param int fill mode (it seems that php has a bug, so currently only OPENSSL_PKCS1_PADDING is supported)
  77. * @ Return string ciphertext
  78. */
  79. Public function encrypt ($ data, $ code = 'base64', $ padding = OPENSSL_PKCS1_PADDING ){
  80. $ Ret = false;
  81. If (! $ This-> _ checkPadding ($ padding, 'en') $ this-> _ error ('padding error ');
  82. If (openssl_public_encrypt ($ data, $ result, $ this-> pubKey, $ padding )){
  83. $ Ret = $ this-> _ encode ($ result, $ code );
  84. }
  85. Return $ ret;
  86. }
  87. /**
  88. * Decryption
  89. *
  90. * @ Param string ciphertext
  91. * @ Param string ciphertext encoding (base64/hex/bin)
  92. * @ Param int fill mode (OPENSSL_PKCS1_PADDING/OPENSSL_NO_PADDING)
  93. * @ Param bool whether to flip the plaintext (When passing Microsoft CryptoAPI-generated RSA cyphertext, revert the bytes in the block)
  94. * @ Return string plaintext
  95. */
  96. Public function decrypt ($ data, $ code = 'base64', $ padding = OPENSSL_PKCS1_PADDING, $ rev = false ){
  97. $ Ret = false;
  98. $ Data = $ this-> _ decode ($ data, $ code );
  99. If (! $ This-> _ checkPadding ($ padding, 'de') $ this-> _ error ('padding error ');
  100. If ($ data! = False ){
  101. If (openssl_private_decrypt ($ data, $ result, $ this-> priKey, $ padding )){
  102. $ Ret = $ rev? Rtrim (strrev ($ result), "\ 0"): ''. $ result;
  103. }
  104. }
  105. Return $ ret;
  106. }
  107. // Private method
  108. /**
  109. * Check filling type
  110. * Encryption only supports PKCS1_PADDING.
  111. * Supports PKCS1_PADDING and NO_PADDING for decryption.
  112. *
  113. * @ Param int fill mode
  114. * @ Param string encrypt en/decrypt de
  115. * @ Return bool
  116. */
  117. Private function _ checkPadding ($ padding, $ type ){
  118. If ($ type = 'en '){
  119. Switch ($ padding ){
  120. Case OPENSSL_PKCS1_PADDING:
  121. $ Ret = true;
  122. Break;
  123. Default:
  124. $ Ret = false;
  125. }
  126. } Else {
  127. Switch ($ padding ){
  128. Case OPENSSL_PKCS1_PADDING:
  129. Case OPENSSL_NO_PADDING:
  130. $ Ret = true;
  131. Break;
  132. Default:
  133. $ Ret = false;
  134. }
  135. }
  136. Return $ ret;
  137. }
  138. Private function _ encode ($ data, $ code ){
  139. Switch (strtolower ($ code )){
  140. Case 'base64 ':
  141. $ Data = base64_encode (''. $ data );
  142. Break;
  143. Case 'Hex ':
  144. $ Data = bin2hex ($ data );
  145. Break;
  146. Case 'bin ':
  147. Default:
  148. }
  149. Return $ data;
  150. }
  151. Private function _ decode ($ data, $ code ){
  152. Switch (strtolower ($ code )){
  153. Case 'base64 ':
  154. $ Data = base64_decode ($ data );
  155. Break;
  156. Case 'Hex ':
  157. $ Data = $ this-> _ hex2bin ($ data );
  158. Break;
  159. Case 'bin ':
  160. Default:
  161. }
  162. Return $ data;
  163. }
  164. Private function _ getPublicKey ($ file ){
  165. $ Key_content = $ this-> _ readFile ($ file );
  166. If ($ key_content ){
  167. $ This-> pubKey = openssl_get_publickey ($ key_content );
  168. }
  169. }
  170. Private function _ getPrivateKey ($ file ){
  171. $ Key_content = $ this-> _ readFile ($ file );
  172. If ($ key_content ){
  173. $ This-> priKey = openssl_get_privatekey ($ key_content );
  174. }
  175. }
  176. Private function _ readFile ($ file ){
  177. $ Ret = false;
  178. If (! File_exists ($ file )){
  179. $ This-> _ error ("The file {$ file} is not exists ");
  180. } Else {
  181. $ Ret = file_get_contents ($ file );
  182. }
  183. Return $ ret;
  184. }
  185. Private function _ hex2bin ($ hex = false ){
  186. $ Ret = $ hex! = False & preg_match ('/^ [0-9a-fA-F] + $/I', $ hex )? Pack ("H *", $ hex): false;
  187. Return $ ret;
  188. }
  189. }


Test example

  1. Header ('content-Type: text/html; Charset = utf-8 ;');
  2. Include "rsa. php ";
  3. Echo'
    ';
  4. $ A = isset ($ _ GET ['A'])? $ _ GET ['A']: 'Test 100 ';
  5. //////////////////////////////////////
  6. $ Pubfile = 'E: \ ssl \ cert \ pwd. crt ';
  7. $ Prifile = 'E: \ ssl \ cert \ pwd. pem ';
  8. $ M = new RSA ($ pubfile, $ prifile );
  9. $ X = $ m-> sign ($ );
  10. $ Y = $ m-> verify ($ a, $ x );
  11. Var_dump ($ x, $ y );
  12. $ X = $ m-> encrypt ($ );
  13. $ Y = $ m-> decrypt ($ x );
  14. Var_dump ($ x, $ y );


Php, RAS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.