RSA 用Security.framwork解密问题


我用RSA的public key来解密,php那边用private key来加密,用的Security.framework来解密。但是解出来的数据前面多了一小串奇怪的乱码,后面数据是正确的。谁能帮我看看哪里有问题?


 - (NSData *)decryptToDataWithPublicKey: (NSData *)dataToDecrypt
{
    NSData *wrappedSymmetricKey = dataToDecrypt;
    SecKeyRef key = self.publicKey;//这是之前已经成功使用的SecKeyRef

    size_t cipherBufferSize = SecKeyGetBlockSize(key);
    size_t keyBufferSize = [wrappedSymmetricKey length];

    NSMutableData *bits = [NSMutableData dataWithLength:keyBufferSize];
    __unused OSStatus sanityCheck = SecKeyDecrypt(key,
                                         kSecPaddingNone,
                                         (const uint8_t *) [wrappedSymmetricKey bytes],
                                         cipherBufferSize,
                                         [bits mutableBytes],
                                         &keyBufferSize);
    [bits setLength:keyBufferSize];
    return [bits copy];
}

最后的数据前面多了一堆fffff,不知道哪里出了问题..
f结束后的数据是正确的。
图片描述

ios rsa

撸管强力3连发 9 years, 2 months ago

自问自答吧。最后这个方法还是没有找到解决方案,最后弃用了 Security.framework ,而是利用OC兼容C的特性,倒入openssl的framework,用openssl的函数解密。


 - (NSString *)decryptToDataWithPublicKey: (NSString *)dataToDecrypt
{

    NSData *contentData = [dataToDecrypt base64DecodedData];
    unsigned char *decrypted = (unsigned char *)malloc(rsa_public_len - 1);

    char *err = NULL;

    if (RSA_public_decrypt([contentData length], [contentData bytes], decrypted, rsa_publicKey, RSA_NO_PADDING) == -1) {
        ERR_load_CRYPTO_strings();
        fprintf(stderr, "Error %s\n", ERR_error_string(ERR_get_error(), err));
        fprintf(stderr, "Error %s\n", err);
        return nil;
    }
    RSA_free(rsa_publicKey);
    NSString *str = [NSString stringWithUTF8String:(char *) decrypted];
    return str;
}

我只是扎古而已 answered 9 years, 2 months ago

Your Answer