background image

29

                            CFRelease(trust);  

30

                        }  

31

                    }  

32

                }  

33

            }  

34

        }  

35

    }  

36

    

return

 status;  

37

}  

5. 用公钥对数据加密。

38

//加密

  

39

- (NSMutableData *)encryptWithPublicKey:(NSData *)plainData {  

40

    

// 分配内存块,用于存放加密后的数据段

  

41

    

size_t

 cipherBufferSize = SecKeyGetBlockSize(_publicKey);  

42

    uint8_t *cipherBuffer = malloc(cipherBufferSize * 

sizeof

(uint8_t));  

43

    

double

 totalLength = [plainData length];  

44

    

size_t

 blockSize = cipherBufferSize - 12;  

45

    

size_t

 blockCount = (

size_t

)ceil(totalLength / blockSize);  

46

    NSMutableData *encryptedData = [NSMutableData data];  

47

    

// 分段加密

  

48

    

for

 (

int

 i = 0; i < blockCount; i++) {  

49

        NSUInteger loc = i * blockSize;  

50

        

// 数据段的实际大小。最后一段可能比 blockSize 小。

  

51

        

int

 dataSegmentRealSize = MIN(blockSize, [plainData length] - loc);  

52

        

// 截取需要加密的数据段

  

53

        NSData *dataSegment = [plainData subdataWithRange:NSMakeRange(loc, 

dataSegmentRealSize)];  

54

        OSStatus status = SecKeyEncrypt(_publicKey, kSecPaddingPKCS1, (

const

 uint8_t 

*)[dataSegment bytes], dataSegmentRealSize, cipherBuffer, &cipherBufferSize);  

55

        

if

 (status == errSecSuccess) {  

56

            NSData *encryptedDataSegment = [[NSData alloc] initWithBytes:(

const

 

void 

*)cipherBuffer length:cipherBufferSize];  

57

            

// 追加加密后的数据段

  

58

            [encryptedData appendData:encryptedDataSegment];  

59

            [encryptedDataSegment release];  

60

        } 

else

 {  

61

            

if

 (cipherBuffer) {  

62

                free(cipherBuffer);  

63

            }