0%

RSA加密(一)

近期公司支付接口总是被人公司修改数据,原来的MD5加密已经不能满足与当前的安全要求,于是我们采用了一种更为安全的加密方式RSA+AES加密。在开发过程中由于双方之前都没有直接参入这种加密方式开发,所以我们分别采用RSA和AES接口测试。闲话不多说,开始步入流程:

第一步:生成私钥公钥证书

1、生成私钥

1
openssl genrsa -out rsa_private_key.pem 1024 

2、生成公钥

1
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

3、 由于Java服务器和我们加密解密方式不一样(我们使用PCKS#1,他们使用PCKS#8)为了配合他们我们一般需要导出一个PCKS#8格式的密钥证书(注:证书导出不可逆且公钥无法导出PCKS#8证书,IOS和JAVA服务器可以通用PCKS#1公钥证书)

1
openssl pkcs8 -topk8 -inform PEM -in private_rsa.pem -outform PEM -nocrypt -out private_key.pem

第二步:导入openssl库

pod入openssl库,没有安装cocopods的自行百度安装方法

第三步:编写加密解密方法

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
#import <Foundation/Foundation.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/md5.h>

/**
@abstract padding type
*/
typedef NS_ENUM(NSInteger, RSA_PADDING_TYPE) {

RSA_PADDING_TYPE_NONE = RSA_NO_PADDING,
RSA_PADDING_TYPE_PKCS1 = RSA_PKCS1_PADDING,
RSA_PADDING_TYPE_SSLV23 = RSA_SSLV23_PADDING
};

@interface BBRSACryptor : NSObject
{
RSA *_rsaPublic;
RSA *_rsaPrivate;

@public
RSA *_rsa;
}
- (NSString *)signString:(NSString *)string;
- (BOOL)verifyMD5String:(NSString *)string withSign:(NSString *)signString;
- (NSString *)signMD5String:(NSString *)string;
- (BOOL)verifyString:(NSString *)string withSign:(NSString *)signString;
/**
Generate rsa key pair by the key size.
@param keySize RSA key bits . The value could be `512`,`1024`,`2048` and so on.
Normal is `1024`.
*/
- (BOOL)generateRSAKeyPairWithKeySize:(int)keySize;

/**
@abstract import public key, call before 'encryptWithPublicKey'
@param publicKey with base64 encoded
@return Success or not.
*/
- (BOOL)importRSAPublicKeyBase64:(NSString *)publicKey;

/**
@abstract import private key, call before 'decryptWithPrivateKey'
@param privateKey with base64 encoded
@return Success or not.
*/
- (BOOL)importRSAPrivateKeyBase64:(NSString *)privateKey;

/**
@abstract export public key, 'generateRSAKeyPairWithKeySize' or 'importRSAPublicKeyBase64' should call before this method
@return public key base64 encoded
*/
- (NSString *)base64EncodedPublicKey;

/**
@abstract export public key, 'generateRSAKeyPairWithKeySize' or 'importRSAPrivateKeyBase64' should call before this method
@return private key base64 encoded
*/
- (NSString *)base64EncodedPrivateKey;

/**
@abstract encrypt text using RSA public key
@param padding type add the plain text
@return encrypted data
*/
- (NSData *)encryptWithPublicKeyUsingPadding:(RSA_PADDING_TYPE)padding
plainData:(NSData *)plainData;

/**
@abstract encrypt text using RSA private key
@param padding type add the plain text
@return encrypted data
*/
- (NSData *)encryptWithPrivateKeyUsingPadding:(RSA_PADDING_TYPE)padding
plainData:(NSData *)plainData;

/**
@abstract decrypt text using RSA private key
@param padding type add the plain text
@return encrypted data
*/
- (NSData *)decryptWithPrivateKeyUsingPadding:(RSA_PADDING_TYPE)padding
cipherData:(NSData *)cipherData;

/**
@abstract decrypt text using RSA public key
@param padding type add the plain text
@return encrypted data
*/
- (NSData *)decryptWithPublicKeyUsingPadding:(RSA_PADDING_TYPE)padding
cipherData:(NSData *)cipherData;
@end
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#import "BBRSACryptor.h"

#define DocumentsDir [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
#define OpenSSLRSAKeyDir [DocumentsDir stringByAppendingPathComponent:@".openssl_rsa"]
#define OpenSSLRSAPublicKeyFile [OpenSSLRSAKeyDir stringByAppendingPathComponent:@"bb.publicKey.pem"]
#define OpenSSLRSAPrivateKeyFile [OpenSSLRSAKeyDir stringByAppendingPathComponent:@"bb.privateKey.pem"]

@implementation BBRSACryptor

- (instancetype)init
{
self = [super init];
if (self) {

// mkdir for key dir
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:OpenSSLRSAKeyDir])
{
[fm createDirectoryAtPath:OpenSSLRSAKeyDir withIntermediateDirectories:YES attributes:nil error:nil];
}
}
return self;
}
/**
* <#Description#>
*
* @param keySize <#keySize description#>
*
* @return <#return value description#>
*/
- (BOOL)generateRSAKeyPairWithKeySize:(int)keySize
{
if (NULL != _rsa)
{
RSA_free(_rsa);
_rsa = NULL;
}
_rsa = RSA_generate_key(keySize,RSA_F4,NULL,NULL);
assert(_rsa != NULL);

const char *publicKeyFileName = [OpenSSLRSAPublicKeyFile cStringUsingEncoding:NSASCIIStringEncoding];
const char *privateKeyFileName = [OpenSSLRSAPrivateKeyFile cStringUsingEncoding:NSASCIIStringEncoding];

//写入私钥和公钥
RSA_blinding_on(_rsa, NULL);

BIO *priBio = BIO_new_file(privateKeyFileName, "w");
PEM_write_bio_RSAPrivateKey(priBio, _rsa, NULL, NULL, 0, NULL, NULL);

BIO *pubBio = BIO_new_file(publicKeyFileName, "w");


PEM_write_bio_RSA_PUBKEY(pubBio, _rsa);
// PEM_write_bio_RSAPublicKey(pubBio, _rsa);

BIO_free(priBio);
BIO_free(pubBio);

//分别获取公钥和私钥
_rsaPrivate = RSAPrivateKey_dup(_rsa);
assert(_rsaPrivate != NULL);

_rsaPublic = RSAPublicKey_dup(_rsa);
assert(_rsaPublic != NULL);

NSLog(@"公钥路径:\n %@",OpenSSLRSAPublicKeyFile);
NSLog(@"私钥路径:\n %@",OpenSSLRSAPrivateKeyFile);

if (_rsa && _rsaPublic && _rsaPrivate)
{
return YES;
}
else
{
return NO;
}
}
/**
* <#Description#>
*
* @param publicKey <#publicKey description#>
*
* @return <#return value description#>
*/
- (BOOL)importRSAPublicKeyBase64:(NSString *)publicKey
{
//格式化公钥
NSMutableString *result = [NSMutableString string];
[result appendString:@"-----BEGIN PUBLIC KEY-----\n"];
int count = 0;
for (int i = 0; i < [publicKey length]; ++i) {

unichar c = [publicKey characterAtIndex:i];
if (c == '\n' || c == '\r') {
continue;
}
[result appendFormat:@"%c", c];
if (++count == 64) {
[result appendString:@"\n"];
count = 0;
}
}
[result appendString:@"\n-----END PUBLIC KEY-----"];
[result writeToFile:OpenSSLRSAPublicKeyFile
atomically:YES
encoding:NSASCIIStringEncoding
error:NULL];

FILE *publicKeyFile;
// NSLog(@"%@",result);
const char *publicKeyFileName = [OpenSSLRSAPublicKeyFile cStringUsingEncoding:NSASCIIStringEncoding];
publicKeyFile = fopen(publicKeyFileName,"rb");
if (NULL != publicKeyFile)
{
BIO *bpubkey = NULL;
bpubkey = BIO_new(BIO_s_file());
BIO_read_filename(bpubkey, publicKeyFileName);

_rsaPublic = PEM_read_bio_RSA_PUBKEY(bpubkey, NULL, NULL, NULL);
assert(_rsaPublic != NULL);
BIO_free_all(bpubkey);
}

return YES;
}
/**
* <#Description#>
*
* @param privateKey <#privateKey description#>
*
* @return <#return value description#>
*/
- (BOOL)importRSAPrivateKeyBase64:(NSString *)privateKey
{
//格式化私钥
const char *pstr = [privateKey UTF8String];
int len = (int)[privateKey length];
// NSLog(@"%d",len);
NSMutableString *result = [NSMutableString string];
[result appendString:@"-----BEGIN RSA PRIVATE KEY-----\n"];
int index = 0;
int count = 0;
while (index < len) {
char ch = pstr[index];
if (ch == '\r' || ch == '\n') {
++index;
continue;
}
[result appendFormat:@"%c", ch];
if (++count == 64)
{
[result appendString:@"\n"];
count = 0;
}
index++;
}
[result appendString:@"\n-----END RSA PRIVATE KEY-----"];

[result writeToFile:OpenSSLRSAPrivateKeyFile
atomically:YES
encoding:NSASCIIStringEncoding
error:NULL];
// NSLog(@"%@",result);
FILE *privateKeyFile;
const char *privateKeyFileName = [OpenSSLRSAPrivateKeyFile cStringUsingEncoding:NSASCIIStringEncoding];
privateKeyFile = fopen(privateKeyFileName,"rb");
if (NULL != privateKeyFile)
{
BIO *bpubkey = NULL;
bpubkey = BIO_new(BIO_s_file());

BIO_read_filename(bpubkey, privateKeyFileName);
// _rsaPrivate = PEM_read_bio_PrivateKey(bpubkey, NULL, NULL, NULL);
_rsaPrivate = PEM_read_bio_RSAPrivateKey(bpubkey, NULL, NULL, NULL);
assert(_rsaPrivate != NULL);
BIO_free_all(bpubkey);
}

return YES;
}
/**
* <#Description#>
*
* @return <#return value description#>
*/
- (NSString *)base64EncodedPublicKey
{
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:OpenSSLRSAPublicKeyFile])
{
//NSLog(@"%@",OpenSSLRSAPublicKeyFile);
NSString *str = [NSString stringWithContentsOfFile:OpenSSLRSAPublicKeyFile encoding:NSUTF8StringEncoding error:nil];
NSString *string = [[str componentsSeparatedByString:@"-----"] objectAtIndex:2];
string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
//NSLog(@"%@",string);
return string;
}
return nil;
}
/**
* <#Description#>
*
* @return <#return value description#>
*/
- (NSString *)base64EncodedPrivateKey
{
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:OpenSSLRSAPrivateKeyFile])
{
NSString *str = [NSString stringWithContentsOfFile:OpenSSLRSAPrivateKeyFile encoding:NSUTF8StringEncoding error:nil];
NSString *string = [[str componentsSeparatedByString:@"-----"] objectAtIndex:2];
string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
return string;
}
return nil;
}
/**
* <#Description#>
*
* @param padding <#padding description#>
* @param plainData <#plainData description#>
*
* @return <#return value description#>
*/
- (NSData *)encryptWithPublicKeyUsingPadding:(RSA_PADDING_TYPE)padding plainData:(NSData *)plainData
{
NSAssert(_rsaPublic != NULL, @"You should import public key first");

if ([plainData length])
{
int len = (int)[plainData length];
unsigned char *plainBuffer = (unsigned char *)[plainData bytes];

//result len
int clen = RSA_size(_rsaPublic);
unsigned char *cipherBuffer = calloc(clen, sizeof(unsigned char));

RSA_public_encrypt(len,plainBuffer,cipherBuffer, _rsaPublic, padding);

NSData *cipherData = [[NSData alloc] initWithBytes:cipherBuffer length:clen];

free(cipherBuffer);

return cipherData;
}

return nil;
}
/**
* <#Description#>
*
* @param padding <#padding description#>
* @param plainData <#plainData description#>
*
* @return <#return value description#>
*/
- (NSData *)encryptWithPrivateKeyUsingPadding:(RSA_PADDING_TYPE)padding plainData:(NSData *)plainData
{
NSAssert(_rsaPrivate != NULL, @"You should import private key first");

if ([plainData length])
{
int len = (int)[plainData length];
unsigned char *plainBuffer = (unsigned char *)[plainData bytes];

//result len
int clen = RSA_size(_rsaPrivate);
unsigned char *cipherBuffer = calloc(clen, sizeof(unsigned char));

RSA_private_encrypt(len,plainBuffer,cipherBuffer, _rsaPrivate, padding);

NSData *cipherData = [[NSData alloc] initWithBytes:cipherBuffer length:clen];

free(cipherBuffer);

return cipherData;
}

return nil;
}
/**
* <#Description#>
*
* @param padding <#padding description#>
* @param cipherData <#cipherData description#>
*
* @return <#return value description#>
*/
- (NSData *)decryptWithPrivateKeyUsingPadding:(RSA_PADDING_TYPE)padding cipherData:(NSData *)cipherData
{
NSAssert(_rsaPrivate != NULL, @"You should import private key first");

if ([cipherData length])
{
int len = (int)[cipherData length];
unsigned char *cipherBuffer = (unsigned char *)[cipherData bytes];

//result len
int mlen = RSA_size(_rsaPrivate);
unsigned char *plainBuffer = calloc(mlen, sizeof(unsigned char));

RSA_private_decrypt(len, cipherBuffer, plainBuffer, _rsaPrivate, padding);

NSData *plainData = [[NSData alloc] initWithBytes:plainBuffer length:mlen];

free(plainBuffer);

return plainData;
}

return nil;
}
/**
* <#Description#>
*
* @param padding <#padding description#>
* @param cipherData <#cipherData description#>
*
* @return <#return value description#>
*/
- (NSData *)decryptWithPublicKeyUsingPadding:(RSA_PADDING_TYPE)padding cipherData:(NSData *)cipherData
{
NSAssert(_rsaPublic != NULL, @"You should import public key first");

if ([cipherData length])
{
int len = (int)[cipherData length];
unsigned char *cipherBuffer = (unsigned char *)[cipherData bytes];

//result len
int mlen = RSA_size(_rsaPublic);
unsigned char *plainBuffer = calloc(mlen, sizeof(unsigned char));

RSA_public_decrypt(len, cipherBuffer, plainBuffer, _rsaPublic, padding);

NSData *plainData = [[NSData alloc] initWithBytes:plainBuffer length:mlen];

free(plainBuffer);

return plainData;
}

return nil;
}
#pragma mark RSA sha1验证签名
//signString为base64字符串
- (BOOL)verifyString:(NSString *)string withSign:(NSString *)signString
{
if (!_rsaPublic) {
NSLog(@"please import public key first");
return NO;
}

const char *message = [string cStringUsingEncoding:NSUTF8StringEncoding];
int messageLength = (int)[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSData *signatureData = [[NSData alloc]initWithBase64EncodedString:signString options:0];
unsigned char *sig = (unsigned char *)[signatureData bytes];
unsigned int sig_len = (int)[signatureData length];




unsigned char sha1[20];
SHA1((unsigned char *)message, messageLength, sha1);
int verify_ok = RSA_verify(NID_sha1
, sha1, 20
, sig, sig_len
, _rsaPublic);

if (1 == verify_ok){
return YES;
}
return NO;


}
#pragma mark RSA MD5 验证签名
- (BOOL)verifyMD5String:(NSString *)string withSign:(NSString *)signString
{
if (!_rsaPublic) {
NSLog(@"please import public key first");
return NO;
}

const char *message = [string cStringUsingEncoding:NSUTF8StringEncoding];
// int messageLength = (int)[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSData *signatureData = [[NSData alloc]initWithBase64EncodedString:signString options:0];
unsigned char *sig = (unsigned char *)[signatureData bytes];
unsigned int sig_len = (int)[signatureData length];

unsigned char digest[MD5_DIGEST_LENGTH];
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, message, strlen(message));
MD5_Final(digest, &ctx);
int verify_ok = RSA_verify(NID_md5
, digest, MD5_DIGEST_LENGTH
, sig, sig_len
, _rsaPublic);
if (1 == verify_ok){
return YES;
}
return NO;

}

- (NSString *)signString:(NSString *)string
{
if (!_rsaPrivate) {
NSLog(@"please import private key first");
return nil;
}
const char *message = [string cStringUsingEncoding:NSUTF8StringEncoding];
int messageLength = (int)strlen(message);
unsigned char *sig = (unsigned char *)malloc(256);
unsigned int sig_len;

unsigned char sha1[20];
SHA1((unsigned char *)message, messageLength, sha1);

int rsa_sign_valid = RSA_sign(NID_sha1
, sha1, 20
, sig, &sig_len
, _rsaPrivate);
if (rsa_sign_valid == 1) {
NSData* data = [NSData dataWithBytes:sig length:sig_len];

NSString * base64String = [data base64EncodedStringWithOptions:0];
free(sig);
return base64String;
}

free(sig);
return nil;
}
/**
* <#Description#>
*
* @param string <#string description#>
*
* @return <#return value description#>
*/
- (NSString *)signMD5String:(NSString *)string
{
if (!_rsaPrivate) {
NSLog(@"please import private key first");
return nil;
}
const char *message = [string cStringUsingEncoding:NSUTF8StringEncoding];
//int messageLength = (int)strlen(message);
unsigned char *sig = (unsigned char *)malloc(256);
unsigned int sig_len;

unsigned char digest[MD5_DIGEST_LENGTH];
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, message, strlen(message));
MD5_Final(digest, &ctx);

