将RSA公钥发送到iphone并使用它进行加密

Sta*_*Yeo 11 c++ iphone openssl cryptography rsa

我有一个TCP套接字服务器,我想使用SSL执行以下操作:

  1. 在服务器上,制作RSA密钥对(我知道如何使用openssl的加密库)
  2. 在服务器上,将公钥发送到iphone并保留私钥.
  3. 在客户端(iphone)上,要使用SecKeyEncrypt使用公钥加密消息.
  4. 在服务器上,解密消息.

消息足够短,以便PKCS1填充结果适合128个字节.

我不知道怎么做2~4.有谁知道?

sca*_*aba 18

这应该是您要求的 - 它使用服务器的公钥加密数据.它不受MITM攻击,除非攻击者拥有您的私钥及其密码的副本(通过非SSL进行通信,但仍然是,但是使用服务器的合法公钥加密的数据几乎不可能解密) .

我从Apple的文档,这个网站,Apple开发者论坛以及其他地方拼凑了这些.所以感谢大家,我从中抄写了代码!这段代码假定了几件事:

  1. 您已经生成了RSA密钥对(我使用的是4096位密钥并且看起来足够快)并且使用私钥创建了一个名为"cert.cer"的DER编码证书,并将其放入资源中捆绑您的应用程序(显然,您也可以从您的服务器下载证书,但之后您再次接受MITM攻击).默认情况下,OpenSSL生成PEM编码的证书,因此您必须使用"openssl x509 -in cert.pem -inform PEM -out cert.cer -outform DER"进行转换.iOS将在PEM上进行barf.我使用证书的原因是它实际上更容易使用,并且在iOS中受支持.仅使用公钥(虽然可以完成).

  2. 您已将Security.framework添加到项目中,并且#import <Security/Security.h>.

/*返回加密文本的NSData,如果加密不成功,则返回nil.
将X.509证书作为NSData(例如,来自dataWithContentsOfFile:)*/

+(NSData *)encryptString:(NSString *)plainText withX509Certificate:(NSData *)certificate {

    SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certificate);
    SecPolicyRef policy = SecPolicyCreateBasicX509();
    SecTrustRef trust;
    OSStatus status = SecTrustCreateWithCertificates(cert, policy, &trust);

    SecTrustResultType trustResult;
    if (status == noErr) {
        status = SecTrustEvaluate(trust, &trustResult);
    }

    SecKeyRef publicKey = SecTrustCopyPublicKey(trust);

    const char *plain_text = [plainText UTF8String];
    size_t blockSize = SecKeyGetBlockSize(publicKey);
    NSMutableData *collectedCipherData = [NSMutableData data];

    BOOL success = YES;
    size_t cipherBufferSize = blockSize;
    uint8_t *cipherBuffer = malloc(blockSize);

    int i;
    for (i = 0; i < strlen(plain_text); i += blockSize-11) {
        int j;
        for (j = 0; j < blockSize-11 && plain_text[i+j] != '\0'; ++j) {
            cipherBuffer[j] = plain_text[i+j];
        }

        int result;
        if ((result = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, cipherBuffer, j, cipherBuffer, &cipherBufferSize)) == errSecSuccess) {
            [collectedCipherData appendBytes:cipherBuffer length:cipherBufferSize];
        } else {
            success = NO;
            break;
        }
    }

    /* Free the Security Framework Five! */
    CFRelease(cert);
    CFRelease(policy);
    CFRelease(trust);
    CFRelease(publicKey);
    free(cipherBuffer);

    if (!success) {
        return nil;
    }

    return [NSData dataWithData:collectedCipherData];
}
Run Code Online (Sandbox Code Playgroud)

  • +1"Free the Security Framework Five!" (3认同)