Base64可以将二进制转码成可见字符方便进行http传输,但是base64转码时会生成“+”,“/”,“=”这些被URL进行转码的特殊字符,导致两方面数据不一致。
我们可以在发送前将“+”,“/”,“=”替换成URL不会转码的字符,接收到数据后,再将这些字符替换回去,再进行解码。
PHP:
/**
* URL base64解码
* ‘-‘ -> ‘+‘
* ‘_‘ -> ‘/‘
* 字符串长度%4的余数,补‘=‘
* @param unknown $string
*/
public static function urlsafe_b64decode($string) {
$data = str_replace(array(‘-‘,‘_‘),array(‘+‘,‘/‘),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr(‘====‘, $mod4);
}
return base64_decode($data);
}
/**
* URL base64编码
* ‘+‘ -> ‘-‘
* ‘/‘ -> ‘_‘
* ‘=‘ -> ‘‘
* @param unknown $string
*/
function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array(‘+‘,‘/‘,‘=‘),array(‘-‘,‘_‘,‘‘),$data);
return $data;
}
OC:
#pragma - 将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:mod4]];
NSLog(@"Base64原文:%@", base64Str);
return [GTMBase64 decodeData:[base64Str dataUsingEncoding:NSUTF8StringEncoding]];
}
#pragma - 因为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;
}
Java:
public static String safeUrlBase64Encode(byte[] data){
String encodeBase64 = new BASE64Encoder().encode(data);
String safeBase64Str = encodeBase64.replace(‘+‘, ‘-‘);
safeBase64Str = safeBase64Str.replace(‘/‘, ‘_‘);
safeBase64Str = safeBase64Str.replaceAll("=", "");
return safeBase64Str;
}
public static byte[] safeUrlBase64Decode(final String safeBase64Str){
String base64Str = safeBase64Str.replace(‘-‘, ‘+‘);
base64Str = base64Str.replace(‘_‘, ‘/‘);
int mod4 = base64Str.length()%4;
if(mod4 > 0){
base64Str = base64Str + "====".substring(0, mod4);
}
return new BASE64Decoder().decodeBuffer(base64Str);
}