AzDGCrypt是Azerbaijan Development Group(AzDG)开发的可逆加密算法。最近在研究Discuz4.1.0提供的passport功能。其中用到了AzDGCrypt加解密方法。顺手把他翻译成了java版的。代码中用到了MD5和Base64两个类,这两个算法可以在网上找到相应的java实现。只要稍做修改就可以,所有没有给出代码。
因为我用的discuz是gb2312的码,而java那边用的是utf-8,所有为了解决编码问题,这段代码也给出了一个可选择编码方式的实现。
/**
* AzDGCrypt.java
*
* 2006-03-08
*
*/
package cn.vap.lib;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
/**
* The AzDGCrypt
*
* @author Shell.C
*
*/
public class AzDGCrypt {
/**
* encrypt
*
* @param txt
* @param key
* @return
*/
public static byte[] encrypt(byte[] txt, byte[] key) {
int rand = new Double(Math.random()*32000).intValue();
byte[] encrypt_key = new MD5().getMD5ofStr(rand+"").toLowerCase().getBytes();
byte ctr = 0;
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
for (int i = 0, j = 0; i < txt.length; i++,j+=2) {
ctr = ctr == encrypt_key.length ? 0 : ctr;
byteOut.write(encrypt_key[ctr]);
byteOut.write(txt[i] ^ encrypt_key[ctr++]);
}
return Base64.encodeBytes(encodeKey(byteOut.toByteArray(), key)).getBytes();
}
public static String encrypt(String txt,String key){
return new String(encrypt(txt.getBytes(),key.getBytes()));
}
public static String encrypt(String txt,String key,String encoding){
String str = null;
try{
str = new String(encrypt(txt.getBytes(encoding),key.getBytes()));
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
return str;
}
/**
* decrypt
*
* @param txt
* @param key
* @return
*/
public static byte[] decrypt(byte[] txt, byte[] key) {
txt = encodeKey(Base64.decode(txt, 0, txt.length), key);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
for (int i = 0; i < txt.length; i++) {
byte md5 = txt[i];
byteOut.write(txt[++i] ^ md5);
}
return byteOut.toByteArray();
}
/**
*
* @param txt
* @param key
* @return
*/
public static String decrypt(String txt, String key){
return new String(decrypt(txt.getBytes(),key.getBytes()));
}
/**
*
* @param txt
* @param key
* @return
*/
public static byte[] encodeKey(byte[] txt, byte[] encrypt_key) {
encrypt_key = new MD5().getMD5ofStr(new String(encrypt_key))
.toLowerCase().getBytes();
byte ctr = 0;
byte[] tmp = new byte[txt.length];
//ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
for (int i = 0; i < txt.length; i++) {
ctr = ctr == encrypt_key.length ? 0 : ctr;
tmp[i] = (byte) (txt[i] ^ encrypt_key[ctr++]);
//byteOut.write(txt[i] ^ encrypt_key[ctr++]);
}
return tmp;
}
public static void main(String[] arg) {
String source = "Hello, World!中文";
String key = "1221";
System.out.println("Source : " + source + " Key : " + key);
String encryptTxt = AzDGCrypt.encrypt(source, key,"gbk");
System.out.println("Encypt String : " + encryptTxt);
String decryptTxt = AzDGCrypt.decrypt(encryptTxt, key);
System.out.println("Decypt String : " + decryptTxt);
}
}