RSA encryption instance implemented by php

Source: Internet
Author: User

RSA encryption instance implemented by php

This article describes how to implement RSA encryption in php. The example analyzes the php custom RSA encryption and decryption techniques, which are very useful. For more information, see

 

 

This example describes how to implement RSA encryption in php. Share it with you for your reference. The specific analysis is as follows:

Openssl-based signatures, signatures, and asymmetric encryption and decryption must be used with x.509 certificates (such as crt and pem) files.
For various reasons, this class is not perfect. You are welcome to test it!

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

<? Php

/**

* RSA Algorithm

* Signature and ciphertext encoding: base64 string/hexadecimal string/binary string stream

* Filling mode: PKCS1Padding (encryption and decryption)/NOPadding (decryption)

*

* Notice: Only accepts a single block. Block size is equal to the RSA key size!

* 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.

*

* @ Author: linvo

* @ Version: 1.0.0

* @ Date: 2013/1/23

*/

Class RSA {

Private $ pubKey = null;

Private $ priKey = null;

/**

* Custom error handling

*/

Private function _ error ($ msg ){

Die ('rsa Error: '. $ msg); // TODO

}

/**

* Constructor

*

* @ Param string public key file (passed during signature verification and encryption)

* @ Param string private key file (input during signature and decryption)

*/

Public function _ construct ($ public_key_file = '', $ private_key_file = ''){

If ($ public_key_file ){

$ This-> _ getPublicKey ($ public_key_file );

}

If ($ private_key_file ){

$ This-> _ getPrivateKey ($ private_key_file );

}

}

/**

* Generate a signature

*

* @ Param string signature Material

* @ Param string signature encoding (base64/hex/bin)

* @ Return signature Value

*/

Public function sign ($ data, $ code = 'base64 '){

$ Ret = false;

If (openssl_sign ($ data, $ ret, $ this-> priKey )){

$ Ret = $ this-> _ encode ($ ret, $ code );

}

Return $ ret;

}

/**

* Verify the signature

*

* @ Param string signature Material

* @ Param string signature Value

* @ Param string signature encoding (base64/hex/bin)

* @ Return bool

*/

Public function verify ($ data, $ sign, $ code = 'base64 '){

$ Ret = false;

$ Sign = $ this-> _ decode ($ sign, $ code );

If ($ sign! = False ){

Switch (openssl_verify ($ data, $ sign, $ this-> pubKey )){

Case 1: $ ret = true; break;

Case 0:

Case-1:

Default: $ ret = false;

}

}

Return $ ret;

}

/**

* Encryption

*

* @ Param string plaintext

* @ Param string ciphertext encoding (base64/hex/bin)

* @ Param int fill mode (it seems that php has a bug, so currently only OPENSSL_PKCS1_PADDING is supported)

* @ Return string ciphertext

*/

Public function encrypt ($ data, $ code = 'base64', $ padding = OPENSSL_PKCS1_PADDING ){

$ Ret = false;

If (! $ This-> _ checkPadding ($ padding, 'en') $ this-> _ error ('padding error ');

If (openssl_public_encrypt ($ data, $ result, $ this-> pubKey, $ padding )){

$ Ret = $ this-> _ encode ($ result, $ code );

}

Return $ ret;

}

/**

* Decryption

*

* @ Param string ciphertext

* @ Param string ciphertext encoding (base64/hex/bin)

* @ Param int fill mode (OPENSSL_PKCS1_PADDING/OPENSSL_NO_PADDING)

* @ Param bool whether to flip the plaintext (When passing Microsoft CryptoAPI-generated RSA cyphertext, revert the bytes in the block)

* @ Return string plaintext

*/

Public function decrypt ($ data, $ code = 'base64', $ padding = OPENSSL_PKCS1_PADDING, $ rev = false ){

$ Ret = false;

$ Data = $ this-> _ decode ($ data, $ code );

If (! $ This-> _ checkPadding ($ padding, 'de') $ this-> _ error ('padding error ');

If ($ data! = False ){

If (openssl_private_decrypt ($ data, $ result, $ this-> priKey, $ padding )){

$ Ret = $ rev? Rtrim (strrev ($ result), "\ 0"): ''. $ result;

}

}

Return $ ret;

}

// Private Method

/**

* Check Filling Type

* Encryption only supports PKCS1_PADDING.

* Supports PKCS1_PADDING and NO_PADDING for decryption.

*

* @ Param int fill Mode

* @ Param string encrypt en/decrypt de

* @ Return bool

*/

Private function _ checkPadding ($ padding, $ type ){

If ($ type = 'en '){

Switch ($ padding ){

Case OPENSSL_PKCS1_PADDING:

$ Ret = true;

Break;

Default:

$ Ret = false;

}

} Else {

Switch ($ padding ){

Case OPENSSL_PKCS1_PADDING:

Case OPENSSL_NO_PADDING:

$ Ret = true;

Break;

Default:

$ Ret = false;

}

}

Return $ ret;

}

Private function _ encode ($ data, $ code ){

Switch (strtolower ($ code )){

Case 'base64 ':

$ Data = base64_encode (''. $ data );

Break;

Case 'hex ':

$ Data = bin2hex ($ data );

Break;

Case 'bin ':

Default:

}

Return $ data;

}

Private function _ decode ($ data, $ code ){

Switch (strtolower ($ code )){

Case 'base64 ':

$ Data = base64_decode ($ data );

Break;

Case 'hex ':

$ Data = $ this-> _ hex2bin ($ data );

Break;

Case 'bin ':

Default:

}

Return $ data;

}

Private function _ getPublicKey ($ file ){

$ Key_content = $ this-> _ readFile ($ file );

If ($ key_content ){

$ This-> pubKey = openssl_get_publickey ($ key_content );

}

}

Private function _ getPrivateKey ($ file ){

$ Key_content = $ this-> _ readFile ($ file );

If ($ key_content ){

$ This-> priKey = openssl_get_privatekey ($ key_content );

}

}

Private function _ readFile ($ file ){

$ Ret = false;

If (! File_exists ($ file )){

$ This-> _ error ("The file {$ file} is not exists ");

} Else {

$ Ret = file_get_contents ($ file );

}

Return $ ret;

}

Private function _ hex2bin ($ hex = false ){

$ Ret = $ hex! = False & preg_match ('/^ [0-9a-fA-F] + $/I', $ hex )? Pack ("H *", $ hex): false;

Return $ ret;

}

}

Test demo:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<? Php

Header ('content-Type: text/html; Charset = UTF-8 ;');

Include "rsa. php ";

Echo '<pre> ';

$ A = isset ($ _ GET ['a'])? $ _ GET ['a']: 'test 100 ';

//////////////////////////////////////

$ Pubfile = 'e: \ ssl \ cert \ pwd. crt ';

$ Prifile = 'e: \ ssl \ cert \ pwd. pem ';

$ M = new RSA ($ pubfile, $ prifile );

$ X = $ m-> sign ($ );

$ Y = $ m-> verify ($ a, $ x );

Var_dump ($ x, $ y );

$ X = $ m-> encrypt ($ );

$ Y = $ m-> decrypt ($ x );

Var_dump ($ x, $ y );

I hope this article will help you with php programming.

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.