-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathNSData+KKSignVerify.m
100 lines (90 loc) · 2.48 KB
/
NSData+KKSignVerify.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
95
96
97
98
99
100
//
// NSData+KKSignVerify.m
// SecurityiOS
//
// Created by cocoa on 16/12/15.
// Copyright © 2016年 dev.keke@gmail.com. All rights reserved.
//
#import "NSData+KKSignVerify.h"
#import <Security/Security.h>
@implementation NSData (KKSignVerify)
/**
根据不同的算法,签名数据,
*/
- (NSData *)signDataWith:(SecKeyRef)privateKey algorithm:(SEC_PKCS1_ALGORITHM )ccAlgorithm
{
if (!privateKey || self.length <1) {
return nil;
}
OSStatus ret;
NSData *retData = nil;
size_t siglen = SecKeyGetBlockSize(privateKey);
uint8_t *sig = malloc(siglen);
bzero(sig, siglen);
SecPadding secpdal ;
switch (ccAlgorithm) {
case SEC_PKCS1SHA1:
secpdal = kSecPaddingPKCS1SHA1;
break;
case SEC_PKCS1SHA224:
secpdal = kSecPaddingPKCS1SHA224;
break;
case SEC_PKCS1SHA256:
secpdal = kSecPaddingPKCS1SHA256;
break;
case SEC_PKCS1SHA384:
secpdal = kSecPaddingPKCS1SHA384;
break;
case SEC_PKCS1SHA512:
secpdal = kSecPaddingPKCS1SHA512;
break;
default:
secpdal = kSecPaddingPKCS1SHA1;
break;
}
ret = SecKeyRawSign(privateKey, secpdal, self.bytes, self.length, sig, &siglen);
if (ret==errSecSuccess) {
retData = [NSData dataWithBytes:sig length:siglen];
}
free(sig);
sig = NULL;
return retData;
}
/**
验证签名
*/
- (BOOL)verifySignWith:(SecKeyRef)publicKey signData:(NSData *)signData algorithm:(SEC_PKCS1_ALGORITHM )ccAlgorithm
{
if (!publicKey || self.length <1) {
return NO;
}
OSStatus ret;
BOOL retStatus = NO;
SecPadding secpdal ;
switch (ccAlgorithm) {
case SEC_PKCS1SHA1:
secpdal = kSecPaddingPKCS1SHA1;
break;
case SEC_PKCS1SHA224:
secpdal = kSecPaddingPKCS1SHA224;
break;
case SEC_PKCS1SHA256:
secpdal = kSecPaddingPKCS1SHA256;
break;
case SEC_PKCS1SHA384:
secpdal = kSecPaddingPKCS1SHA384;
break;
case SEC_PKCS1SHA512:
secpdal = kSecPaddingPKCS1SHA512;
break;
default:
secpdal = kSecPaddingPKCS1SHA1;
break;
}
ret = SecKeyRawVerify(publicKey, secpdal, self.bytes, self.length,signData.bytes, signData.length);
if (ret==errSecSuccess) {
retStatus = YES;
}
return retStatus;
}
@end