-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathNSData+KKRSA.m
94 lines (83 loc) · 2.2 KB
/
NSData+KKRSA.m
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
//
// NSData+KKRSA.m
// SecurityiOS
//
// Created by cocoa on 16/12/15.
// Copyright © 2016年 dev.keke@gmail.com. All rights reserved.
//
#import "NSData+KKRSA.h"
#import <Security/Security.h>
@implementation NSData (KKRSA)
/**
公钥加密
*/
- (NSData *)RSAEncryptWith:(SecKeyRef )publicKey paddingType:(RSAPaddingTYPE )pdType
{
if (!publicKey || self.length <1) {
return nil;
}
OSStatus ret;
NSData *retData = nil;
size_t blockSize = SecKeyGetBlockSize(publicKey);
uint8_t *encData = malloc(blockSize);
bzero(encData, blockSize);
SecPadding rsaPdd;
switch (pdType) {
case RSAPaddingNONE:
rsaPdd = kSecPaddingNone;
break;
case RSAPaddingPKCS1:
rsaPdd = kSecPaddingPKCS1;
break;
case RSAPaddingOAEP:
rsaPdd = kSecPaddingOAEP;
break;
default:
rsaPdd = kSecPaddingPKCS1;
break;
}
ret = SecKeyEncrypt(publicKey, rsaPdd, self.bytes, self.length, encData, &blockSize);
if (ret==errSecSuccess) {
retData = [NSData dataWithBytes:encData length:blockSize];
}
free(encData);
encData = NULL;
return retData;
}
/**
私钥解密
*/
- (NSData *)RSADecryptWith:(SecKeyRef )privateKey paddingType:(RSAPaddingTYPE )pdType
{
if (!privateKey || self.length <1) {
return nil;
}
NSData *retData = nil;
OSStatus ret;
size_t blockSize = SecKeyGetBlockSize(privateKey);
uint8_t *decData = malloc(blockSize);
bzero(decData, blockSize);
SecPadding rsaPdd;
switch (pdType) {
case RSAPaddingNONE:
rsaPdd = kSecPaddingNone;
break;
case RSAPaddingPKCS1:
rsaPdd = kSecPaddingPKCS1;
break;
case RSAPaddingOAEP:
rsaPdd = kSecPaddingOAEP;
break;
default:
rsaPdd = kSecPaddingPKCS1;
break;
}
ret = SecKeyDecrypt(privateKey, rsaPdd, self.bytes, self.length, decData, &blockSize);
if (ret==errSecSuccess) {
retData = [NSData dataWithBytes:decData length:blockSize];
}
free(decData);
decData = NULL;
return retData;
}
@end