import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.zip.Deflater;

import java.util.zip.Inflater;

public class Base64 {

/**

* Byte value that maps to 'a' in Base64 encoding

*/

private final static int LOWER_CASE_A_VALUE = 26;

/**

* Byte value that maps to '0' in Base64 encoding

*/

private final static int ZERO_VALUE = 52;

/**

* Byte value that maps to '+' in Base64 encoding

*/

private final static int PLUS_VALUE = 62;

/**

* Byte value that maps to '/' in Base64 encoding

*/

private final static int SLASH_VALUE = 63;

/**

* Bit mask for one character worth of bits in Base64 encoding. Equivalent

* to binary value 111111b.

*/

private final static int SIX_BIT_MASK = 63;

/**

* Bit mask for one byte worth of bits in Base64 encoding. Equivalent to

* binary value 11111111b.

*/

private static final int EIGHT_BIT_MASK = 0xFF;

/**

* The input String to be decoded

*/

private String mString;

/**

* Current position in the String(to be decoded)

*/

private int mIndex = 0;

/**

* Encode an array of bytes using Base64

*

* @param data[]

*            The bytes to be encoded

* @return A valid Base64 representation of the input

*/

public static String encode(byte data[])

{

return new Base64().internalEncode(data);

}

/**

* Encode an array of bytes using Base64

*

* @param data[]

*            The bytes to be encoded

* @return A valid Base64 representation of the input

*/

public String internalEncode(byte data[])

{

// Base64 encoding yields a String that is 33% longer than the byte

// array

int charCount = ((data.length * 4) / 3) + 4;

// New lines will also be needed for every 76 charactesr, so allocate a

// StringBuffer that is long enough to hold the full result without

// having to expand later

StringBuffer result = new StringBuffer((charCount * 77) / 76);

int byteArrayLength = data.length;

int byteArrayIndex = 0;

int byteTriplet = 0;

while (byteArrayIndex < byteArrayLength - 2)

{

// Build the 24 bit byte triplet from the input data

byteTriplet = convertUnsignedByteToInt(data[byteArrayIndex++]);

// Each input byte contributes 8 bits to the triplet

byteTriplet <<= 8;

byteTriplet |= convertUnsignedByteToInt(data[byteArrayIndex++]);

byteTriplet <<= 8;

byteTriplet |= convertUnsignedByteToInt(data[byteArrayIndex++]);

// Look at the lowest order six bits and remember them

byte b4 = (byte) (SIX_BIT_MASK & byteTriplet);

// Move the byte triplet to get the next 6 bit value

byteTriplet >>= 6;

byte b3 = (byte) (SIX_BIT_MASK & byteTriplet);

byteTriplet >>= 6;

byte b2 = (byte) (SIX_BIT_MASK & byteTriplet);

byteTriplet >>= 6;

byte b1 = (byte) (SIX_BIT_MASK & byteTriplet);

// Add the Base64 encoded character to the result String

result.append(mapByteToChar(b1));

result.append(mapByteToChar(b2));

result.append(mapByteToChar(b3));

result.append(mapByteToChar(b4));

// There are 57 bytes for every 76 characters, so wrap the line when

// needed

// if ( byteArrayIndex % 57 == 0 ) {

// result.append( "\n" );

// }

}

// Check if we have one byte left over

if (byteArrayIndex == byteArrayLength - 1)

{

// Convert our one byte to an int

byteTriplet = convertUnsignedByteToInt(data[byteArrayIndex++]);

// Right pad the second 6 bit value with zeros

byteTriplet <<= 4;

byte b2 = (byte) (SIX_BIT_MASK & byteTriplet);

byteTriplet >>= 6;

byte b1 = (byte) (SIX_BIT_MASK & byteTriplet);

result.append(mapByteToChar(b1));

result.append(mapByteToChar(b2));

// Add "==" to the output to make it a multiple of 4 Base64

// characters

result.append("==");

}

// Check if we have two byte left over

if (byteArrayIndex == byteArrayLength - 2)

{

// Convert our two bytes to an int

byteTriplet = convertUnsignedByteToInt(data[byteArrayIndex++]);

byteTriplet <<= 8;

byteTriplet |= convertUnsignedByteToInt(data[byteArrayIndex++]);

// Right pad the third 6 bit value with zeros

byteTriplet <<= 2;

byte b3 = (byte) (SIX_BIT_MASK & byteTriplet);

byteTriplet >>= 6;

byte b2 = (byte) (SIX_BIT_MASK & byteTriplet);

byteTriplet >>= 6;

byte b1 = (byte) (SIX_BIT_MASK & byteTriplet);

result.append(mapByteToChar(b1));

result.append(mapByteToChar(b2));

result.append(mapByteToChar(b3));

// Add "==" to the output to make it a multiple of 4 Base64

// characters

result.append("=");

}

return result.toString();

}

/**

* Decode an input String using Base64

*

* @param data

*            The String to be decoded

* @return The appropriate byte array

*/

public static byte[] decode(String data)

{

return new Base64().internalDecode(data);

}

/**

* Decode an input String using Base64

*

* @param data

*            The String to be decoded

* @return The appropriate byte array

*/

public byte[] internalDecode(String data)

{

mString = data;

mIndex = 0;

/**

* Total number of Base64 characters in the input

*/

int mUsefulLength = 0;

int length = mString.length();

for (int i = 0; i < length; i++)

{

if (isUsefulChar(mString.charAt(i)))

{

mUsefulLength++;

}

}

// mString = data;

// A Base64 byte array is 75% the size of its String representation

int byteArrayLength = mUsefulLength * 3 / 4;

byte result[] = new byte[byteArrayLength];

int byteTriplet = 0;

int byteIndex = 0;

// Continue until we have less than 4 full characters left to

// decode in the input.

while (byteIndex + 2 < byteArrayLength)

{

// Package a set of four characters into a byte triplet

// Each character contributes 6 bits of useful information

byteTriplet = mapCharToInt(getNextUsefulChar());

byteTriplet <<= 6;

byteTriplet |= mapCharToInt(getNextUsefulChar());

byteTriplet <<= 6;

byteTriplet |= mapCharToInt(getNextUsefulChar());

byteTriplet <<= 6;

byteTriplet |= mapCharToInt(getNextUsefulChar());

// Grab a normal byte (eight bits) out of the byte triplet

// and put it in the byte array

result[byteIndex + 2] = (byte) (byteTriplet & EIGHT_BIT_MASK);

byteTriplet >>= 8;

result[byteIndex + 1] = (byte) (byteTriplet & EIGHT_BIT_MASK);

byteTriplet >>= 8;

result[byteIndex] = (byte) (byteTriplet & EIGHT_BIT_MASK);

byteIndex += 3;

}

// Check if we have one byte left to decode

if (byteIndex == byteArrayLength - 1)

{

// Take out the last two characters from the String

byteTriplet = mapCharToInt(getNextUsefulChar());

byteTriplet <<= 6;

byteTriplet |= mapCharToInt(getNextUsefulChar());

// Remove the padded zeros

byteTriplet >>= 4;

result[byteIndex] = (byte) (byteTriplet & EIGHT_BIT_MASK);

}

// Check if we have two bytes left to decode

if (byteIndex == byteArrayLength - 2)

{

// Take out the last three characters from the String

byteTriplet = mapCharToInt(getNextUsefulChar());

byteTriplet <<= 6;

byteTriplet |= mapCharToInt(getNextUsefulChar());

byteTriplet <<= 6;

byteTriplet |= mapCharToInt(getNextUsefulChar());

// Remove the padded zeros

byteTriplet >>= 2;

result[byteIndex + 1] = (byte) (byteTriplet & EIGHT_BIT_MASK);

byteTriplet >>= 8;

result[byteIndex] = (byte) (byteTriplet & EIGHT_BIT_MASK);

}

return result;

}

/**

* Convert a Base64 character to its 6 bit value as defined by the mapping.

*

* @param c

*            Base64 character to decode

* @return int representation of 6 bit value

*/

private int mapCharToInt(char c)

{

if (c >= 'A' && c <= 'Z')

{

return c - 'A';

}

if (c >= 'a' && c <= 'z')

{

return (c - 'a') + LOWER_CASE_A_VALUE;

}

if (c >= '0' && c <= '9')

{

return (c - '0') + ZERO_VALUE;

}

if (c == '+')

{

return PLUS_VALUE;

}

if (c == '/')

{

return SLASH_VALUE;

}

throw new IllegalArgumentException(c + " is not a valid Base64 character.");

}

/**

* Convert a byte between 0 and 63 to its Base64 character equivalent

*

* @param b

*            Byte value to be converted

* @return Base64 char value

*/

private char mapByteToChar(byte b)

{

if (b < LOWER_CASE_A_VALUE)

{

return (char) ('A' + b);

}

if (b < ZERO_VALUE)

{

return (char) ('a' + (b - LOWER_CASE_A_VALUE));

}

if (b < PLUS_VALUE)

{

return (char) ('0' + (b - ZERO_VALUE));

}

if (b == PLUS_VALUE)

{

return '+';

}

if (b == SLASH_VALUE)

{

return '/';

}

throw new IllegalArgumentException("Byte " + new Integer(b) + " is not a valid Base64 value");

}

/**

* @param c

*            Character to be examined

* @return Whether or not the character is a Base64 character

*/

private boolean isUsefulChar(char c)

{

return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '+') || (c == '/');

}

