苹果api rsa公钥加密私钥解密
2015-06-18 14:19
78 查看
static SecKeyRef _public_key=nil;
+ (SecKeyRef) getPublicKey{ // 从公钥证书文件中获取到公钥的SecKeyRef指针
if(_public_key == nil){
NSData *certificateData = [GTMBase64 decodeString:RSA_PUBLIC_KEY];
SecCertificateRef myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef)certificateData);
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecTrustRef myTrust;
OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);
SecTrustResultType trustResult;
if (status == noErr) {
status = SecTrustEvaluate(myTrust, &trustResult);
}
_public_key = SecTrustCopyPublicKey(myTrust);
CFRelease(myCertificate);
CFRelease(myPolicy);
CFRelease(myTrust);
}
return _public_key;
}
+ (NSString*) rsaEncryptString:(NSData*) stringBytes{
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([stringBytes length] / (double)blockSize);
NSMutableData *encryptedData = [[[NSMutableData alloc] init] autorelease];
for (int i=0; i<blockCount; i++) {
int bufferSize = MIN(blockSize,[stringBytes length] - i * blockSize);
NSData *buffer = [stringBytes 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];
[encryptedBytes release];
}else{
if (cipherBuffer) free(cipherBuffer);
return nil;
}
}
if (cipherBuffer) free(cipherBuffer);
// NSLog(@"Encrypted text (%d bytes): %@", [encryptedData length], [encryptedData description]);
// NSLog(@"Encrypted text base64: %@", [Base64 encode:encryptedData]);
return [self hexStringFromData:encryptedData];
}
+ (NSData*)rsaDecryptWithString:(NSString*)plaintext{
NSData *data = [SecurityUtil stringToHexData:plaintext];
SecKeyRef key = [self getPublicKey];
size_t plainBufferSize = SecKeyGetBlockSize(key);
uint8_t *plainBuffer = malloc(plainBufferSize * sizeof(uint8_t));
int totalLength = [data length];
size_t blockSize = plainBufferSize;
size_t blockCount = (size_t)ceil(totalLength/blockSize);
NSMutableData *decryptedData = [NSMutableData data];
for (int i=0; i<blockCount; i++){
NSUInteger loc = i * blockSize;
int dataSegmentRealSize = MIN(blockSize, totalLength - i * blockSize);
NSData *dataSegment = [data subdataWithRange:NSMakeRange(loc, dataSegmentRealSize)];
OSStatus status = SecKeyDecrypt(key,
kSecPaddingPKCS1,
(const uint8_t *) [dataSegment bytes],
[dataSegment length],
plainBuffer,
&plainBufferSize);
NSAssert(status == noErr, @"Error decrypting, OSStatus == %d.", (int)status);
if(status == noErr){
NSData *decryptedDataSegment = [[NSData alloc] initWithBytes:(const void *) plainBuffer length:plainBufferSize];
[decryptedData appendData:decryptedDataSegment];
[decryptedDataSegment release];
}else{
if(plainBuffer){
free(plainBuffer);
}
return nil;
}
}
if(plainBuffer){
free(plainBuffer);
}
return decryptedData;
}
+ (SecKeyRef) getPublicKey{ // 从公钥证书文件中获取到公钥的SecKeyRef指针
if(_public_key == nil){
NSData *certificateData = [GTMBase64 decodeString:RSA_PUBLIC_KEY];
SecCertificateRef myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef)certificateData);
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecTrustRef myTrust;
OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);
SecTrustResultType trustResult;
if (status == noErr) {
status = SecTrustEvaluate(myTrust, &trustResult);
}
_public_key = SecTrustCopyPublicKey(myTrust);
CFRelease(myCertificate);
CFRelease(myPolicy);
CFRelease(myTrust);
}
return _public_key;
}
+ (NSString*) rsaEncryptString:(NSData*) stringBytes{
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([stringBytes length] / (double)blockSize);
NSMutableData *encryptedData = [[[NSMutableData alloc] init] autorelease];
for (int i=0; i<blockCount; i++) {
int bufferSize = MIN(blockSize,[stringBytes length] - i * blockSize);
NSData *buffer = [stringBytes 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];
[encryptedBytes release];
}else{
if (cipherBuffer) free(cipherBuffer);
return nil;
}
}
if (cipherBuffer) free(cipherBuffer);
// NSLog(@"Encrypted text (%d bytes): %@", [encryptedData length], [encryptedData description]);
// NSLog(@"Encrypted text base64: %@", [Base64 encode:encryptedData]);
return [self hexStringFromData:encryptedData];
}
+ (NSData*)rsaDecryptWithString:(NSString*)plaintext{
NSData *data = [SecurityUtil stringToHexData:plaintext];
SecKeyRef key = [self getPublicKey];
size_t plainBufferSize = SecKeyGetBlockSize(key);
uint8_t *plainBuffer = malloc(plainBufferSize * sizeof(uint8_t));
int totalLength = [data length];
size_t blockSize = plainBufferSize;
size_t blockCount = (size_t)ceil(totalLength/blockSize);
NSMutableData *decryptedData = [NSMutableData data];
for (int i=0; i<blockCount; i++){
NSUInteger loc = i * blockSize;
int dataSegmentRealSize = MIN(blockSize, totalLength - i * blockSize);
NSData *dataSegment = [data subdataWithRange:NSMakeRange(loc, dataSegmentRealSize)];
OSStatus status = SecKeyDecrypt(key,
kSecPaddingPKCS1,
(const uint8_t *) [dataSegment bytes],
[dataSegment length],
plainBuffer,
&plainBufferSize);
NSAssert(status == noErr, @"Error decrypting, OSStatus == %d.", (int)status);
if(status == noErr){
NSData *decryptedDataSegment = [[NSData alloc] initWithBytes:(const void *) plainBuffer length:plainBufferSize];
[decryptedData appendData:decryptedDataSegment];
[decryptedDataSegment release];
}else{
if(plainBuffer){
free(plainBuffer);
}
return nil;
}
}
if(plainBuffer){
free(plainBuffer);
}
return decryptedData;
}
相关文章推荐
- 关于搭建haddoop分布式系统的全部过程复习
- 《构建之法》13~17章
- CC消隐字幕
- 怎样两周掌握GRE词汇
- 跳表(skiplist)的代码实现
- res与res-auto的区别
- 11.备忘录模式
- php实现socket 比较详细
- MapReduce工作原理图文详解
- 卷积神经网络
- MapReduce工作原理图文详解
- LVM 常用命令
- mysql表分区
- 编写函数strndel,参量是一个字符串string和两个整数start、length。在string中删除start开始的length个字符,最后返回string。
- Linux、hive、sqoop常用脚本
- git---连接github
- centos下安装jdk + tomcat记录
- 跨浏览器设置-你必须了解的浏览器默认样式(User Agent StyleSheet)
- 关注技术-互联网人物
- flashsim源码阅读笔记3