IOS ECC 加密探索随笔:
//使用该方法无法用PEM格式公钥生成SecKeyRef 公钥,待解决。
+(SecKeyRef)getPublicKeyFromPem:(NSString*)key{
// 下面是对于 PEM 格式的密钥文件的密钥多余信息的处理,通常 DER 不需要这一步
//NSString *key = @"PEM 格式的密钥文件";
NSRange spos;
NSRange epos;
//-----BEGIN PUBLIC KEY-----
spos = [key rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];
if(spos.length > 0){
epos = [key rangeOfString:@"-----END RSA PRIVATE KEY-----"];
}else{
spos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
epos = [key rangeOfString:@"-----END PUBLIC KEY-----"];
}
if(spos.location != NSNotFound && epos.location != NSNotFound){
NSUInteger s = spos.location + spos.length;
NSUInteger e = epos.location;
NSRange range = NSMakeRange(s, e-s);
key = [key substringWithRange:range];
}
key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
// This will be base64 encoded, decode it.
//NSData *data = base64_decode(key);
NSData *data = [UtilityHelper Base64Convert2Str:key]
//NSData *data =[key dataUsingEncoding:NSUTF8StringEncoding];
if(!data){
return nil;
}
NSString * strtemp =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// 设置属性字典
NSMutableDictionary *options = [NSMutableDictionary dictionary];
//并尝试kSecAttrKeyTypeEC 也不行
options[(__bridge id)kSecAttrKeyType] = (__bridge id) kSecAttrKeyTypeECSECPrimeRandom;
options[(__bridge id)kSecAttrKeyClass] = (__bridge id) kSecAttrKeyClassPublic;
NSNumber *size = @2048;
options[(__bridge id)kSecAttrKeySizeInBits] = size;
NSError *error = nil;
CFErrorRef ee = (__bridge CFErrorRef)error;
// 调用接口获取密钥对象
SecKeyRef ret = SecKeyCreateWithData((__bridge CFDataRef)data, (__bridge CFDictionaryRef)options, &ee);
if (error) {
return nil;
}
return ret;
}
公钥PEM为:-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2+nDUyXeL6wAu5UAIIhdFdClJNdysydKysyozXtY
W3xXb6szLjA0FpV+mRcHWl+28cV4LxjqTEs+pEvu3bVzng==
-----END PUBLIC KEY-----
运行情况:
网友评论