android Base64

1.简介

  Base64编码是将二进制数据转成文本数据的编码方式,不是加密算法。对于非二进制数据,是先将其转换成二进制形式,然后每连续6比特(2的6次方=64)计算其十进制值,根据该值在A--Z,a--z,0--9,+,/ 这64个字符中找到对应的字符,最终得到一个文本字符串。

  android有base64工具类。 android.util.Base64;

  java8也内置了base64类。但是在android上使用这个需要api 26.

2.编码规则

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

3.Base64编码表

索引对应字符索引对应字符索引对应字符索引对应字符
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v    
14 O 31 f 48 w    
15 P 32 g 49 x    
16 Q 33 h 50 y

4.简单示例

4.1 代码

 1     @Test
 2     public void base64(){
 3 
 4         String data = "test";
 5         String b64 = encodeBase64(data.getBytes());
 6 
 7         byte result [] = decodeBase64(b64);
 8 
 9         String str = new String(result);
10 
11         boolean eqs = str.equals(data);
12         assertTrue(eqs);
13     }
14 
15 
16     String encodeBase64(byte[] data) {
17         String b64 = Base64.encodeToString(data, Base64.DEFAULT);
18         Log.e("MainActivity", "encodeBase64: result = " + b64);
19         return b64;
20     }
21 
22     byte[] decodeBase64(String b64) {
23 
24         byte[] ret = Base64.decode(b64, Base64.DEFAULT);
25         Log.e("MainActivity", "encodeBase64: result = " + new String(ret));
26 
27         return ret;
28     }

4.2 参数Flags

无论是编码还是解码都会有一个参数Flags,Android提供了以下几种:

CRLF Encoder flag bit to indicate lines should be terminated with a CRLF pair instead of just an LF.
DEFAULT Default values for encoder/decoder flags.
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.
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).
URL_SAFE

Encoder/decoder flag bit to indicate using the "URL and filename safe" variant

ofBase64 (see RFC 3548 section 4) where - and _ are used in place of + and /.

posted @ 2016-10-21 15:38  f9q  阅读(623)  评论(0编辑  收藏  举报