/**

* Traverse the String until hitting the next Base64 character. Assumes that

* there is still another valid Base64 character left in the String.

*/

private char getNextUsefulChar()

{

char result = '_'; // Start with a non-Base64 character

while (!isUsefulChar(result))

{

result = mString.charAt(mIndex++);

}

return result;

}

/**

* Convert a byte to an integer. Needed because in Java bytes are signed,

* and for Base64 purposes they are not. If not done this way, when

* converted to an int, 0xFF will become -127

*

* @param b

*            Byte value to be converted

* @return Value as an integer, as if byte was unsigned

*/

private int convertUnsignedByteToInt(byte b)

{

if (b >= 0)

{

return (int) b;

}

return 256 + b;

}

public static String getEncodeMsg(String tMessage)

{

String returnStr = "";

try

{

ByteArrayOutputStream byteStream = getCompressedStr(tMessage);

if(byteStream!=null)

returnStr = Base64.encode(byteStream.toByteArray());

//returnStr = Base64.encode(tMessage.getBytes("UTF-8"));

}

catch (Exception ex)

{

ex.printStackTrace();

}

return returnStr;

}

private static ByteArrayOutputStream getCompressedStr(String tMessage)

{

ByteArrayOutputStream compressedStream = null;

try

{

if (tMessage != null && !"".equals(tMessage))

{

byte[] input = tMessage.getBytes("UTF-8");

Deflater compresser = new Deflater();

compresser.setInput(input);

compresser.finish();

compressedStream = new ByteArrayOutputStream();

byte[] buf = new byte[2048];

while (!compresser.finished())

{

int got = compresser.deflate(buf);

compressedStream.write(buf, 0, got);

}

}

}

catch (Exception ex)

{

ex.printStackTrace();

}

finally

{

if (compressedStream != null)

{

try

{

compressedStream.close();

}

catch (IOException ioex)

{

ioex.printStackTrace();

}

}

}

return compressedStream;

}

