Skip to content

URL的Base64编码代码-有无意义的逻辑处理 #110

@henrybit

Description

@henrybit

代码在encodeBase64Ex中实际上最终调用了jdk提供的Base64编码,那么URL版本的Base64编码与传统Base64编码区别在哪?仅仅是62,63位的字符由+变成-,由/变成_,详情参看http://www.ietf.org/rfc/rfc4648.txt。

  public static byte[] urlsafeEncodeBytes(byte[] src) {
    if (src.length % 3 == 0) {
        return encodeBase64Ex(src);
    }

    byte[] b = encodeBase64Ex(src);
    if (b.length % 4 == 0) {
        return b;
    }

    int pad = 4 - b.length % 4;
    byte[] b2 = new byte[b.length + pad];
    System.arraycopy(b, 0, b2, 0, b.length);
    b2[b.length] = '=';
    if (pad > 1) {
        b2[b.length + 1] = '=';
    }
    return b2;
}

这段代码中的
int pad = 4 - b.length % 4;
byte[] b2 = new byte[b.length + pad];
System.arraycopy(b, 0, b2, 0, b.length);
b2[b.length] = '=';
if (pad > 1) {
b2[b.length + 1] = '=';
}
这段逻辑什么时候能用上,实在无法理解,传统Base64算法里,会自动对二进制位数不足进行补齐,满足6位编码的需要,所以这段代码应该是多余的,除非传统的Base64源码算法不正确。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions