128进制加密数据示例分享
128进制加密数据,可以自定符号表,使用自己喜欢的符号做加密
package com.wmly.enc;
import java.util.hashmap;
/**
* 128进制加解密, 一个符号可表示7个bit
* 可以自定义符号表, 符号不能重复
*/
public class mybase128 {
public static final char[] symboltable = new char[128];
public static final hashmap<character, integer> indextable = new hashmap<>(128);
static {
int i = 0;
for (int j = 0; j < 128; j++) {
// symboltable[j] = (char) j;
if('a' <= j && j <= 'z'
|| 'a' <= j && j <= 'z'
|| '0' <= j && j <= '9') {
symboltable[i++] = (char) j;
}
}
for (char c : "这是中国人写地[备思要爱发]编解码程序&拥有独特的自定义符号表|不过布能使用重复字,汗啊(还差一十二个知*.#)。为我们加油吧,亲!".tochararray()) {
symboltable[i++] = c;
}
checktable();
for (int j = 0; j < 128; j++) {
indextable.put(symboltable[j], j);
}
}
private static void checktable() throws error {
if(symboltable[127] == 0) {
throw new error("符号表长度不正确!");
}
for (char a : symboltable) {
int count = 0;
for (char b : symboltable) {
if(a == b) {
count++;
}
}
if(count > 2) {
throw new error("符号表有重复符号!");
}
}
}
public string encode(byte[] data) {
if(data == null || data.length == 0) {
return new string();
}
stringbuilder result = new stringbuilder();
int tail = 0;
for (int i = 0; i < data.length; i++) {
int mov = (i % 7 + 1);
int curr = 0xff & data[i];
int code = tail + (curr >> mov);
result.append(symboltable[code]);
tail = (0xff & (curr << (8 - mov))) >> 1;
if(mov == 7) {
result.append(symboltable[tail]);
tail = 0;
}
}
result.append(symboltable[tail]);
return result.tostring();
}
public byte[] decode(string base128) {
if(base128 == null || base128.length() == 0) {
return new byte[] { };
}
int length = (int) math.floor(base128.length() * 0.875);
byte[] result = new byte[length];
int idx = 0;
int head = indextable.get(base128.charat(0)) << 1;
for (int i = 1; i < base128.length();) {
int mod = i % 8;
int code = indextable.get(base128.charat(i++));
result[idx++] = (byte) (0xff & (head + (code >> (7 - mod))));
if(mod == 7) {
head = 0xff & (indextable.get(base128.charat(i++)) << 1);
} else {
head = 0xff & (code << (mod + 1));
}
}
return result;
}
///////////////////////测试方法///////////////////////////////
public static void main(string[] args) {
mybase128 base128 = new mybase128();
test(base128);
string txt = "这是我的加解密测试";
string enc = base128.encode(txt.getbytes());
system.out.println(enc);
system.out.println("----------------");
system.out.println(new string(base128.decode(enc)));
}
private static void test(mybase128 base128) {
for (int i = 0; i < 10000; i++) {
string r = randomdata();
string d = new string(base128.decode(base128.encode(r.getbytes())));
if(!r.equals(d)) {
// d = new string(base128.decode(base128.encode(r.getbytes())));
system.out.println("加解密失败!: " + r);
}
}
}
private static string randomdata() {
string textstring = "了咖啡机累啊戴假发\n\r哦-";
int start = random(0, textstring.length() - 3);
int end = random(start + 1, textstring.length() - 1);
return textstring.substring(start, end);
}
private static int random(int i, int j) {
return (int) math.ceil(math.random()*(j-i)+i);
}
}