NO_WRAP:不换行
NO_PADDING:"="号补齐去除,base64会对字符进行串长度余4的"="的补位,需去除"="
URL_SAFE:安全的URL编码,base64转码过程中会生成“+”,“”,“=”这些会被URL进行转码的特殊字符,导致前后台数据不同,所以需要将这些字符替代为URL不会进行转码的字符,保证数据同步;"-" -> "+","_" -> "/"
// base64 url 编码
- (NSString *)base64UrlEncoder:(NSString *)str {
NSData *data = [[str dataUsingEncoding:NSUTF8StringEncoding] base64EncodedDataWithOptions:0];
NSMutableString *base64Str = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"=" withString:@""];
return base64Str;
}
// base64 url 解码
- (NSString *)base64UrlDecoder:(NSString *)str {
NSMutableString *base64Str = [[NSMutableString alloc] initWithString:str];
base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
NSInteger mod4 = base64Str.length % 4;
if (mod4) {
[base64Str appendString:[@"====" substringToIndex:(4 - mod4)]];
}
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64Str options:0];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
使用如下:
NSString *str = @"一串base64编码的字符串";
NSString *urlEncoder = [self base64UrlEncoder:str];
NSLog(@"编码:%@",urlEncoder);
NSString *urlDecoder = [self base64UrlDecoder:urlEncoder];
NSLog(@"解码:%@",urlDecoder);
网友评论