int rsa_sign_valid = RSA_sign(NID_md5
, digest, MD5_DIGEST_LENGTH
, sig, &sig_len
, _rsaPrivate);

if (rsa_sign_valid == 1) {
NSData* data = [NSData dataWithBytes:sig length:sig_len];

NSString * base64String = [data base64EncodedStringWithOptions:0];
free(sig);
return base64String;
}

free(sig);
return nil;


}

@end


加密签名文件和解密验签文件

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
#import "BBRSACryptor.h"
#import "GTMBase64.h"

@interface BBRSACryptor (XHCategory)

/**
* 生成公钥,私钥 (生成成功后控制台会打印出 公钥,私钥 存储路径)
*/
+(void)createPublicKeyAndPrivateKey;

/**
* 公钥加密
*
* @param string 普通字符串
* @param publicKey 公钥
*
* @return 加密后字符串
*/
+(NSString *)encryptString:(NSString *)string publicKey:(NSString *)publicKey;

/**
* 公钥解密
*
* @param string 私钥加密字符串
* @param publicKey 公钥
*
* @return 解密后字符串
*/
+(NSString *)decodingString:(NSString *)string publicKey:(NSString *)publicKey;

/**
* 私钥加密
*
* @param string 普通字符串
* @param privateKey 私钥
*
* @return 加密后字符串
*/
+(NSString *)encryptString:(NSString *)string privateKey:(NSString *)privateKey;