public static String getDecodeMsg(String tMessage)

{

String outputString = "";

byte[] inputStr  = null;

try

{

String newStr = tMessage;

newStr = newStr.replaceAll(" ", "+");

inputStr = Base64.decode(newStr);

outputString = getDeCompressedStr(inputStr);

}

catch (Exception ex)

{

ex.printStackTrace();

}

return outputString;

//      return new String(inputStr);

}

private static String getDeCompressedStr(byte[] tMessage)

{

String returnStr = "";

ByteArrayOutputStream aDeCompressedStream = null;

try

{

// Decompress the bytes

Inflater decompresser = new Inflater();

decompresser.setInput(tMessage);

aDeCompressedStream = new ByteArrayOutputStream();

byte[] buf = new byte[2048];

while (!decompresser.finished())

{

int got = decompresser.inflate(buf);

aDeCompressedStream.write(buf, 0, got);

}

}

catch (Exception ex)

{

ex.printStackTrace();

} finally

{

try

{

if(aDeCompressedStream!=null)

aDeCompressedStream.close();

}

catch (IOException ioex)

{

ioex.printStackTrace();

}

}

try

{

returnStr = aDeCompressedStream.toString("UTF-8");

}

catch (UnsupportedEncodingException encodeEx)

{

encodeEx.printStackTrace();

}

return returnStr;

}

}

