-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRSAEncryptor.m
More file actions
144 lines (128 loc) · 5.46 KB
/
Copy pathRSAEncryptor.m
File metadata and controls
144 lines (128 loc) · 5.46 KB
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
// http://www.cnblogs.com/makemelike/articles/3802518.html
#import "RSAEncryptor.h"
#import <Security/Security.h>
@implementation RSAEncryptor{
SecKeyRef publicKey;
SecKeyRef privateKey;
}
- (void)dealloc{
CFRelease(publicKey);
CFRelease(privateKey);
}
- (SecKeyRef)getPublicKey {
return publicKey;
}
- (SecKeyRef)getPrivateKey {
return privateKey;
}
- (void)loadPublicKeyFromFile: (NSString*) derFilePath{
NSData *derData = [[NSData alloc] initWithContentsOfFile:derFilePath];
[self loadPublicKeyFromData: derData];
}
- (void)loadPublicKeyFromData: (NSData*) derData{
publicKey = [self getPublicKeyRefrenceFromeData: derData];
}
- (void)loadPrivateKeyFromFile: (NSString*) p12FilePath password:(NSString*)p12Password{
NSData *p12Data = [NSData dataWithContentsOfFile:p12FilePath];
[self loadPrivateKeyFromData: p12Data password:p12Password];
}
- (void)loadPrivateKeyFromData: (NSData*) p12Data password:(NSString*)p12Password{
privateKey = [self getPrivateKeyRefrenceFromData: p12Data password: p12Password];
}
#pragma mark - Private Methods
- (SecKeyRef) getPublicKeyRefrenceFromeData: (NSData*)derData{
SecCertificateRef myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)derData);
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecTrustRef myTrust;
OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);
SecTrustResultType trustResult;
if (status == noErr) {
status = SecTrustEvaluate(myTrust, &trustResult);
}
SecKeyRef securityKey = SecTrustCopyPublicKey(myTrust);
CFRelease(myCertificate);
CFRelease(myPolicy);
CFRelease(myTrust);
return securityKey;
}
- (SecKeyRef) getPrivateKeyRefrenceFromData: (NSData*)p12Data password:(NSString*)password{
SecKeyRef privateKeyRef = NULL;
NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
[options setObject: password forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data, (__bridge CFDictionaryRef)options, &items);
if (securityError == noErr && CFArrayGetCount(items) > 0) {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
if (securityError != noErr) {
privateKeyRef = NULL;
}
}
CFRelease(items);
return privateKeyRef;
}
#pragma mark - Encrypt
- (NSString*) rsaEncryptString:(NSString*)string {
NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData* encryptedData = [self rsaEncryptData: data];
NSString* base64EncryptedString = [encryptedData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
return base64EncryptedString;
}
// 加密的大小受限于SecKeyEncrypt函数,SecKeyEncrypt要求明文和密钥的长度一致,如果要加密更长的内容,需要把内容按密钥长度分成多份,然后多次调用SecKeyEncrypt来实现
- (NSData*) rsaEncryptData:(NSData*)data {
SecKeyRef key = [self getPublicKey];
size_t cipherBufferSize = SecKeyGetBlockSize(key);
uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
size_t blockSize = cipherBufferSize - 11; // 分段加密
size_t blockCount = (size_t)ceil([data length] / (double)blockSize);
NSMutableData *encryptedData = [[NSMutableData alloc] init] ;
for (int i=0; i<blockCount; i++) {
NSInteger bufferSize = MIN(blockSize,[data length] - i * blockSize);
NSData *buffer = [data subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
OSStatus status = SecKeyEncrypt(key, kSecPaddingPKCS1, (const uint8_t *)[buffer bytes], [buffer length], cipherBuffer, &cipherBufferSize);
if (status == noErr){
NSData *encryptedBytes = [[NSData alloc] initWithBytes:(const void *)cipherBuffer length:cipherBufferSize];
[encryptedData appendData:encryptedBytes];
}else{
if (cipherBuffer) {
free(cipherBuffer);
}
return nil;
}
}
if (cipherBuffer){
free(cipherBuffer);
}
return encryptedData;
}
#pragma mark - Decrypt
- (NSString*) rsaDecryptString:(NSString*)string {
NSData* data = [[NSData alloc] initWithBase64EncodedString:string options:0];
NSData* decryptData = [self rsaDecryptData: data];
NSString* result = [[NSString alloc] initWithData: decryptData encoding:NSUTF8StringEncoding];
return result;
}
- (NSData*) rsaDecryptData:(NSData*)data {
SecKeyRef key = [self getPrivateKey];
size_t cipherLen = [data length];
void *cipher = malloc(cipherLen);
[data getBytes:cipher length:cipherLen];
size_t plainLen = SecKeyGetBlockSize(key) - 12;
void *plain = malloc(plainLen);
OSStatus status = SecKeyDecrypt(key, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);
if (status != noErr) {
return nil;
}
NSData *decryptedData = [[NSData alloc] initWithBytes:(const void *)plain length:plainLen];
return decryptedData;
}
#pragma mark - Class Methods
static RSAEncryptor* sharedInstance = nil;
+ (void) setSharedInstance: (RSAEncryptor*)instance{
sharedInstance = instance;
}
+ (RSAEncryptor*) sharedInstance{
return sharedInstance;
}
@end