This article is a mirror article of machine translation, please click here to jump to the original article.

View: 10067|Reply: 0

URL secure Base64 encoding, decoding

[Copy link]
Posted on 11/15/2019 2:10:48 PM | | |
Base64 can transcode binary characters into visible characters for HTTP transmission, but Base64 transcoding will generate "+", "/", "=" and other special characters transcoded by the URL, resulting in inconsistency between the two aspects.
We can replace "+", "/", and "=" with characters that do not transcode URLs before sending, and then replace these characters back after receiving the data and then decode them.


PHP:

    /**

     * URL base64 decoding

     * '-' -> '+'

     * '_' -> '/'

     * The remainder of string length %4, complement '='

     * @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 encoded

     * '+' -> '-'

     * '/' -> '_'

     * '=' -> ''

     * @param unknown $string

     */

    function urlsafe_b64encode($string) {

        $data = base64_encode($string);

        $data = str_replace(array('+','/','='),array('-','_',''),$data);

        return $data;

    }




OC:



#pragma - Convert the strings "-", "_" in saveBase64 encoding to "+", "/", and the bit complement with 4 times the length of the string "="

+(NSData*)safeUrlBase64Decode:(NSString*)safeUrlbase64Str

{

    // '-' -> '+'

    // '_' -> '/'

    If it is less than 4 times the length, make up for '='

    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 original: %@", base64Str);

    return [GTMBase64 decodeData:[base64Str dataUsingEncoding:NSUTF8StringEncoding]];

   

}



#pragma - Base64 encoding contains +, /, = these insecure URL strings, so change characters

+(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(@"safeBase64encoded:%@", 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(mod4);

}

return new BASE64Decoder().decodeBuffer(base64Str);

}



For Android, android.utils.Base64 comes with this feature:

Base64.encodeToString(encrypted, Base64.URL_SAFE| Base64.NO_WRAP);

Base64.decode(data, Base64.URL_SAFE);




Previous:Play with an account lockout security strategy
Next:C# connects sqlserver to two types of connection strings for windows and sqlserver authentication
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com