分享

Base64

 黄金屋1 2019-05-30

一:算法由来

Base64最早应用于解决电子邮件传输的问题。在早期,由于“历史问题”,电子邮件只允许ASCII码字符。如果要传输一封带有非ASCII码字符的电子邮件(例如附件),当它通过有“历史问题”的网关时就可能出现问题(网关可能会对非ASCII码字符的二进制位作调整,即将非ASCII码的8位二进制码最高位置为0)。此时用户收到的邮件会是一封纯粹的乱码邮件,由于这个原因产生了base64算法。Base64是一种编码方式,而不是一种加密方式

电子邮件的附件一般也作Base64编码的,因为一个附件数据往往是有不可见字符的。
对证书来说,特别是根证书,一般都是作Base64编码的,因为它要在网上被许多人下载。

  • 标准Base64只有64个字符(英文大小写、数字和+、/)以及用作后缀等号
  • base64是把3个字节变成4个可打印字符,所以base64编码后的字符串一定能被4整除(不算用作后缀的等号)
  • 等号一定用作后缀,且数目一定是0个、1个或2个。这是因为如果原文长度不能被3整除,base64要在后面添加\0凑齐3n位。为了正确还原,添加了几个\0就加上几个等号。显然添加等号的数目只能是0、1或2;

Base64是一种任意二进制到文本字符串的编码方法(二进制=》ASCII),Base64适用于小段内容的编码,常用于在URL、Cookie、网页中传输少量二进制数据、数字证书签名、密钥。

“123456”对应的二进制位 00110001 00110010 00110011 00110100 00110101 00110110, 我们取6个比特为一组结果为

  • 001100
  • 010011
  • 001000
  • 110011
  • 001101
  • 000011
  • 010100
  • 110110

对应的base64为:MTIzNDU2

由于标准的Base64编码后可能出现字符+和/,在URL中就不能直接作为参数,所以又有一种”url safe”的base64编码,其实就是把字符+和/分别变成-和_:
由于=字符也可能出现在Base64编码中,但=用在URL、Cookie里面会造成歧义,所以,很多Base64编码后会把=去掉或者替换成.

二:Base64Util

public class Base64Util { public static String encode(String src){ BASE64Encoder encoder = new BASE64Encoder(); String encode = encoder.encode(src.getBytes()); return encode; } public static String decode(String encode) throws Exception { BASE64Decoder decoder = new BASE64Decoder(); byte[] bytes = decoder.decodeBuffer(encode); return new String(bytes); } /** * 将base64种的敏感字符+,/,=转化为_,-,. 以及base64会在编码串中产生换行符 * @param source * @return */ public static String urlSafeEncode(byte[] source) { BASE64Encoder encoder = new BASE64Encoder(); String str = encoder.encode(source); str = str.replaceAll('\\+', '_'); str = str.replaceAll('/', '-'); str = str.replaceAll('=', '.'); str = str.replaceAll('\\s', ''); return str; } /** * urlSafeEncode逆过程 * @param str * @return * @throws IOException */ public static byte[] urlSafeDecode(String str) throws IOException { if (str == null) { return null; } str = str.replaceAll('_', '+'); str = str.replaceAll('-', '/'); str = str.replaceAll('\\.', '='); BASE64Decoder decoder = new BASE64Decoder(); byte[] bytes = decoder.decodeBuffer(str); return bytes; } public static void main(String[] args) throws Exception{ String encode = Base64Util.encode('123456'); String decode = Base64Util.decode(encode); System.out.println(encode); System.out.println(decode); }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多