JavaWeb—Base64编码(转载)
基本概念
一个例子
-
Man is distinguished, not only by his reason, but by this singular passion from
other animals, which is a lust of the mind, that by a perseverance of delight
in the continued and indefatigable generation of knowledge, exceeds the short
vehemence of any carnal pleasure.
-
TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=
转换方法
- M、a和n的ASCII编码分别为01001101、01100001和01101110,合并后得到一个24位的二进制串010011010110000101101110
- 按每6位一组将其分为4组:010011、010110、000101、101110
- 最后按对应关系从字符集中取出4个字符(即T、W、F、u)作为结果(本文后面列出了由MIME定义的字符集)。
补零处理
- 没有字节剩下
- 还剩下1个字节
- 还剩下2个字节


填充
- 没有字符剩下
- 还剩下2个字符
- 还剩下3个字符

.png)
实现(示例)
| 编码 | 字符 | 编码 | 字符 | 编码 | 字符 | 编码 | 字符 | |||
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | A |
16 | Q |
32 | g |
48 | w |
|||
| 1 | B |
17 | R |
33 | h |
49 | x |
|||
| 2 | C |
18 | S |
34 | i |
50 | y |
|||
| 3 | D |
19 | T |
35 | j |
51 | z |
|||
| 4 | E |
20 | U |
36 | k |
52 | 0 |
|||
| 5 | F |
21 | V |
37 | l |
53 | 1 |
|||
| 6 | G |
22 | W |
38 | m |
54 | 2 |
|||
| 7 | H |
23 | X |
39 | n |
55 | 3 |
|||
| 8 | I |
24 | Y |
40 | o |
56 | 4 |
|||
| 9 | J |
25 | Z |
41 | p |
57 | 5 |
|||
| 10 | K |
26 | a |
42 | q |
58 | 6 |
|||
| 11 | L |
27 | b |
43 | r |
59 | 7 |
|||
| 12 | M |
28 | c |
44 | s |
60 | 8 |
|||
| 13 | N |
29 | d |
45 | t |
61 | 9 |
|||
| 14 | O |
30 | e |
46 | u |
62 | + |
|||
| 15 | P |
31 | f |
47 | v |
63 | / |
public String encode(String inputStr, String charset, boolean padding)
throws UnsupportedEncodingException {
String encodeStr = null; byte[] bytes = inputStr.getBytes(charset);
encodeStr = encode(bytes, padding); return encodeStr;
}
encode()方法的核心代码是:
for (int i = 0; i < groups; i++) {
byte_1 = bytes[3*i] & 0xFF;
byte_2 = bytes[3*i+1] & 0xFF;
byte_3 = bytes[3*i+2] & 0xFF;
group_6bit_1 = byte_1 >>> 2;
group_6bit_2 = (byte_1 & 0x03) << 4 | byte_2 >>> 4;
group_6bit_3 = (byte_2 & 0x0F) << 2 | byte_3 >>> 6;
group_6bit_4 = byte_3 & 0x3F;
sb.append(CHARSET[group_6bit_1])
.append(CHARSET[group_6bit_2])
.append(CHARSET[group_6bit_3])
.append(CHARSET[group_6bit_4]);
}
if (tail == 1) {
byte_1 = bytes[bytes.length-1] & 0xFF;
group_6bit_1 = byte_1 >>> 2;
group_6bit_2 = (byte_1 & 0x03) << 4;
sb.append(CHARSET[group_6bit_1])
.append(CHARSET[group_6bit_2]);
if (padding) {
sb.append('=').append('=');
}
} else if (tail == 2) {
byte_1 = bytes[bytes.length-2] & 0xFF;
byte_2 = bytes[bytes.length-1] & 0xFF;
group_6bit_1 = byte_1 >>> 2;
group_6bit_2 = (byte_1 & 0x03) << 4 | byte_2 >>> 4;
group_6bit_3 = (byte_2 & 0x0F) << 2;
sb.append(CHARSET[group_6bit_1])
.append(CHARSET[group_6bit_2])
.append(CHARSET[group_6bit_3]);
if (padding) {
sb.append('=');
}
}
decode过程是类似的,具体请自行查阅完整代码。
package base64; import java.io.UnsupportedEncodingException; /**
* This class provides a simple implementation of Base64 encoding and decoding.
*
* @author QiaoMingkui
*
*/
public class Base64 {
/*
* charset
*/
private static final char[] CHARSET = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
}; /*
* charset used to decode.
*/
private static final int[] DECODE_CHARSET = new int[128];
static {
for (int i=0; i<64; i++) {
DECODE_CHARSET[CHARSET[i]] = i;
}
} /**
* A convenient method for encoding Java String,
* it uses encode(byte[], boolean) to encode byte array.
*
* @param inputStr a string to be encoded.
* @param charset charset name ("GBK" for example) that is used to convert inputStr into byte array.
* @param padding whether using padding characters "="
* @return encoded string
* @throws UnsupportedEncodingException if charset is unsupported
*/
public String encode(String inputStr, String charset, boolean padding)
throws UnsupportedEncodingException {
String encodeStr = null; byte[] bytes = inputStr.getBytes(charset);
encodeStr = encode(bytes, padding); return encodeStr;
} /**
* Using Base64 to encode bytes.
*
* @param bytes byte array to be encoded
* @param padding whether using padding characters "="
* @return encoded string
*/
public String encode(byte[] bytes, boolean padding) {
// 4 6-bit groups
int group_6bit_1,
group_6bit_2,
group_6bit_3,
group_6bit_4; // bytes of a group
int byte_1,
byte_2,
byte_3; // number of 3-byte groups
int groups = bytes.length / 3;
// at last, there might be 0, 1, or 2 byte(s) remained,
// which needs to be encoded individually.
int tail = bytes.length % 3; StringBuilder sb = new StringBuilder(groups * 4 + 4); // handle each 3-byte group
for (int i = 0; i < groups; i++) {
byte_1 = bytes[3*i] & 0xFF;
byte_2 = bytes[3*i+1] & 0xFF;
byte_3 = bytes[3*i+2] & 0xFF; group_6bit_1 = byte_1 >>> 2;
group_6bit_2 = (byte_1 & 0x03) << 4 | byte_2 >>> 4;
group_6bit_3 = (byte_2 & 0x0F) << 2 | byte_3 >>> 6;
group_6bit_4 = byte_3 & 0x3F; sb.append(CHARSET[group_6bit_1])
.append(CHARSET[group_6bit_2])
.append(CHARSET[group_6bit_3])
.append(CHARSET[group_6bit_4]);
} // handle last 1 or 2 byte(s)
if (tail == 1) {
byte_1 = bytes[bytes.length-1] & 0xFF; group_6bit_1 = byte_1 >>> 2;
group_6bit_2 = (byte_1 & 0x03) << 4; sb.append(CHARSET[group_6bit_1])
.append(CHARSET[group_6bit_2]); if (padding) {
sb.append('=').append('=');
}
} else if (tail == 2) {
byte_1 = bytes[bytes.length-2] & 0xFF;
byte_2 = bytes[bytes.length-1] & 0xFF; group_6bit_1 = byte_1 >>> 2;
group_6bit_2 = (byte_1 & 0x03) << 4 | byte_2 >>> 4;
group_6bit_3 = (byte_2 & 0x0F) << 2; sb.append(CHARSET[group_6bit_1])
.append(CHARSET[group_6bit_2])
.append(CHARSET[group_6bit_3]); if (padding) {
sb.append('=');
}
} return sb.toString();
} /**
* Decode a Base64 string to bytes (byte array).
*
* @param code Base64 string to be decoded
* @return byte array
*/
public byte[] decode(String code) {
char[] chars = code.toCharArray(); int group_6bit_1,
group_6bit_2,
group_6bit_3,
group_6bit_4; int byte_1,
byte_2,
byte_3; int len = chars.length;
// ignore last '='s
if (chars[chars.length - 1] == '=') {
len--;
}
if (chars[chars.length - 2] == '=') {
len--;
} int groups = len / 4;
int tail = len % 4; // each group of characters (4 characters) will be converted into 3 bytes,
// and last 2 or 3 characters will be converted into 1 or 2 byte(s).
byte[] bytes = new byte[groups * 3 + (tail > 0 ? tail - 1 : 0)]; int byteIdx = 0; // decode each group
for (int i=0; i<groups; i++) {
group_6bit_1 = DECODE_CHARSET[chars[4*i]];
group_6bit_2 = DECODE_CHARSET[chars[4*i + 1]];
group_6bit_3 = DECODE_CHARSET[chars[4*i + 2]];
group_6bit_4 = DECODE_CHARSET[chars[4*i + 3]]; byte_1 = group_6bit_1 << 2 | group_6bit_2 >>> 4;
byte_2 = (group_6bit_2 & 0x0F) << 4 | group_6bit_3 >>> 2;
byte_3 = (group_6bit_3 & 0x03) << 6 | group_6bit_4; bytes[byteIdx++] = (byte) byte_1;
bytes[byteIdx++] = (byte) byte_2;
bytes[byteIdx++] = (byte) byte_3;
} // decode last 2 or 3 characters
if (tail == 2) {
group_6bit_1 = DECODE_CHARSET[chars[len - 2]];
group_6bit_2 = DECODE_CHARSET[chars[len - 1]]; byte_1 = group_6bit_1 << 2 | group_6bit_2 >>> 4;
bytes[byteIdx] = (byte) byte_1;
} else if (tail == 3) {
group_6bit_1 = DECODE_CHARSET[chars[len - 3]];
group_6bit_2 = DECODE_CHARSET[chars[len - 2]];
group_6bit_3 = DECODE_CHARSET[chars[len - 1]]; byte_1 = group_6bit_1 << 2 | group_6bit_2 >>> 4;
byte_2 = (group_6bit_2 & 0x0F) << 4 | group_6bit_3 >>> 2; bytes[byteIdx++] = (byte) byte_1;
bytes[byteIdx] = (byte) byte_2;
} return bytes;
} /**
* Test.
* @param args
*/
public static void main(String[] args) {
Base64 base64 = new Base64();
String str = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
System.out.println(str);
try {
String encodeStr = base64.encode(str, "GBK", false);
System.out.println(encodeStr);
byte[] decodeBytes = base64.decode(encodeStr);
String decodeStr = new String(decodeBytes, "GBK");
System.out.println(decodeStr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
工具类
可以使用Java现有的工具类进行编码解码,这样可以简化代码。
BASE64Encoder encoder = new BASE64Encoder();
BASE64Decoder decoder = new BASE64Decoder();
String str1 = encoder.encode("111".getBytes());
String str2 = encoder.encode("222".getBytes());
System.out.println(str1);
System.out.println(new String(decoder.decodeBuffer(str1)));
System.out.println(str2);
System.out.println(new String(decoder.decodeBuffer(str2)));
运行结果:
MTEx MjIy
转载自:
JavaWeb—Base64编码(转载)的更多相关文章
- NET MVC全局异常处理(一) 【转载】网站遭遇DDoS攻击怎么办 使用 HttpRequester 更方便的发起 HTTP 请求 C#文件流。 Url的Base64编码以及解码 C#计算字符串长度,汉字算两个字符 2019周笔记(2.18-2.23) Mysql语句中当前时间不能直接使用C#中的Date.Now传输 Mysql中Count函数的正确使用
NET MVC全局异常处理(一) 目录 .NET MVC全局异常处理 IIS配置 静态错误页配置 .NET错误页配置 程序设置 全局异常配置 .NET MVC全局异常处理 一直知道有.NET有相关 ...
- (转载)javascript将base64编码的图片数据转换为file并提交
/** * @param base64Codes * 图片的base64编码 */ function sumitImageFile(base64Codes){ var form=document.fo ...
- 一篇文章彻底弄懂Base64编码原理(转载)
在互联网中的每一刻,你可能都在享受着Base64带来的便捷,但对于Base64的基础原理又了解多少?今天这篇博文带领大家了解一下Base64的底层实现. Base64的由来 目前Base64已经成为网 ...
- Base64编码
Base64编码 写在前面 今天在做一个Android app时遇到了一个问题:Android端采用ASE对称加密的数据在JavaWeb(jre1.8.0_7)后台解密时,居然解密失败了!经过测试后发 ...
- 浅析用Base64编码的图片优化网页加载速度
想必大家都知道网页加载的过程,从开始请求,到加载页面,开始解析和显示网页,遇到图片就再次向服务器发送请求,加载图片.如果图片很多的话,就会产生大量的http请求,从而影响页面的加载速度.所以现在有一种 ...
- [编解码] 关于base64编码的原理及实现
转载自: http://www.cnblogs.com/hongru/archive/2012/01/14/2321397.html [Base64]-base64的编码都是按字符串长度,以每3个8b ...
- Base64编码和解码算法
Base64么新鲜的算法了.只是假设你没从事过页面开发(或者说动态页面开发.尤其是邮箱服务),你都不怎么了解过,仅仅是听起来非常熟悉. 对于黑客来说,Base64与MD5算法有着相同的位置.由于电子邮 ...
- java使用Base64编码和解码的图像文件
1.编码和解码下面的代码示例看: import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import j ...
- Base64编码 概念和用途
Base64概念 什么是Base64? 依照RFC2045的定义,Base64被定义为:Base64内容传送编码被设计用来把随意序列的8位字节描写叙述为一种不易被人直接识别的形式.(The Base6 ...
随机推荐
- 缓存技术PK:选择Memcached还是Redis(转)
[IT168 技术]要Memcached还是要Redis?在构建一款现代且由数据库驱动的Web应用程序并希望使其拥有更为出色的性能表现时,这个问题总会时不时出现.并给每一位开发人员带来困扰.在考虑对应 ...
- EMC、Pure和NetApp推新品,NAS闪存场景在哪里
Hardy 架构师技术联盟 All Flash/SSD存储的趋势势不可挡,未来在NAS服务上也是如此,眼下已经有非常多家初创厂商支持全SSD的NAS存储服务,包含EMC Isilion也推出了全闪存节 ...
- js获取字符串的实际长度并截断实际长度
在项目中有这样一个需求,就是一个很长的字符串,需要截断成几组字符串,而这几组字符串里既包含汉字,又包含字母,下面提供了几种方法 1,获取字符串的长度 function getstrlength(str ...
- Libgdx window add alpha action change the background actor alpha
现象: Stage中包括一个Window,一个Actor,Window中加入alpha action后,Actor也随之消失:Actor加入alpha action后,不起作用. 解决: 重写draw ...
- MS SQL Server2012中的EOMONTH函数
MS SQL Server2012中的EOMONTH函数 这个函数是获取一个指定日期所在月份最后一天的日期.可以得到某一个月月份的最后一天 如: declare @orderdate date=' ...
- java----代理机制或动态类的生成
在学习Spring的时候,我们知道Spring主要有两大思想,一个是IoC,另一个就是AOP,对于IoC,依赖注入就不用多说了,而对于Spring的核心AOP来说,我们不但要知道怎么通过AOP来满足的 ...
- 嵌入式开发之gb281818
http://www.cnblogs.com/snake-hand/p/3157176.html http://blog.csdn.net/voipmaker/article/category/140 ...
- 【BZOJ】2440: [中山市选2011]完全平方数(莫比乌斯+容斥原理+二分)
http://www.lydsy.com/JudgeOnline/problem.php?id=2440 我觉得网上很多题解都没说清楚...(还是我太弱了? 首先我们可以将问题转换为判定性问题,即给出 ...
- 比较难的sql面试题--记录下来晚上做
一组通话记录(总共500万条):ID 主叫号码 被叫号码 通话起始时间 通话结束时间 通话时长1 98290000 0215466546656 2007-02-01 09:4 ...
- 漫游Kafka设计篇之性能优化(7)
Kafka在提高效率方面做了很大努力.Kafka的一个主要使用场景是处理网站活动日志,吞吐量是非常大的,每个页面都会产生好多次写操作.读方面,假设每个消息只被消费一次,读的量的也是很大的,Kafka也 ...