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编码表

索引对应字符索引对应字符索引对应字符索引对应字符
0A17R34i51z
1B18S35j520
2C19T36k531
3D20U37l542
4E21V38m553
5F22W39n564
6G23X40o575
7H24Y41p586
8I25Z42q597
9J26a43r608
10K27b44s619
11L28c45t62+
12M29d46u63/
13N30e47v  
14O31f48w  
15P32g49x  
16Q33h50y

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提供了以下几种:

CRLFEncoder flag bit to indicate lines should be terminated with a CRLF pair instead of just an LF.
DEFAULTDefault values for encoder/decoder flags.
NO_CLOSEFlag to pass to Base64OutputStream to indicate that it should not close the output stream it is wrapping when it itself is closed.
NO_PADDINGEncoder flag bit to omit the padding '=' characters at the end of the output (if any).
NO_WRAPEncoder 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 /.

转载于:https://www.cnblogs.com/sjjg/p/5984840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值