Base64编码

简述

Base64常用于在通常处理文本数据的场合,表示、传输、存储一些二进制数据。

flag meaning
DEFAULT Encoder/Decoder flag,RFC 2045
NO_PADDING Encoder flag bit to omit the padding '=' characters at the end of the output (if any).
NO_WRAP Encoder flag bit to omit all line terminators(i.e., the output will be on one long line).
CRLF Encoder flag bit to indicate lines should be terminated with a CRLF pair instead of just an LF. Has no effect if NO_WRAP is specified as well.
URL_SAFE Encoder/decoder flag bit to indicate using the "URL and filename safe" variant of Base64 (see RFC 3548 section 4) where - and _ are used in place of + and*.
NO_CLOSE Flag to pass to Base64OutputStream to indicate that it should not close the output stream it is wrapping when it itself is closed.

Base64编码提供以下几种flag:

flag meaning
DEFAULT Encoder/Decoder flag,RFC 2045
NO_PADDING Encoder flag bit to omit the padding '=' characters at the end of the output (if any).
NO_WRAP Encoder flag bit to omit all line terminators(i.e., the output will be on one long line).
CRLF Encoder flag bit to indicate lines should be terminated with a CRLF pair instead of just an LF. Has no effect if NO_WRAP is specified as well.
URL_SAFE Encoder/decoder flag bit to indicate using the "URL and filename safe" variant of Base64 (see RFC 3548 section 4) where - and _ are used in place of + and*.
NO_CLOSE Flag to pass to Base64OutputStream to indicate that it should not close the output stream it is wrapping when it itself is closed.

在Base64中的可打印字符包括字母A-Z、a-z、数字0-9,这样共有62个字符,最后两个可打印符号在不同的系统中而不同。

转换的时候,将三个byte的数据,先后放入一个24bit的缓冲区中,先来的byte占高位。数据不足3byte的话,于缓冲器中剩下的bit用0补足。然后,每次取出6(因为26=64)个bit,按照其值选择ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/中的字符作为编码后的输出。不断进行,直到全部输入数据转换完成。

当原数据长度不是3的整数倍时, 如果最后剩下一个输入数据,在编码结果后加2个“=”;如果最后剩下两个输入数据,编码结果后加1个“=”;如果没有剩下任何数据,就什么都不要加


base64.png

因为URL编码器会把标准Base64中的“/”和“+”字符变为形如“%XX”的形式,而这些“%”号在存入数据库时还需要再进行转换,因为ANSI SQL中已将“%”号用作通配符。

为解决此问题,可采用一种用于URL的改进Base64编码,它不在末尾填充'='号,并将标准Base64中的“+”和“/”分别改成了“-”和“_”,这样就免去了在URL编解码和数据库存储时所要作的转换,避免了编码信息长度在此过程中的增加,并统一了数据库、表单等处对象标识符的格式。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Base64编码由来 Base64最早是用来解决电子邮件的传输问题。 传统的电子邮件是1982年定下技术规范的,详...
    Ashton阅读 2,627评论 0 6
  • 前言:前面学习总结了平时开发中遇见的各种数据加密方式,最终都会对加密后的二进制数据进行Base64编码,起到一种二...
    博格体阅读 1,257评论 0 1
  • 最近学Python的时候遇到了编码问题,顺带了解了一下base64编码,首先阅读了咱CSDN上的一篇文章Base6...
    连命都给你了阅读 913评论 0 3
  • 1、Base64编码原理 下图为Base64编码索引表: 字符选用了"A-Z、a-z、0-9、+、/" 64个可打...
    M_JCs阅读 1,816评论 1 9
  • 一天一天的变冷了 早上把自己在被窝缩成一小团 昨晚说好的早餐就这么泡汤了 学校通知 网上选课于上午十点开始 根据以...
    奈良艾木阅读 228评论 0 0