rsa从cer证书中拿公钥进行加密

来源:互联网 发布:java语言怎么学 编辑:程序博客网 时间:2024/06/05 03:56
   起初,读召辉给的cer证书的时候,

SecCertificateCreateWithData

总是返回为nil,原因是因为这个证书是服务器自己生成的,不是正规的CA机构颁发的,苹果安全性要求是很高的,所以这个读不出来,直接导致后面的崩溃。后来折腾了半天,比如直接从证书里面导出字符串作为公钥,也不行,安卓这样也是不行的。            

后来迪哥又生成了个der证书,这样读就是正常的,这样就能正常的拿到公钥。

- (id)init {

    

    self = [superinit];

    NSString *publicKeyPath = [[NSBundlemainBundle] pathForResource:@"public-rsa"ofType:@"der"];

    //從檔案讀取公鑰

    

    if (publicKeyPath ==nil) {

        NSLog(@"Can not find pub.der");

        returnnil;

    }

    

    NSDate *publicKeyFileContent = [NSDatadataWithContentsOfFile:publicKeyPath];

    if (publicKeyFileContent ==nil) {

        NSLog(@"Can not read from pub.der");

        returnnil;

    }

    

    certificate =SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)publicKeyFileContent);

    if (certificate ==nil) {

        NSLog(@"Can not read certificate from pub.der");

        returnnil;

    }

    

    policy =SecPolicyCreateBasicX509();

    OSStatus returnCode =SecTrustCreateWithCertificates(certificate,policy, &trust);

    if (returnCode !=0) {

        NSLog(@"SecTrustCreateWithCertificates fail. Error Code: %ld", returnCode);

        returnnil;

    }

    

    SecTrustResultType trustResultType;

    returnCode = SecTrustEvaluate(trust, &trustResultType);

    if (returnCode !=0) {

        returnnil;

    }

    

    publicKey =SecTrustCopyPublicKey(trust);

    if (publicKey ==nil) {

        NSLog(@"SecTrustCopyPublicKey fail");

        returnnil;

    }

    

    maxPlainLen =SecKeyGetBlockSize(publicKey) -12;

    returnself;

}


        

//利用公钥 RSA加密

- (NSData *) encryptWithData:(NSData *)content {

    

    size_t plainLen = [contentlength];

    if (plainLen >maxPlainLen) {

        NSLog(@"content(%ld) is too long, must < %ld", plainLen,maxPlainLen);

        returnnil;

    }

    

    void *plain =malloc(plainLen);

    [content getBytes:plain

               length:plainLen];

    

    size_t cipherLen =256; // 目前使用的RSA加密長度為2048bits(即256bytes)

    void *cipher =malloc(cipherLen);

    

    OSStatus returnCode =SecKeyEncrypt(publicKey,kSecPaddingPKCS1, plain,

                                        plainLen, cipher, &cipherLen);

    

    NSData *result =nil;

    if (returnCode !=0) {

        NSLog(@"SecKeyEncrypt fail. Error Code: %ld", returnCode);

    }

    else {

        result = [NSDatadataWithBytes:cipher length:cipherLen];

    }

    

    free(plain);

    free(cipher);

    

    return result;

}


- (NSData *) encryptWithString:(NSString *)content {

    return [selfencryptWithData:[contentdataUsingEncoding:NSUTF8StringEncoding]];

}


- (NSString *) encryptToString:(NSString *)content {

    NSData *data = [selfencryptWithString:content];

    return [selfbase64forData:data];

}


// convert NSData to NSString

- (NSString *)base64forData:(NSData *)theData {

    constuint8_t* input = (constuint8_t*)[theData bytes];

    NSInteger length = [theDatalength];

    

    staticchar table[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    

    NSMutableData* data = [NSMutableDatadataWithLength:((length +2) / 3) *4];

    uint8_t* output = (uint8_t*)data.mutableBytes;

    

    NSInteger i;

    for (i=0; i < length; i +=3) {

        NSInteger value =0;

        NSInteger j;

        for (j = i; j < (i +3); j++) {

            value <<= 8;

            

            if (j < length) {

                value |= (0xFF & input[j]);

            }

        }

        

        NSInteger theIndex = (i /3) * 4;

        output[theIndex + 0] =                    table[(value >>18) & 0x3F];

        output[theIndex + 1] =                    table[(value >>12) & 0x3F];

        output[theIndex + 2] = (i +1) < length ? table[(value >>6)  & 0x3F] :'=';

        output[theIndex + 3] = (i +2) < length ? table[(value >>0)  & 0x3F] :'=';

    }

    

    return [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

}


- (void)dealloc{

    CFRelease(certificate);

    CFRelease(trust);

    CFRelease(policy);

    CFRelease(publicKey);

}




0 0