29,028
社区成员
发帖
与我相关
我的任务
分享
//.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;
}