/**
* 私钥解密
*
* @param string 公钥加密字符串
* @param privateKey 私钥
*
* @return 解密后字符串
*/
+(NSString *)decodingString:(NSString *)string privateKey:(NSString *)privateKey;

/**
* 私钥签名
*
* @param string 普通字符串
* @param privateKey 私钥
*
* @return 签名后字符串
*/
+(NSString *)singString:(NSString *)string privateKey:(NSString *)privateKey;

/**
* 私钥签名MD5
*
* @param string 普通字符串
* @param privateKey 私钥
*
* @return 签名后字符串
*/
+(NSString *)singMD5String:(NSString *)string privateKey:(NSString *)privateKey;

/**
* RSA sha1 验证签名
*
* @param string 普通字符串
* @param signString 签名字符串(base64)
* @param publicKey 公钥
*
* @return 验证结果
*/
+(BOOL)verifyString:(NSString *)string sign:(NSString *)signString publicKey:(NSString *)publicKey;

/**
* RSA MD5 验证签名
*
* @param string 普通字符串
* @param signString 签名字符串
* @param publicKey 公钥
*
* @return 验证结果
*/
+(BOOL)verifyMD5String:(NSString *)string sign:(NSString *)signString publicKey:(NSString *)publicKey;
@end
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
#import "BBRSACryptor+XHAdd.h"