Base64(2)的更多相关文章

  1. linux shell 不同进制数据转换(二进制,八进制,十六进制,base64) (转)

    shell可以在不调用第3方命令,表示不同进制数据.这里总结以下表示方法.shell 脚本默认数值是由10 进制数处理,除非这个数字某种特殊的标记法或前缀开头. 才可以表示其它进制类型数值.如:以 0 ...

  2. 将上传图片转成base64(转)

    效果如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"><titl ...

  3. js转base64(数字)

    var name='测试文字'; var t_name=encodeURIComponent(name); t_name=window.btoa(t_name); console.log(t_name ...

  4. hdu 5237 Base64(模拟)

    Base64 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Subm ...

  5. Base64(3)

    public final class Base64 { static private final int     BASELENGTH           = 128; static private ...

  6. WebSocket协议探究(一)

    一 复习和目标 1 复习 上一节使用wireshark抓包分析了WebSocket流量 包含连接的建立:HTTP协议升级WebSocket协议 使用建立完成的WebSocket协议发送数据 2 目标 ...

  7. cookie规范(RFC6265)翻译

    来源:https://github.com/renaesop/blog/issues/4 RFC 6265 要点翻译 1.简介 本文档定义了HTTP Cookie以及HTTP头的Set-Cookie字 ...

  8. (iOS)Base64加密和DES加密、以及JAVA和iOS中DES加密统一性问题

    我们在项目中为了安全方面的考虑,通常情况下会选择一种加密方式对需要安全性的文本进行加密,而Base64加密和DES64加密是常用的加密算法.我记得我在前一个项目中使用的就是这两种加密算法的结合:Bas ...

  9. Java加密技术(一)——BASE64与单向加密算法MD5&SHA&MAC

    Java加密技术(一)——BASE64与单向加密算法MD5&SHA&MAC 博客分类: Java/Security Javabase64macmd5sha     加密解密,曾经是我一 ...

随机推荐

  1. docker容器资源配额控制_转

    转自:docker容器资源配额控制 ■ 文/ 天云软件 容器技术团队 docker通过cgroup来控制容器使用的资源配额,包括CPU.内存.磁盘三大方面,基本覆盖了常见的资源配额和使用量控制. cg ...

  2. MySQL优化整理

    一.SQL优化 1.show status查看各种sql的执行频率   SHOW STATUS 可以根据需要显示 session 级别的统计结果和 global级别的统计结果.   显示当前sessi ...

  3. ARTS-week4

    Algorithm 将两个有序链表合并为一个新的有序链表并返回.新链表是通过拼接给定的两个链表的所有节点组成的.示例:输入:1->2->4, 1->3->4输出:1->1 ...

  4. 1、Python简介与Python安装

    一.Python简介: Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. Python的创始人为吉多·范罗苏姆(Guido van Rossum)少数几个不秃头的语言创始 ...

  5. 聊聊rocketmq的ConsumeMode.CONCURRENTLY

    序 本文主要研究一下rocketmq的ConsumeMode.CONCURRENTLY ConsumeMode.CONCURRENTLY rocketmq-spring-boot-2.0.4-sour ...

  6. S1_搭建分布式OpenStack集群_05 glance安装配置

    一.基本简介         镜像服务(glance)使用户能够发现,注册和检索虚拟机镜像. 它提供了一个REST API,使您可以查询虚拟机镜像元数据并检索实际镜像. 您可以将通过镜像服务提供的虚拟 ...

  7. Minidumps 和 modules匹配

    简介 调试应用程序时,调试器必须加载可执行模块的符号,以便能够显示有意义的调用堆栈.当前源代码行.变量值等.如果您曾经调试过在另一个系统上创建的小型转储,那么您已经知道除了符号之外,调试器还需要访问创 ...

  8. zeebe 0.20.0 集群部署试用

    zeebe 0.20.0 是生产可用的第一个版本,同时也有好多变动,以下是一个简单集群的运行以及一个简单 的运行说明 环境准备 docker-compose 文件   version: "3 ...

  9. Uncaught ReferenceError: Invalid left-hand side in assignment

    Uncaught ReferenceError: Invalid left-hand side in assignment 今天在对个人资料页面增加当浏览别的页面之后第二次访问当前页面,之前填写的内容 ...

  10. go的接口内部实现

    1 前言 1.1 Go汇编 Go语言被定义为一门系统编程语言,与C语言一样通过编译器生成可直接运行的二进制文件.这一点与Java,PHP,Python等编程语言存在很大的不同,这些语言都是运行在基于C ...