在Objective C中对字符串进行编码和解码

时间:2012-12-21 04:53:04

标签: objective-c encryption encoding

我使用下面的代码对目标C上的字符串进行编码和解码。编码很好,我调试并看到它在输入为@“1”时抛出一个哈希字符串。但是当我尝试解码这个哈希字符串时,它返回nil。

请帮帮我。

+(NSString *)encrypt: (NSString*) input
{

    //Base64 Encoding

    char base64Result[32];
    size_t theResultLength = 32;
    Base64EncodeData(input, 20, base64Result, &theResultLength);
    NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];
    NSString *base64EncodedResult = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

    NSString* decryptedString = [self decrypt:base64EncodedResult];
    return [base64EncodedResult autorelease];
}
+ (NSString *) decrypt:(NSString*) input{

        Byte inputData[[input lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];//prepare a Byte[]
    [[input dataUsingEncoding:NSUTF8StringEncoding] getBytes:inputData];//get the pointer of the data
    size_t inputDataSize = (size_t)[input length];
    size_t outputDataSize = EstimateBas64DecodedDataSize(inputDataSize);//calculate the decoded data size
    Byte outputData[outputDataSize];//prepare a Byte[] for the decoded data
    Base64DecodeData(inputData, inputDataSize, outputData, &outputDataSize);//decode the data
    NSData *theData = [[NSData alloc] initWithBytes:outputData length:outputDataSize];//create a NSData object from the decoded data
    NSString *result = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
    return [result autorelease];
}

1 个答案:

答案 0 :(得分:0)

在编码方法中,您必须将输入字符串转换为字节缓冲区并将其提供给Base64EncodeData

NSData *inputData = [input dataUsingEncoding:NSUTF8StringEncoding];
Base64EncodeData([inputData bytes], [inputData length], base64Result, &theResultLength, NO);

(编码方法中的NSString *input参数指向Objective-C结构,而不是C字符串。因此您的编码方法似乎可以工作。它编码某事,但不是输入字符串。然后解码方法失败

NSString *result = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

因为解码数据不包含有效的UTF-8。)