1、先将字符串变成byte数组,再将数组每位与key做位运算,得到新的数组就是加密或解密后的byte数组.----缺点:转换后含有特殊符号,Sting字符串copy出来进行解密时,需要先处理特殊符号。如果不是通过手工copy出来再解密的方式,速度会很快。
public classTest {
public static void main(String[] args) throwsException {
String a = "在java快速和简单的字符串加密/解密问题,怎么解决";
System.out.println("原字符串: "+ a);
String b = deal(a, (byte) 88); // 88 为加密密钥
System.out.println("加密后字符串: "+ b);
String c = deal(b, (byte) 88); // 88 为解密密钥,要和加密一致,否则无法解密
System.out.println("解密后字符串: "+ c);
}
/**
* 知识:^ 是java位运算,可以百度了解下,a = b ^ skey 反之也成立,即b = a ^ skey
* @param str 解密/加密 字符串
* @param skey 解密/加密 密钥(加密解密为同一个密钥才能解密,否则是乱码)
*/
static String deal(String str, byte skey) throws Exception {
byte[] bytes = str.getBytes("GBK");
for(int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) (bytes[i] ^ skey);
}
return new String(bytes, "GBK");
}
}
2、java通过base64对字符串进行压缩转换复原
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* 字符串压缩
*/
public class ZipStrUtil {
/**
* 恢复字符串
* @param compressedStr
* @return
*/
public static String gunzip(String compressedStr){
if(compressedStr==null){
return null;
}
ByteArrayOutputStream out= new ByteArrayOutputStream();
ByteArrayInputStream in=null;
GZIPInputStream ginzip=null;
byte[] compressed=null;
String decompressed = null;
try {
compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
in=new ByteArrayInputStream(compressed);
ginzip=new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed=out.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ginzip != null) {
try {
ginzip.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return decompressed;
}
/**
* 压缩字符串
* @param primStr
* @return
*/
public static String gzip(String primStr) {
if (primStr == null || primStr.length() == 0) {
return primStr;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip=null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(primStr.getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally{
if(gzip!=null){
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
}