检测NSString是否为Base64

3

最近我尝试创建一个iOS应用程序,能够编码和解码Base64,以及其他“语言”,例如十六进制和二进制。我正在尝试创建一个自动解码器(能够自动检测“语言”)。然而,当我碰到Base64时,自动解码器似乎无法检测到有效的Base64,因为Base64字符串中有换行符。我的Base64检测代码如下:

-(BOOL)isBase64Data:(NSString *)input
{
    if ([input length] % 4 == 0) {
        static NSCharacterSet *invertedBase64CharacterSet = nil;
        if (invertedBase64CharacterSet == nil) {
            invertedBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="]invertedSet];
        }
        return [input rangeOfCharacterFromSet:invertedBase64CharacterSet options:NSLiteralSearch].location == NSNotFound;
    }
    return NO;
}

仅提供额外信息,以下是我检测NSString中“语言”类型的方法。

-(NSInteger)detectType:(BOOL)base64 hexadecimal:(BOOL)hex binary:(BOOL)binary
{
    //Make sure the checking of characters are in this order!
    if (binary) {
        return 0; //Type 0 means binary
    }
    else if (hex) {
        return 1; //Type 1 means hexadecimal
    }
    else if (base64) {
        return 2; //Type 2 means base64
    }
    else {
        return 3; //Type 3 is error/invalid text
    }
}

每当我想要解码时,我只需调用此方法:

-(IBAction)decode:(id)sender
{
    //This is where I detect the type
    NSInteger type = [self detectType:[self isBase64Data:userInput.text] hexadecimal:[self isHexadecimal:userInput.text] binary:[self isBinary:userInput.text]];

    if ([userInput text].length<1) { //First, check if the text view is empty in the first place
        WCAlertView *alert=[[WCAlertView alloc]initWithTitle:@"Error: No input!" message:nil delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
        [alert show];
    }
    else if (type==0) {
        //Initiate the binary converter here
        TextBinViewController *binVC=[[TextBinViewController alloc]init];
        output.text=[binVC binToText:userInput.text];
    }
    else if (type==1) {
        //Initiate the hexadecimal converter here
        TextHexViewController *hexVC=[[TextHexViewController alloc]init];
        output.text=[hexVC hexToText:userInput.text];
    }
    else if (type==2) {
        //Initiate the base64 converter here
        TextBase64ViewController *baseVC=[[TextBase64ViewController alloc]init];
        output.text=[baseVC base64Decode:userInput.text];
    }
    else {
        //If the type matches none of the above, show an error (WCAlertView is a subclass of alertview that allows more styling)
        WCAlertView *alert=[[WCAlertView alloc]initWithTitle:@"Error: Invalid input!" message:nil delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
        [alert show];
        output.text=@"";
    }

    [userInput resignFirstResponder];
}

你能详细说明一下问题吗?具体而言,失败的症状是什么? - jscs
2个回答

5

大家好,我发现我可以从字符串中简单地删除所有换行符。更新后的-isBase64Data方法如下:

-(BOOL)isBase64Data:(NSString *)input
{

    input=[[input componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:@""];
    if ([input length] % 4 == 0) {
        static NSCharacterSet *invertedBase64CharacterSet = nil;
        if (invertedBase64CharacterSet == nil) {
            invertedBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="]invertedSet];
        }
        return [input rangeOfCharacterFromSet:invertedBase64CharacterSet options:NSLiteralSearch].location == NSNotFound;
    }
    return NO;
}

现在Base64字符串的检测已经可以正常工作了。我发现当字符串包含换行符等特殊字符时,[input length] % 4将不会返回0。因此,我的当前解决方案是使用whitespaceAndNewlineCharacterSet简单地修剪掉这些字符。


1
如果你传入一个十六进制字符串(例如0b0c0f00和0a0f0f02),这个函数也会返回YES。有没有什么解决办法? - Mike97

0

在用于创建集合的有效字符字符串中添加一行,并取其反。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接