@implementation BBRSACryptor (XHCategory)

/**
* 生成公钥,私钥
*/
+(void)createPublicKeyAndPrivateKey
{
BBRSACryptor *reaCryptor = [[BBRSACryptor alloc] init];
[reaCryptor generateRSAKeyPairWithKeySize:1024];
}
/**
* 公钥加密
*
* @param string 普通字符串
* @param publicKey 公钥
*
* @return 加密后字符串
*/
+(NSString *)encryptString:(NSString *)string publicKey:(NSString *)publicKey
{
BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
if([rsaCryptor importRSAPublicKeyBase64:publicKey])
{
NSData *cipherData = [rsaCryptor encryptWithPublicKeyUsingPadding:RSA_PADDING_TYPE_PKCS1 plainData:[string dataUsingEncoding:NSUTF8StringEncoding]];
NSString *cipherString = [GTMBase64 stringByEncodingData:cipherData];
return cipherString;
}
return nil;
}

/**
* 公钥解密
*
* @param string 私钥加密字符串
* @param publicKey 公钥
*
* @return 解密后字符串
*/
+(NSString *)decodingString:(NSString *)string publicKey:(NSString *)publicKey
{
BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
if([rsaCryptor importRSAPublicKeyBase64:publicKey])
{
NSData *cipherData = [GTMBase64 decodeString:string];
NSData *plainData = [rsaCryptor decryptWithPublicKeyUsingPadding:RSA_PADDING_TYPE_PKCS1 cipherData:cipherData];
NSString *plainStr = [[NSString alloc]initWithData:plainData encoding:NSUTF8StringEncoding];
return plainStr;
}
return nil;
}

