欢迎进入java社区论坛,与200万技术人员互动交流 >>进入
日常开放中 平台中通常不会只有单一的环境,因此跨平台的通讯 通常会使用标准的aes,des等加密规则
公司的项目开发中 遇到了java和php的加密解密跨平台的问题 经过多方查找资料以及研究找出一个通用的基础加解密方案如下
1:java代码 (3des版)
import javax.crypto.cipher;
import javax.crypto.secretkey;
import javax.crypto.spec.secretkeyspec;
import org.apache.log4j.logger;
import sun.misc.base64decoder;
import sun.misc.base64encoder;
/**
* java版3des加密解密,适用于php版3des加密解密(php语言开发的mcrypt_3des算法、mcrypt_mode_ecb模式、pkcs7填充方式)
* @author g007n
*/
public class desbase64tool {
private static secretkey secretkey = null;//key对象
private static cipher cipher = null; //私?加密对象cipher
private static string keystring = aklmu89d3fchikhkymma6fie;//密钥
private static logger log = logger.getrootlogger();
static{
try {
secretkey = new secretkeyspec(keystring.getbytes(), desede);//获得密钥
/*获得一个私?加密类cipher,desede是算法,ecb是加密模式,pkcs5padding是填充方式*/
cipher = cipher.getinstance(desede/ecb/pkcs5padding);
} catch (exception e) {
log.error(e.getmessage(), e);
}
}
/**
* 加密
* @param message
* @return
*/
public static string desencrypt(string message) {
string result = ; //des加密字符串
string newresult = ;//去掉换行符后的加密字符串
try {
cipher.init(cipher.encrypt_mode, secretkey); //设置工作模式为加密模式,给出密钥
byte[] resultbytes = cipher.dofinal(message.getbytes(utf-8)); //正式执行加密操作
base64encoder enc = new base64encoder();
result = enc.encode(resultbytes);//进行base64编码
newresult = filter(result); //去掉加密串中的换行符
} catch (exception e) {
log.error(e.getmessage(), e);
}
return newresult;
}
/**
* 解密
* @param message
* @return
* @throws exception
*/
public static string desdecrypt(string message) throws exception {
string result = ;
try {
base64decoder dec = new base64decoder();
byte[] messagebytes = dec.decodebuffer(message); //进行base64编码
cipher.init(cipher.decrypt_mode, secretkey); //设置工作模式为解密模式,给出密钥
byte[] resultbytes = cipher.dofinal(messagebytes);//正式执行解密操作
result = new string(resultbytes,utf-8);
} catch (exception e) {
e.printstacktrace();
}
return result;
}
/**
* 去掉加密字符串换行符
* @param str
* @return
*/
public static string filter(string str) {
string output = ;
stringbuffer sb = new stringbuffer();
for (int i = 0; i
int asc = str.charat(i);
if (asc != 10 && asc != 13) {
sb.append(str.subsequence(i, i+1));
}
}
output = new string(sb);
return output;
}
/**
* 加密解密测试
* @param args
*/
public static void main(string[] args) {
try {
string strtext = hello world!;
string deseresult = desencrypt(strtext);//加密
system.out.println(加密结果:+deseresult);
string desdresult = desdecrypt(deseresult);//解密
system.out.println(解密结果:+desdresult);
} catch (exception e) {
e.printstacktrace();
}
}
}
[1] [2] [3]
