一. iOS Base64URL编码:
java中,在进行base64编码时会看到类似如下代码:
String result = Base64.encodeToString(bytedata, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
其中参数的含义是:
URL_SAFE:安全的URL编码,base64转码过程中会生成“+”,“/”,“=”这些会被URL进行转码的特殊字符,导致前后台数据不同,所以需要将这些字符替代为URL不会进行转码的字符,保证数据同步;
"-" -> "+"
"_" -> "/"
NO_WRAP:不换行
NO_PADDING:"="号补齐去除,base64会对字符进行串长度余4的"="的补位,需去除"="。
这些功能都是android.utils.Base64中自带的
在iOS中没有,所以我们只能自己动手了~
Swift代码:
//MARK: Data转Base64URL加密
internal class func convertByte(bytedata:Data?) -> String {
guard let bytedata = bytedata else {
return ""
}
// data数据进行base64加密
guard let result = bytedata.base64EncodedString() else {
return ""
}
// %替换为_
let result4 = result.replacingOccurrences(of: "%", with: "_")
// =替换为空
let result1 = result4.replacingOccurrences(of: "=", with: "")
// +替换为—
let result2 = result1.replacingOccurrences(of: "+", with: "-")
// /替换为_
let result3 = result2.replacingOccurrences(of: "/", with: "_")
return result3
}
//MARK: 后台反回的base64字符串转为data
internal class func convertBase64URL(base64:String?) -> Data? {
guard let base64 = base64 else {
return nil
}
// -替换为+
let base64Str = base64.replacingOccurrences(of: "-", with: "+")
// _替换为/
let base64Str2 = base64Str.replacingOccurrences(of: "_", with: "/")
var base64Str3 = ""
// =号补全
let mod4 = base64Str.count % 4
if mod4 > 0 {
let appStr = ("====" as NSString).substring(to: (4 - mod4))
base64Str3 = base64Str2 + appStr
}
// base64Str转data并进行Base64Decoding
return Data(base64Encoded: base64Str3, options: Data.Base64DecodingOptions.init(rawValue: 0))
}
OC:
//MARK: 将saveBase64编码中的"-","_"字符串转换成"+","/",字符串长度余4倍的位补"="
+(NSData*)safeUrlBase64Decode:(NSString*)safeUrlbase64Str
{
// '-' -> '+'
// '_' -> '/'
// 不足4倍长度,补'='
NSMutableString * base64Str = [[NSMutableString alloc]initWithString:safeUrlbase64Str];
base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
NSInteger mod4 = base64Str.length % 4;
if(mod4 > 0)
[base64Str appendString:[@"====" substringToIndex:(4-mod4)]];
NSLog(@"Base64原文:%@", base64Str);
return [GTMBase64 decodeData:[base64Str dataUsingEncoding:NSUTF8StringEncoding]];
}
//MARK: 因为Base64编码中包含有+,/,=这些不安全的URL字符串,所以要进行换字符
+(NSString*)safeUrlBase64Encode:(NSData*)data
{
// '+' -> '-'
// '/' -> '_'
// '=' -> ''
NSString * base64Str = [GTMBase64 stringByEncodingData:data];
NSMutableString * safeBase64Str = [[NSMutableString alloc]initWithString:base64Str];
safeBase64Str = (NSMutableString * )[safeBase64Str stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
safeBase64Str = (NSMutableString * )[safeBase64Str stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
safeBase64Str = (NSMutableString * )[safeBase64Str stringByReplacingOccurrencesOfString:@"=" withString:@""];
NSLog(@"safeBase64编码:%@", safeBase64Str);
return safeBase64Str;
}