简体   繁体   中英

ObjC Base64 Decode returns nil

I'm trying to decode a Base64 encoded string and it always returns nil when using the UTF8 encoding. I've tried changing the character encoding to several different options and can't get it to return the same value as when I put it into a website like: https://www.base64decode.org/

The string I'm trying to decode is "qc6mSDfm1pizbp0szoQmoQ=="

Here is the code I'm using to test this

// DataHelper.m

+(NSString*) base64Encode:(NSString*) string andEncoding:(NSStringEncoding) encoding {
  NSData *plainData = [string dataUsingEncoding:encoding];
  return [plainData base64EncodedStringWithOptions:kNilOptions];
}

+(NSString*) base64Decode:(NSString*) string andEncoding:(NSStringEncoding) encoding {
  NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions];
  NSString *str = [[NSString alloc] initWithData:decodedData encoding:encoding];
  return str;
} 


// TestCases.m
-(void) testDecodeEncodeNonce {
  NSString *nonce = @"qc6mSDfm1pizbp0szoQmoQ==";
  NSString *decoded = [DataHelper base64Decode:nonce andEncoding:NSUTF8StringEncoding];
  NSString *encoded = [DataHelper base64Encode:decoded andEncoding:NSUTF8StringEncoding];
  XCTAssertEqualObjects(nonce, encoded);
}

Your code works fine (try this: Y2hlY2sgaXQgb3V0IG15IGVuY29kZWQgc3RyaW5nLg== ). Your problem is not the code, but the characters you encoded. Somehow you have encoded special characters that initWithBase64EncodedString is not able to decode in NSUTF8StringEncoding use NSASCIIStringEncoding instead of it.

I hope this can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM