使用RSA / SHA-1签名时崩溃

时间:2015-06-02 11:18:36

标签: ios objective-c openssl keychain

我在下面的代码中使用带有私钥的唱歌字符串。

我在iPhone钥匙串中有私钥。现在获取钥匙串中的私钥并传递到PEM_read_RSAPrivateKey:

- (NSString *)RSASHA1HashForString:(NSString *)source {

    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc]
                                         initWithIdentifier:@"TestKeychain"
                                         accessGroup:@"keys"];       

    if (source == nil) return nil;

    OpenSSL_add_all_algorithms();

    NSString *signature = nil;

    // make a SHA-1 digest of the source string
    const char* sourceChars = [source UTF8String];

    unsigned char digest[SHA_DIGEST_LENGTH];
    SHA1((const unsigned char *)sourceChars, strlen(sourceChars), digest);        

    FILE *secretFile;
    RSA *rsa = NULL;
    @try {
        NSData *privateKeyFileData = [keychainItem objectForKey:(__bridge id)kSecAttrLabel];

        secretFile = (__bridge FILE *)(privateKeyFileData);

        PEM_read_RSAPrivateKey(secretFile, &rsa, NULL, NULL);
    }
    @catch (NSException *exception) {
        NSLog(@"Error %@",[exception description]);
    }

    if (rsa != NULL) {

        unsigned int sigLen = 0;
        unsigned char *sigBuff = malloc(RSA_size(rsa));

        int result = RSA_sign(NID_sha1, digest, (unsigned int) sizeof(digest),
                              sigBuff, &sigLen, rsa);

        if (result != 0) {
            NSData *sigData = [NSData dataWithBytes:sigBuff length:sigLen];
            signature = [self base64forData:sigData];                
        }

        free(sigBuff);            
        RSA_free(rsa);
    }

    return signature;
}

但它会在代码下面崩溃,

FILE *secretFile;
RSA *rsa = NULL;
@try {
    NSData *privateKeyFileData = [keychainItem objectForKey:(__bridge id)kSecAttrLabel];

    secretFile = (__bridge FILE *)(privateKeyFileData);

    PEM_read_RSAPrivateKey(secretFile, &rsa, NULL, NULL);
}

有没有办法解决这个问题,我没有PEM文件,我在Keychain中有私钥。

1 个答案:

答案 0 :(得分:0)

PEM_read_RSAPrivateKey(secretFile, &rsa, NULL, NULL);

尝试:

rsa = PEM_read_RSAPrivateKey(privateKeyFile, NULL, NULL, NULL);
// make a SHA-1 digest of the source string
const char* sourceChars = [source UTF8String];

这不是必需的。 RSA_sign将为您消化数据。