私钥加密:
1.使用哈希算法获取待签名字符串的摘要
+ (NSData *)sha256:(NSString *)str {
const char *s = [str cStringUsingEncoding:str];
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
uint8_t digest [CC_SHA256_DIGEST_LENGTH] = {0};
CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);
NSData *outData = [NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
return outData;
}
2.使用私钥字符串获取SecKeyRef指针,通过读取pem文件即可获取,网上代码很多。也可使用指数、模数生成,参考此库。
3.使用sha256WithRSA加密数据
// sha256加密
NSData *outData = [self sha256:storString];
size_t signedHashBytesSize = SecKeyGetBlockSize(privateKey);
uint8_t* signedHashBytes = malloc(signedHashBytesSize);
memset(signedHashBytes, 0x0, signedHashBytesSize);
size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH;
uint8_t* hashBytes = malloc(hashBytesSize);
if (!CC_SHA256([outData bytes], (CC_LONG)[outData length], hashBytes)) {
return nil;
}
SecKeyRawSign(privateKey,
kSecPaddingPKCS1SHA256,
hashBytes,
hashBytesSize,
signedHashBytes,
&signedHashBytesSize);
NSData* signedHash = [NSData dataWithBytes:signedHashBytes length:(NSUInteger)signedHashBytesSize];
if (hashBytes)
free(hashBytes);
if (signedHashBytes)
free(signedHashBytes);
NSString *signString = [signedHash base64EncodedStringWithOptions:NSUTF8StringEncoding];
NSLog(@"%@",signString);
公钥验签:
// sha256加密
NSData *outData = [self sha256:response];
// 签名base64解码
NSData *signData = [[NSData alloc] initWithBase64EncodedString:signString options:NSDataBase64DecodingIgnoreUnknownCharacters];
// 签名验证
size_t signedHashBytesSize = SecKeyGetBlockSize(publicKey);
const void* signedHashBytes = [signData bytes];
size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH;
uint8_t* hashBytes = malloc(hashBytesSize);
if (!CC_SHA256([outData bytes], (CC_LONG)[outData length], hashBytes)) {
return NO;
}
OSStatus status = SecKeyRawVerify(publicKey,
kSecPaddingPKCS1SHA256,
hashBytes,
hashBytesSize,
signedHashBytes,
signedHashBytesSize);
if (hashBytes)
free(hashBytes);
status == errSecSuccess;