美文网首页
iOS URL Safe类型的 Base64解码

iOS URL Safe类型的 Base64解码

作者: 那月无痕 | 来源:发表于2024-02-26 16:49 被阅读0次

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);

相关文章

网友评论

      本文标题:iOS URL Safe类型的 Base64解码

      本文链接:https://www.haomeiwen.com/subject/neizadtx.html