1+ package com.wrbug.developerhelper.commonutil
2+
3+ object Base64 {
4+
5+ private val alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
6+ .toCharArray()
7+ private val codes = ByteArray (256 )
8+ /* 将原始数据编码为base64编码
9+ */
10+ fun encodeAsString (data : ByteArray ): String {
11+ return String (encode(data))
12+ }
13+
14+ fun encode (data : ByteArray ): CharArray {
15+ val out = CharArray ((data.size + 2 ) / 3 * 4 )
16+ var i = 0
17+ var index = 0
18+ while (i < data.size) {
19+ var quad = false
20+ var trip = false
21+ var value = 0xFF and data[i].toInt()
22+ value = value shl 8
23+ if (i + 1 < data.size) {
24+ value = value or (0xFF and data[i + 1 ].toInt())
25+ trip = true
26+ }
27+ value = value shl 8
28+ if (i + 2 < data.size) {
29+ value = value or (0xFF and data[i + 2 ].toInt())
30+ quad = true
31+ }
32+ out [index + 3 ] = alphabet[if (quad) value and 0x3F else 64 ]
33+ value = value shr 6
34+ out [index + 2 ] = alphabet[if (trip) value and 0x3F else 64 ]
35+ value = value shr 6
36+ out [index + 1 ] = alphabet[value and 0x3F ]
37+ value = value shr 6
38+ out [index + 0 ] = alphabet[value and 0x3F ]
39+ i + = 3
40+ index + = 4
41+ }
42+ return out
43+ }
44+
45+ /* *
46+ * 将base64编码的数据解码成原始数据
47+ */
48+ fun decode (data : CharArray ): ByteArray {
49+ var len = (data.size + 3 ) / 4 * 3
50+ if (data.size > 0 && data[data.size - 1 ] == ' =' )
51+ -- len
52+ if (data.size > 1 && data[data.size - 2 ] == ' =' )
53+ -- len
54+ val out = ByteArray (len)
55+ var shift = 0
56+ var accum = 0
57+ var index = 0
58+ for (ix in data.indices) {
59+ val value = codes[data[ix].toInt() and 0xFF ].toInt()
60+ if (value >= 0 ) {
61+ accum = accum shl 6
62+ shift + = 6
63+ accum = accum or value
64+ if (shift >= 8 ) {
65+ shift - = 8
66+ out [index++ ] = (accum shr shift and 0xff ).toByte()
67+ }
68+ }
69+ }
70+ if (index != out .size)
71+ throw Error (" miscalculated data length!" )
72+ return out
73+ }
74+
75+ fun decode (data : String? ): String {
76+ if (data.isNullOrEmpty()) {
77+ return " "
78+ }
79+ return String (decode(data.toCharArray()))
80+ }
81+
82+ init {
83+ for (i in 0 .. 255 )
84+ codes[i] = - 1
85+ run {
86+ var i: Int = ' A' .toInt()
87+ while (i <= ' Z' .toInt()) {
88+ codes[i] = (i - ' A' .toInt()).toByte()
89+ i++
90+ }
91+ }
92+ run {
93+ var i: Int = ' a' .toInt()
94+ while (i <= ' z' .toInt()) {
95+ codes[i] = (26 + i - ' a' .toInt()).toByte()
96+ i++
97+ }
98+ }
99+ var i: Int = ' 0' .toInt()
100+ while (i <= ' 9' .toInt()) {
101+ codes[i] = (52 + i - ' 0' .toInt()).toByte()
102+ i++
103+ }
104+ codes[' +' .toInt()] = 62
105+ codes[' /' .toInt()] = 63
106+ }
107+ // public static void main(String[] args) throws Exception {
108+ // // 加密成base64
109+ // String strSrc = "林";
110+ // String strOut = new String(Base64.encode(strSrc.getBytes("GB18030")));
111+ // System.out.println(strOut);
112+ //
113+ // }
114+
115+ }
0 commit comments