使用RSA加密,_rsaPublic = PEM_read_bio_RSA_PUBKEY(bpubkey, NULL, NULL, NULL),开始_rsaPublic取值正常,但是经过多次网络请求,进行加密,_rsaPublic取值为NULL。为什么会是NULL呢??

解决方案 »

  1.   

    我用的这种方法来加密的,不知道对你是否有用//.h
    +(NSString *)RSAEncrypotoTheData:(NSString *)plainText publicKey:(NSString *) key;//.m
    +(NSString *)RSAEncrypotoTheData:(NSString *)plainText publicKey:(NSString *) key
    {
        
        SecKeyRef publicKey=[self addPublicKey:key];
        size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
        uint8_t *cipherBuffer = NULL;
        
        cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
        memset((void *)cipherBuffer, 0*0, cipherBufferSize);
        
        NSData *plainTextBytes = [plainText dataUsingEncoding:NSUTF8StringEncoding];
        size_t blockSize = cipherBufferSize-11;  // 这个地方比较重要是加密问组长度
        int numBlock = (int)ceil([plainTextBytes length] / (double)blockSize);
        NSMutableData *encryptedData = [[NSMutableData alloc] init];
        for (int i=0; i<numBlock; i++) {
            long bufferSize = MIN(blockSize,[plainTextBytes length]-i*blockSize);
            NSData *buffer = [plainTextBytes subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
            OSStatus status = SecKeyEncrypt(publicKey,
                                            kSecPaddingPKCS1,
                                            (const uint8_t *)[buffer bytes],
                                            [buffer length],
                                            cipherBuffer,
                                            &cipherBufferSize);
            if (status == noErr)
            {
                NSData *encryptedBytes = [[NSData alloc]
                                           initWithBytes:(const void *)cipherBuffer
                                           length:cipherBufferSize];
                [encryptedData appendData:encryptedBytes];
            }
            else
            {
                return nil;
            }
        }
        if (cipherBuffer)
        {
            free(cipherBuffer);
        }
        NSString *encrypotoResult=[NSString stringWithFormat:@"%@",[encryptedData base64EncodedStringWithOptions:0]];
        return encrypotoResult;
    }