iOS rsa加密與解密

來源:互聯網
上載者:User

標籤:

轉自 --響鈴  IOS rsa加密與解密

 

ras加密需要兩組秘鑰,一組公用秘鑰,一組私人秘鑰。

產生命令:

openssl req -x509 -out public_key.der -outform der -new -newkey rsa:2048 -keyout private_key.pem

public_key.der為公用秘鑰檔案,private_key.pem為私人秘鑰檔案。

產生ios可引用的私人秘鑰檔案.pfx:

1. OpenSSL rsa -in private_key.pem -out private_key.key

2. OpenSSL req -new -key private_key.key -out private_key.crt

3. OpenSSL x509 -req -days 3650 -in private_key.crt -signkey private_key.key -out rsaCert.crt

4. OpenSSL x509 -outform der -in rsaCert.crt -out rsaCert.der

5. OpenSSL pkcs12 -export -out private_key.pfx -inkey private_key.key -in rsaCert.crt

private_key.pfx即為產生的檔案

 

公用秘鑰的引用:

- (SecKeyRef)getPublicKey

{

    SecCertificateRef myCertificate = nil;

    NSString *path = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];

    NSData *certificateData = [NSData dataWithContentsOfFile:path];

    myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridgeCFDataRef)certificateData);

    SecPolicyRef myPolicy = SecPolicyCreateBasicX509();

    SecTrustRef myTrust;

    OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);

    SecTrustResultType trustResult;

    if (status == noErr) {

        status = SecTrustEvaluate(myTrust, &trustResult);

    }

    return SecTrustCopyPublicKey(myTrust);

 

}

 

私人秘鑰的引用

- (SecKeyRef)getPrivateKey

{

    NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"private_key"ofType:@"pfx"];

    NSData *pfxkeyData = [[NSData alloc]initWithContentsOfFile:publicKeyPath];

    

    NSMutableDictionary * options = [[NSMutableDictionary alloc] init];

    [options setObject:@"password" forKey:(__bridge id)kSecImportExportPassphrase];

    

    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);

    

    OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) pfxkeyData,

                                             (__bridge CFDictionaryRef)options, &items);

    

    CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);

    SecIdentityRef identityApp =

    (SecIdentityRef)CFDictionaryGetValue(identityDict,

                                         kSecImportItemIdentity);

    

    assert(securityError == noErr);

    SecKeyRef privateKeyRef;

    SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);

    

    return privateKeyRef;

 

}

 

公開金鑰加密:

- (NSData*)rsaEncryptWithData:(NSData*)data usingKey:(SecKeyRef)key{

    

    size_t cipherBufferSize = SecKeyGetBlockSize(key);

    uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));

    memset((void *)cipherBuffer, 0*0, cipherBufferSize);

    

    NSData *plainTextBytes = data;

    size_t blockSize = cipherBufferSize - 11;

    size_t blockCount = (size_t)ceil([plainTextBytes length] / (double)blockSize);

    NSMutableData *encryptedData = [NSMutableData dataWithCapacity:0];

    

    for (int i=0; i<blockCount; i++) {

        

        int bufferSize = MIN(blockSize,[plainTextBytes length] - i * blockSize);

        NSData *buffer = [plainTextBytes 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 dataWithBytes:(const void *)cipherBuffer length:cipherBufferSize];

            [encryptedData appendData:encryptedBytes];

            

        }else{

            

            if (cipherBuffer) {

                free(cipherBuffer);

            }

            return nil;

        }

    }

    if (cipherBuffer) free(cipherBuffer);

    return encryptedData;

 

}

 

私密金鑰解密:

- (NSData*)rsaDecryptWithData:(NSData*)data usingKey:(SecKeyRef)key{

    NSData *wrappedSymmetricKey = data;

    

    size_t cipherBufferSize = SecKeyGetBlockSize(key);

    size_t keyBufferSize = [wrappedSymmetricKey length];

    

    NSMutableData *bits = [NSMutableData dataWithLength:keyBufferSize];

    OSStatus sanityCheck = SecKeyDecrypt(key,

                                         kSecPaddingPKCS1,

                                         (const uint8_t *) [wrappedSymmetricKey bytes],

                                         cipherBufferSize,

                                         [bits mutableBytes],

                                         &keyBufferSize);

    NSAssert(sanityCheck == noErr, @"Error decrypting, OSStatus == %ld.", sanityCheck);

    

    [bits setLength:keyBufferSize];

    

    return bits;

 

}

 

加密解密網上有寫好的ras.m,可以參考:

http://code4app.com/ios/RSA-Encrypt-and-Decrypt/5061d6476803faf86c000001

iOS rsa加密與解密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.