`
superich2008
  • 浏览: 326164 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Base64加密、解密

阅读更多

package util;

import java.io.UnsupportedEncodingException;

/**
* Provides encoding of raw bytes to base64-encoded characters, and decoding of
* base64 characters to raw bytes.
*
* @author Kevin Kelley (kelley@ruralnet.net)
* @version 1.3
* @date 06 August 1998
* @modified 14 February 2000
* @modified 22 September 2000
*/
public class Base64
{

private static final String URL_ENCODE = "UTF-8";

private static final String BASE64_ENCODE = "GBK";

public static String encodeURL(String str)
{
try
{
str = java.net.URLEncoder.encode(str, URL_ENCODE);
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}

public static String decodeURL(String str)
{
try
{
str = java.net.URLDecoder.decode(str, URL_ENCODE);
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}

/**
* returns an array of base64-encoded characters to represent the passed
* data array.
*
* @param data
* the array of bytes to encode
* @return base64-coded character array.
*/
static public char[] encode(byte[] data)
{
char[] out = new char[((data.length + 2) / 3) * 4];

//
// 3 bytes encode to 4 chars. Output is always an even
// multiple of 4 characters.
//
for (int i = 0, index = 0; i < data.length; i += 3, index += 4)
{
boolean quad = false;
boolean trip = false;

int val = (0xFF & (int) data[i]);
val <<= 8;
if ((i + 1) < data.length)
{
val |= (0xFF & (int) data[i + 1]);
trip = true;
}
val <<= 8;
if ((i + 2) < data.length)
{
val |= (0xFF & (int) data[i + 2]);
quad = true;
}
out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 1] = alphabet[val & 0x3F];
val >>= 6;
out[index + 0] = alphabet[val & 0x3F];
}
return out;
}

/**
* Decodes a BASE-64 encoded stream to recover the original data. White
* space before and after will be trimmed away, but no other manipulation of
* the input will be performed.
*
* As of version 1.2 this method will properly handle input containing junk
* characters (newlines and the like) rather than throwing an error. It does
* this by pre-parsing the input and generating from that a count of VALID
* input characters.
*/
static public byte[] decode(char[] data)
{
// as our input could contain non-BASE64 data (newlines,
// whitespace of any sort, whatever) we must first adjust
// our count of USABLE data so that...
// (a) we don't misallocate the output array, and
// (b) think that we miscalculated our data length
// just because of extraneous throw-away junk

int tempLen = data.length;
for (int ix = 0; ix < data.length; ix++)
{
if ((data[ix] > 255) || codes[data[ix]] < 0)
--tempLen; // ignore non-valid chars and padding
}
// calculate required length:
// -- 3 bytes for every 4 valid base64 chars
// -- plus 2 bytes if there are 3 extra base64 chars,
// or plus 1 byte if there are 2 extra.

int len = (tempLen / 4) * 3;
if ((tempLen % 4) == 3)
len += 2;
if ((tempLen % 4) == 2)
len += 1;

byte[] out = new byte[len];

int shift = 0; // # of excess bits stored in accum
int accum = 0; // excess bits
int index = 0;

// we now go through the entire array (NOT using the 'tempLen' value)
for (int ix = 0; ix < data.length; ix++)
{
int value = (data[ix] > 255) ? -1 : codes[data[ix]];

if (value >= 0) // skip over
// non-code
{
accum <<= 6; // bits
// shift up
// by 6 each
// time thru
shift += 6; // loop,
// with new
// bits
// being put
// in
accum |= value; // at the
// bottom.
if (shift >= 8) // whenever
// there are
// 8 or more
// shifted
// in,
{
shift -= 8; // write
// them out
// (from the
// top,
// leaving
// any
out[index++] = // excess at the
// bottom for
// next
// iteration.
(byte) ((accum >> shift) & 0xff);
}
}
// we will also have skipped processing a padding null byte
// ('=') here;
// these are used ONLY for padding to an even length and do not
// legally
// occur as encoded data. for this reason we can ignore the fact
// that
// no index++ operation occurs in that special case: the out[]
// array is
// initialized to all-zero bytes to start with and that works to
// our
// advantage in this combination.
}

// if there is STILL something wrong we just have to throw up now!
if (index != out.length)
{
throw new Error("Miscalculated data length (wrote " + index
+ " instead of " + out.length + ")");
}

return out;
}

/**
* added by Neal
*
* @param str
* String
* @return String
*/

public static String encodeString(String str)
{
byte[] bt = null;
try
{
bt = str.getBytes(BASE64_ENCODE);
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
bt = str.getBytes();
e.printStackTrace();
}

char[] cArray = Base64.encode(bt);
return new String(cArray);
}

/**
* added by Neal
*
* @param str
* String
* @return String
*/
public static String decodeString(String str)
{
char[] cArray = str.toCharArray();
byte[] bt = Base64.decode(cArray);
return (new String(bt));
}

//
// code characters for values 0..63
//
static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray();

//
// lookup table for converting base64 characters to value in range 0..63
//
static private byte[] codes = new byte[256];
static
{
for (int i = 0; i < 256; i++)
codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
codes[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
codes[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}

public static void main(String[] args)
{
String str = "中文测试";
String encodeStr = Base64.encodeURL(Base64.encodeString(str));
System.out.println(encodeStr);
System.out.println(Base64.decodeString(Base64.decodeURL(encodeStr)));
}
}

分享到:
评论

相关推荐

    BASE64加密解密

    【标题】:BASE64加密解密 在计算机科学中,BASE64是一种常见的数据编码方式,用于将二进制数据转换为可打印的ASCII字符序列。这种编码方法广泛应用于电子邮件系统、网络传输以及文件存储等领域,因为它可以将任何...

    C# Base64加密解密

    总的来说,C#中的Base64加密解密提供了简单且安全的方法来处理二进制数据,特别是在需要在文本环境(如邮件、网页)中传输时。在WinForm应用中,开发者可以结合UI设计,创建用户友好的工具,方便地进行Base64编码和...

    Java Base64加密解密方法工具类

    Java Base64加密解密方法工具类

    Base64加密解密.zip

    以下是对Base64加密解密的详细讲解以及如何在C# WinForm应用中实现。 首先,理解Base64的基本原理。Base64使用64个不同的字符(包括大小写字母、数字以及"+"和"/")来表示二进制数据,每个字符代表6位二进制数。...

    java 图片base64 加密解密

    在Java编程中,图片Base64加密解密是一种常见的数据处理技术,特别是在网络传输和存储时,由于Base64编码可以将二进制数据转换为可打印的ASCII字符,因此非常适用。`sun.misc.BASE64Encoder`和`sun.misc.BASE64...

    微信小程序 AES ECB base64 加密解密

    在微信小程序中实现AES ECB Base64加密解密,你需要以下步骤: 1. 引入加密库:微信小程序提供了`wx.request`方法来调用外部API,你可以引入第三方加密库,如`crypto-js`,通过npm安装后将其添加到项目中。 2. ...

    sqlserver2005的base64加密解密函数

    总结,虽然SQL Server 2005本身并不提供内置的Base64加密解密功能,但通过创建自定义函数,我们可以实现类似的功能。需要注意的是,上述函数仅适用于简单场景,对于更复杂的需求,可能需要更完善的Base64编码解码...

    LabVIEW实现Base64加密解密程序源码

    LabVIEW实现Base64加密解密程序源码,可以作为子VI直接调用,非常方便,经过测试没有问题。base64是一种用64个字符来表示任意二进制数据的方法。base 64编码可以将任意一组字节转换为较长的常见文本字符序列,从而...

    js的base64加密解密

    在这个场景中,我们讨论的是一个纯JavaScript实现的Base64加密解密工具类,它无需依赖其他外部JavaScript库,因此非常适合在各种环境中使用,特别是对于那些对文件大小和加载速度有严格要求的项目。 Base64加密,也...

    Sql Server Base64加密解密角本

    非常实用的Base64加密,解密角本。基于UTF8,支持中文加解密。

    C#base64加密解密工具(有源码)

    总结来说,C#的Base64加密解密工具提供了对二进制数据的简单编码和解码,方便在各种环境中传递和存储数据。源码的分析有助于开发者理解和掌握这一基础但实用的技术,进一步提高编程能力。在使用过程中,注意正确处理...

    base64加密解密

    下面,我们将深入探讨Base64加密解密的原理和实现: 1. **Base64编码原理**:Base64编码将每3个字节的二进制数据(24位)转化为4个6位的二进制数,然后将这6位转换为对应的Base64字符。如果原始数据不是3的倍数,会...

    base64加密解密的hive udf函数

    本文将详细探讨如何在Hive中自定义User Defined Function(UDF)来实现Base64的加密和解密。 首先,我们需要了解Base64的基本原理。Base64是一种将任意二进制数据转化为ASCII字符集的方法,它通过将每3个字节转换为...

    Base64加密解密

    这个压缩包文件"复件 Base64_Test源码"包含了C++实现Base64加密解密的源代码,对于理解Base64的工作原理和C++编程实践非常有帮助。 Base64的基本原理是将每3个8位字节(共24位)的数据块转换为4个6位的字节(共24位...

    Base64 加密解密小工具

    下面,我们将深入探讨Base64加密解密的基本原理、用途以及如何使用工具进行操作。 1. Base64的基本原理 Base64是基于64个可打印字符来表示二进制数据的编码方法。这64个字符包括大小写字母(A-Z, a-z)、数字(0-9...

    Base64加密解密工具

    "Base64加密解密工具"是专门针对这种编码方式进行设计的实用程序,能够帮助用户便捷地对数据进行Base64编码或解码。 Base64编码的基本原理是将每3个字节(24位)的数据转换为4个6位的Base64字符,这样每个64字符的...

    Base64加密解密封装

    标题提到的"Base64加密解密封装"是指将Base64编码和解码的逻辑进行封装,以方便在项目中复用。封装通常包括创建类或方法,提供接口供其他部分的代码调用,实现加密和解密功能。这种封装能提高代码的可读性和可维护性...

    用Java实现BASE64加密解密

    总之,Java提供了方便的`java.util.Base64`工具类来处理Base64编码和解码,使得在Java项目中实现Base64加密解密变得简单且高效。这个基础的加密解密机制虽然简单,但在很多场景下已经足够满足基本的数据保护需求。

    base64 加密解密

    Base64是一种常见的数据编码方式,它将...总的来说,通过理解和掌握C#中的Base64加密解密,你可以更好地处理二进制数据的传输和存储问题。这个VS2015的Demo提供了一个很好的起点,帮助开发者快速上手并应用于实际项目。

Global site tag (gtag.js) - Google Analytics