/**
* 私钥加密
*
* @param string 普通字符串
* @param privateKey 私钥
*
* @return 加密后字符串
*/
+(NSString *)encryptString:(NSString *)string privateKey:(NSString *)privateKey
{
BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
if([rsaCryptor importRSAPrivateKeyBase64:privateKey])
{
NSData *cipherData = [rsaCryptor encryptWithPrivateKeyUsingPadding:RSA_PKCS1_PADDING plainData:[string dataUsingEncoding:NSUTF8StringEncoding]];
NSString *cipherString = [GTMBase64 stringByEncodingData:cipherData];
return cipherString;
}
return nil;
}

/**
* 私钥解密
*
* @param string 公钥加密字符串
* @param privateKey 私钥
*
* @return 解密后字符串
*/
+(NSString *)decodingString:(NSString *)string privateKey:(NSString *)privateKey
{
BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
if([rsaCryptor importRSAPrivateKeyBase64:privateKey])
{
NSData *cipherData = [GTMBase64 decodeString:string];
NSData *plainData = [rsaCryptor decryptWithPrivateKeyUsingPadding:RSA_PADDING_TYPE_PKCS1 cipherData:cipherData];
NSString *plainText = [[NSString alloc]initWithData:plainData encoding:NSUTF8StringEncoding];
return plainText;
}
return nil;
}

/**
* 私钥签名
*
* @param string 普通字符串
* @param privateKey 私钥
*
* @return 签名后字符串
*/
+(NSString *)singString:(NSString *)string privateKey:(NSString *)privateKey
{

BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
if([rsaCryptor importRSAPrivateKeyBase64:privateKey])
{
NSString* sing= [rsaCryptor signString:string];
return sing;
}
return nil;
}

/**
* 私钥签名MD5
*
* @param string 普通字符串
* @param privateKey 私钥
*
* @return 签名后字符串
*/
+(NSString *)singMD5String:(NSString *)string privateKey:(NSString *)privateKey
{

BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
if([rsaCryptor importRSAPrivateKeyBase64:privateKey])
{
NSString* singMd5 = [rsaCryptor signMD5String:string];
return singMd5;
}
return nil;
}

/**
* RSA sha1 验证签名
*
* @param string 普通字符串
* @param signString 签名字符串(base64)
* @param publicKey 公钥
*
* @return 验证结果
*/
+(BOOL)verifyString:(NSString *)string sign:(NSString *)signString publicKey:(NSString *)publicKey
{
BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
if([rsaCryptor importRSAPublicKeyBase64:publicKey])
{
return [rsaCryptor verifyString:string withSign:signString];
}
return NO;
}

/**
* RSA MD5 验证签名
*
* @param string 普通字符串
* @param signString 签名字符串
* @param publicKey 公钥
*
* @return 验证结果
*/
+(BOOL)verifyMD5String:(NSString *)string sign:(NSString *)signString publicKey:(NSString *)publicKey
{
BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];
if([rsaCryptor importRSAPublicKeyBase64:publicKey])
{
return [rsaCryptor verifyMD5String:string withSign:signString];
}
return NO;
}
@end

