iPhone RSA文本编码+解码

时间:2011-05-18 19:43:18

标签: iphone encoding rsa decoding

会发生什么。

用户将加密的消息发送到服务器。其他用户从服务器检索消息然后将其描述。反之亦然。

我有一些unicode编码的文本。文本应使用RSA encription作为JSON的一部分发送到服务器(如{“message”:“”})

要创建文本,我创建的函数有NSString作为输入参数,NSString作为输出参数。 Decript函数具有相同的格式。

我的问题:由于解码功能而导致的文本与编码的文本不同。

-(NSString*) encryptText:(NSString*) text {

OSStatus status = noErr;

//text = @"ネイティブ英会話";
text = @"test text";

int length = [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
const char *cText = [text cStringUsingEncoding:NSUTF8StringEncoding];

size_t cipherBufferSize = BUFFER_SIZE;
if (cipherBufferSize < length) {
    cipherBufferSize = length;
}

char *cipherBuffer = malloc(cipherBufferSize);
memset(cipherBuffer, 0, cipherBufferSize);

NSLog(@"BEFORE SIPHER TEXT = %s", cText);

status = SecKeyEncrypt(_publicKey,
                       kSecPaddingNone,
                       (unsigned char*) cText,
                       length,
                       (unsigned char*) cipherBuffer,
                       &cipherBufferSize
                       );

NSLog(@"CIPHER TEXT = %s", cipherBuffer);

NSString *result = nil;

if (status == 0) {
    result = [NSString stringWithFormat:@"%s", cipherBuffer];
}

free(cipherBuffer);

return result;
}


-(NSString*) decriptText:(NSString*) encriptedText {

OSStatus status = noErr;

const char *cText = [encriptedText cStringUsingEncoding:NSUTF8StringEncoding];

int length = [encriptedText lengthOfBytesUsingEncoding:NSUTF8StringEncoding];

size_t plainBufferSize = BUFFER_SIZE;
if (plainBufferSize < length) {
    plainBufferSize = length;
}

char *plainBuffer = malloc(plainBufferSize);
memset(plainBuffer, 0, plainBufferSize);

NSLog(@"BEFORE DECIPHER TEXT = %s", cText);

status = SecKeyDecrypt(_privateKey,
                       kSecPaddingNone,
                       (unsigned char *) cText,
                       length,
                       (unsigned char *) plainBuffer,
                       &plainBufferSize
                       );

NSLog(@"AFTER DESIPHER BUFFER = %s status = %d", plainBuffer, status);

NSString *decriptedText = nil;

if (status == 0) {
    decriptedText = [NSString stringWithUTF8String:plainBuffer]; 
}

free(plainBuffer);

return decriptedText;
 }

0 个答案:

没有答案