程序主要是把一个字符串按照base64编码的方式转换为目标字符串,以及提供了解码的方式。
可以改变其中的Base64Code 就可以实现一个不同的编码方法,可以做加密解密的小程序哦。
以下是java的程序代码:
package renjie120;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyBase64 {
public MyBase64() {
}
static int w;// 3-编码时数组除以3余下的数
static char[] source;
static String Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
static char[] baseCodes = Base64Code.toCharArray();
static String regex = "^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=]*$";
public static char[] ToBase64String(char[] input) {
source = input;
int messageLen = input.length;
int page = messageLen / 3;
int messageLen2;
if ((messageLen % 3) > 0) {
page++;
w = 3 - messageLen % 3;
}
messageLen2 = messageLen + w;
char[] before = new char[messageLen2];
for (int x = 0; x < messageLen2; x++) {
if (x < messageLen) {
before[x] = source[x];
} else {//将补上的数组设置为0
before[x] = 0;
}
}
char[] instr = new char[3];
char[] result = new char[page * 4];
byte[] buffer = new byte[page * 4];
for (int i = 0; i < page; i++) {
instr[0] = before[i * 3];
instr[1] = before[i * 3 + 1];
instr[2] = before[i * 3 + 2];
buffer[0 + i * 4] = (byte) (instr[0] >> 2);
buffer[1 + i * 4] = (byte) (((instr[0] & 0x03) << 4) ^ (instr[1] >> 4));
if (instr[1] != 0) {
buffer[2 + i * 4] = (byte) (((instr[1] & 0x0f) << 2) ^ (instr[2] >> 6));
} else {
buffer[2 + i * 4] = 64;
}
if (instr[2] != 0) {
buffer[3 + i * 4] = (byte) (instr[2] & 0x3f);
} else {
buffer[3 + i * 4] = 64;//这一步必不可少!!!这样的话,虽然叫Base64,
}
//有64个有用的代码,实际要用的是65个!!!!,多个‘=’,以后要把他去掉的!!
}
for (int x = 0; x < page * 4; x++) {
result[x] = baseCodes[buffer[x]];
}
return result;
}
public static String ToMyBase64String(String input) {
try {
byte[] temp;
temp = input.getBytes(System.getProperty("file.encoding"));
int len = temp.length;
char[] oldStrbyte = new char[len];
for (int i = 0; i < len; i++) {
char hh = (char) temp[i];
if (temp[i] < 0) {
hh = (char) (temp[i] + 256);
}
oldStrbyte[i] = hh;
}
char[] ansChars = ToBase64String(oldStrbyte);
return new String(ansChars);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static byte[] FromBase64String(String Message1) throws Exception {
int q = 0;// 用来统计有多少个转义字符!
for (int a = 0; a < Message1.length(); a++) {
byte x = (byte) Message1.charAt(a);
if (x == 10 || x == 13 || x == 9 || x == 32)
q++;
}
char[] message = new char[Message1.length() - q];
int d = 0;
for (int a = 0; a < Message1.length(); a++) {
byte x = (byte) Message1.charAt(a);
if (x == 10 || x == 13 || x == 9 || x == 32) {
d++;
continue;
} else
message[a - d] = Message1.charAt(a);
}
String Message = new String(message);
int flag = Pattern.CASE_INSENSITIVE;
Pattern p = Pattern.compile(regex, flag);
Matcher m = p.matcher(Message);
int matchStartIndex = -1;
int matchEndIndex = -1;
while (m.find()) {
matchStartIndex = m.start();
matchEndIndex = m.end();
break;
}
if (matchStartIndex != 0 || matchEndIndex != Message.length()) {
throw new Exception("含有非法的字符在编码中,请检查!");
}
if (((Message.length()) % 4) != 0)
throw new Exception("不是正确的BASE64编码,请检查。");
int page = Message.length() / 4;
byte[] buffer = new byte[page * 3];
int length;
int temp = 0;// 用来看最后的3个字符中有多少个“=”
for (int x = 0; x < 2; x++) {
if (message[Message.length() - x - 1] == '=')
temp++;
}
length = buffer.length - temp;
byte[] newStr = new byte[length];
byte[] outstr = new byte[3 * page];// 用来将outMessage的内容全部复制到这里好把他传到外面去.
for (int i = 0; i < page; i++) {
byte[] instr = new byte[4];// 下面的是用来看base64编码的对应的数是0到64的哪一个
instr[0] = (byte) Base64Code.indexOf(message[i * 4]);
instr[1] = (byte) Base64Code.indexOf(message[i * 4 + 1]);
instr[2] = (byte) Base64Code.indexOf(message[i * 4 + 2]);
instr[3] = (byte) Base64Code.indexOf(message[i * 4 + 3]);
outstr[0 + i * 3] = (byte) ((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4));
if (instr[2] != 64)
outstr[1 + i * 3] = (byte) ((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2));
else
outstr[2 + i * 3] = 0;
if (instr[3] != 64)
outstr[2 + i * 3] = (byte) ((instr[2] << 6) ^ instr[3]);
else
outstr[2 + i * 3] = 0;
}
for (int o = 0; o < length; o++)
// length为去掉了后面的'='后的长度
newStr[o] = outstr[o];
return newStr;
}
public static String FromMyBase64String(String str) throws Exception {
byte[] ansBytes = FromBase64String(str);
String ans = new String(ansBytes, System.getProperty("file.encoding"));
return ans;
}
public static void main(String[] args) {
MyBase64 b1 = new MyBase64();
String s = "祝福大家开心每天";
String s1 = b1.ToMyBase64String(s);
System.out.println(s1);
try {
System.out.println(b1.FromMyBase64String(s1));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
以下是C#的程序代码:
using System;
namespace 公告模版小小修改器
{
///
/// MyBase64 的摘要说明。
///
public class MyBase64
{
public MyBase64()
{
}
static int w;//3-编码时数组除以3余下的数
static byte[] source;
//简便的加密字符串的方法。
public static string getToBase64(string input)
{
Encoding Unicode = System.Text.Encoding.Default;
byte[] byt=Unicode.GetBytes(input);
char[] newch=MyBase64.ToBase64String(byt);
return new string(newch);
}
public static char[] ToBase64String(byte[] input)
{
char[] Base64Code=new char[]{'B','!','@','#','$','%','D','C','j','0','1','2','3','4','5','6','7','8','9','i','k','L','N','M','O','p','q','R','S','T','U','V','W','X','Y','Z','&','d','c','b','^','*','(',')','I','J','K','P','Q','o','n','m','l','r','s','t','u','v','w','x','y','z','+','/','='};
source=input;
int messageLen=input.Length;
int page=messageLen/3;
int messageLen2;
if((messageLen%3)>0)
{
page++;
w=3-messageLen%3;
}
messageLen2=messageLen+w;
byte[] before=new byte[messageLen2];
for (int x=0; x<
p>
{
if (x<
p>
{
before[x]= source[x];
}
else
{//将补上的数组设置为0
before[x]=0;
}
}
byte[] instr = new byte[3];
char[] result=new char[page*4];
byte[] buffer=new byte[page*4];
for(int i=0;i<
p>
{
instr[0]=(byte)before[i*3];
instr[1]=(byte)before[i*3+1];
instr[2]=(byte)before[i*3+2];
buffer[0+i*4]=(byte)(instr[0]>>2);
buffer[1+i*4]=(byte)(((instr[0]&0x03)<<4)^(instr[1]>>4));
if(!instr[1].Equals(0))
buffer[2+i*4]=(byte)(((instr[1]&0x0f)<<2)^(instr[2]>>6));
else
buffer[2+i*4]=64;
if(!instr[2].Equals(0))
buffer[3+i*4]=(byte)(instr[2]&0x3f);
else
buffer[3+i*4]=64;//这一步必不可少!!!这样的话,虽然叫Base64,
//有64个有用的代码,实际要用的是65个!!!!,多个‘=’,以后要把他去掉的!!
}
for (int x=0; x<
p>
{
result[x]=Base64Code[buffer[x]];
}
return result;
}
//简单的解密的方法
public static string getFromBase64(string input)
{
byte[] byt=MyBase64.FromBase64String(input);
Encoding Unicode = System.Text.Encoding.Default;
retrun Unicode.GetString(byt);
}
public static byte[] FromBase64String(string Message1)
{
int q=0;//用来统计有多少个转义字符!
for(int a=0;a<
p>
{
byte x=(byte)Message1[a];
if(x==10||x==13||x==9||x==32)
q++;
}
char[] message=new char[Message1.Length-q];
int d=0;
for(int a=0;a<
p>
{
byte x=(byte)Message1[a];
if(x==10||x==13||x==9||x==32)
{
d++;
continue;
}
else
message[a-d]=Message1[a];
}
string Message=new string(message);
if(!System.Text.RegularExpressions.Regex.IsMatch(Message,"^[BCDI-Z0-9^&*()!@#$%/+=]*$",System.Text.RegularExpressions.RegexOptions.IgnoreCase))
throw new ArgumentException("包含不正确的BASE64编码,请检查。","Message");
if(((Message.Length)%4)!=0)
throw new ArgumentException("不是正确的BASE64编码,请检查。","Message");
string Base64Code="B!@#$%DCj0123456789ikLNMOpqRSTUVWXYZ&dcb^*()IJKPQonmlrstuvwxyz+/=";
int page=Message.Length/4;
byte[] buffer=new byte[page*3];
int length;
int temp=0;//用来看最后的3个字符中有多少个“=”
for (int x=0;x<2;x++)
{
if(message[Message.Length-x-1]=='=')
temp++;
}
length=buffer.Length-temp;
byte[] newStr=new byte[length];
byte[] outstr=new byte[3*page];//用来将outMessage的内容全部复制到这里好把他传到外面去.
for(int i=0;i<
p>
{
byte[] instr=new byte[4];//下面的是用来看base64编码的对应的数是0到64的哪一个
instr[0]=(byte)Base64Code.IndexOf(message[i*4]);
instr[1]=(byte)Base64Code.IndexOf(message[i*4+1]);
instr[2]=(byte)Base64Code.IndexOf(message[i*4+2]);
instr[3]=(byte)Base64Code.IndexOf(message[i*4+3]);
outstr[0+i*3]=(byte)((instr[0]<<2)^((instr[1]&0x30)>>4));
if(instr[2]!=64)
outstr[1+i*3]=(byte)((instr[1]<<4)^((instr[2]&0x3c)>>2));
else
outstr[2+i*3]=0;
if(instr[3]!=64)
outstr[2+i*3]=(byte)((instr[2]<<6)^instr[3]);
else
outstr[2+i*3]=0;
}
for(int o=0;o<length;o++)//length为去掉了后面的'='后的长度
newStr[o]=outstr[o];
return newStr;
}
}
}
程序的适用范围是对小的字符串进行base64的编码和解码,速度还不是很慢。
对于大的文件如果要进行base64处理,推荐使用javabase64-1.2.jar开源包进行处理。比较的easy。使用该包的方法如下:
使用方法:把类库 javabase64-1.2.jar 设置到编译路径中。
示例代码:
String类型 进行Base64编码
String encoded = Base64.encode("Hello, world!");
String类型 进行Base64解码
String decoded = Base64.decode(encoded);
指定字符编码方式
String encoded = Base64.encode("Hello, world!", "UTF-8");
String decoded = Base64.decode(encoded, "UTF-8");
对文件进行编码:如果文件比较小,可以通过以下方式,直接读取到内存中进行编码处理
byte[] source = ...; // load your data here
byte[] encoded = Base64.encode(source);
byte[] decoded = Base64.decode(encoded);
如果大件比较大,则建议使用stream:代码示例Base64编码:
InputStream inputStream = new FileInputStream("source.jpg");
OutputStream outputStream = new FileOutputStream("encoded.b64");
Base64.encode(inputStream, outputStream);
outputStream.close();
inputStream.close();
代码示例Base64解码:
InputStream inputStream = new FileInputStream("encoded.b64");
OutputStream outputStream = new FileOutputStream("decoded.jpg");
Base64.decode(inputStream, outputStream);
outputStream.close();
inputStream.close();
加载中,请稍候......