第四步:使用案例

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
  NSString* private_key_string = @"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANv2AQ9nX46HX/+tIyi/j7L62z+jb4dy009+vADUg6F5oBGkDcdPLudcSQzP04iZLJifqWtngUoZ8Pc5WDDuaV4UvOsGzf8IjqzTGZD8eljKKxA+aV5HaMOp/7zTvSBzq0nGcuOWfAERk8L78/EpHwfAyM2XE9u3M2En4+HIkeq3AgMBAAECgYEAm/CV49PHnQZAesTGTlcwixTpZv55TS+Mu6j/pB8Fiu7tGlSSKCDtAb0dVOXp88eUJEfdFnX05RHrEXooGdiL/YQ1KaKcg2N25i9nn+vTQdgBZ64+HR0G47yrAMzvvOwCA7zZVK1+WF+DoK9M9tU7PRPOxMWNgHXPNq6IW21CGgECQQD3mxCofN0jbwWe49P7wEzz6tS2cmGwF0cAGy7zZdsPATs7Bvd/xQvb3/dUVFep/tado4bCi2bg+jQuzf5j4tM3AkEA42sDmDbDGmniWGZcdjaBVWl7Mbba8QTlO4lvS/1tgayU7QG0k+Hp4dpdE9E+LL3cZo3n9Zc+rbHIwr3JF1xkgQJAXVh9QDfKmqgpQ0x6x2co27AFPz8B6wPrhXO6EJKusgpxzQAEYIvlu5/Eu2sMnY7wU/+pN0CcqWZKM/b+16NUowJAZspZ55To/qlZS0eJB01/i9GPg1r4/vONgSmPirNTqccN0UpyCl2UTydZ5rku9x4h3qDJdXIVPIEdExihKdPzAQJBANx8nh0veU4ok1OFZnm8SUfZXMYc05g3iw2Q+1ZajCkFco4o1pXIIGn72QnuWJ18CvfnXTDquw826eaHWtlgis0=";


NSString* public_key_string = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDh5nxZMZ/lCttyHyrOh5AImOUh5OyATJ8fB5z4WlvBCxpe0rUAQ1VQfzOArxB+B4YUxokNijJxwpSiEYvfRk2Xz0I2/LxMq1g+8Stv6SPj4pe2NZRut5NLxLaihtb4Gfuw4GanX5bLauC7BY1akxyCSu0mRpFZ0nNHSuPnCzUHlQIDAQAB";

NSDictionary *stuDic = [NSDictionary dictionaryWithObjectsAndKeys:
@"小华",@"userAccount",
@"123456",@"phoneCode",
@"123456",@"password",
@"1",@"AppTye",
nil];
NSString *tempStr = [@"1|" stringByAppendingString:[self dictionaryToJson:stuDic]];
//NSString * jsonString =[self HAReplaceString:[NSString stringWithFormat:@"1|%@",[self dictionaryToJson:stuDic]] excuseString:@" " replaceSting:@""] ;
//格式化
NSString *str = [self HAReplaceString:tempStr excuseString:@" " replaceSting:@""];

// NSString * jsonString = @"123456";
NSString * jsonString = [self HAReplaceString:str excuseString:@"\n" replaceSting:@""];
NSLog(@"jsonString==%@",jsonString);
// NSData * testData = [GTMBase64 decodeString:public_key_string];
// NSString * testString = [[NSString alloc]initWithData:testData encoding:NSUTF8StringEncoding];
// NSLog(@"testString===%@",testString);
NSString * enString =[BBRSACryptor encryptString:jsonString publicKey:public_key_string];
// NSLog(@"加密==\n%@",enString);
// NSString * deString =[BBRSACryptor decodingString:enString privateKey:private_key_string];
// NSLog(@"解密===\n%@",deString);
NSString * sign = [BBRSACryptor singString:jsonString privateKey:private_key_string];
// NSLog(@"签名:\n%@",sign);
// BOOL match = [BBRSACryptor verifyString:jsonString sign:sign publicKey:public_key_string];
// NSLog(@"验签==%d",match);
// NSDictionary * dic =@{@"param":[NSString stringWithFormat:@"%@|%@",enString,sign]};
NSDictionary * dic =@{@"param":[NSString stringWithFormat:@"%@",sign],@"paramjson":jsonString};
NSLog(@"dic==%@===",dic);
[HABaseRequest requestWithURLName:@"register/registV"
Parameter:dic
SuccessBlock:^(id returnValue) {

} FailBlock:^(NSError *error) {

}];

参考github源码