欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[J2SE]Java中3DES加密解密调用示例

程序员文章站 2023-12-04 10:33:58
jce.jar security/us_export_policy.jar security/local_policy.jar ext/sunjce_provider.ja...
jce.jar
security/us_export_policy.jar
security/local_policy.jar
ext/sunjce_provider.jar
java运行时会自动加载这些包,因此对于带main函数的应用程序不需要设置到classpath环境变量中。对于web应用,不需要把这些包加到web-inf/lib目录下。
以下是java中调用sun公司提供的3des加密解密算法的样本代码:
复制代码 代码如下:

/*字符串 desede(3des) 加密*/
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.secretkeyspec;
public class threedes {
private static final string algorithm = "desede"; //定义 加密算法,可用 des,desede,blowfish

//keybyte为加密密钥,长度为24字节
//src为被加密的数据缓冲区(源)
public static byte[] encryptmode(byte[] keybyte, byte[] src) {
try {
//生成密钥
secretkey deskey = new secretkeyspec(keybyte, algorithm);
//加密
cipher c1 = cipher.getinstance(algorithm);
c1.init(cipher.encrypt_mode, deskey);
return c1.dofinal(src);
}
catch (java.security.nosuchalgorithmexception e1) {
e1.printstacktrace();
}
catch (javax.crypto.nosuchpaddingexception e2) {
e2.printstacktrace();
}
catch (java.lang.exception e3) {
e3.printstacktrace();
}
return null;
}

//keybyte为加密密钥,长度为24字节
//src为加密后的缓冲区
public static byte[] decryptmode(byte[] keybyte, byte[] src) {
try {
//生成密钥
secretkey deskey = new secretkeyspec(keybyte, algorithm);
//解密
cipher c1 = cipher.getinstance(algorithm);
c1.init(cipher.decrypt_mode, deskey);
return c1.dofinal(src);
}
catch (java.security.nosuchalgorithmexception e1) {
e1.printstacktrace();
}
catch (javax.crypto.nosuchpaddingexception e2) {
e2.printstacktrace();
}
catch (java.lang.exception e3) {
e3.printstacktrace();
}
return null;
}

//转换成十六进制字符串
public static string byte2hex(byte[] b) {
string hs="";
string stmp="";
for (int n=0;n<b.length;n++) {
stmp=(java.lang.integer.tohexstring(b[n] & 0xff));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
if (n<b.length-1) hs=hs+":";
}
return hs.touppercase();
}
public static void main(string[] args){

//添加新安全算法,如果用jce就要把它添加进去
security.addprovider(new com.sun.crypto.provider.sunjce());
final byte[] keybytes = {0x11, 0x22, 0x4f, 0x58,
(byte)0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51,
(byte)0xcb, (byte)0xdd, 0x55, 0x66, 0x77, 0x29, 0x74,
(byte)0x98, 0x30, 0x40, 0x36, (byte)0xe2
}; //24字节的密钥

string szsrc = "this is a 3des test. 测试";
system.out.println("加密前的字符串:" + szsrc);

byte[] encoded = encryptmode(keybytes, szsrc.getbytes());
system.out.println("加密后的字符串:" + new string(encoded));

byte[] srcbytes = decryptmode(keybytes, encoded);
system.out.println("解密后的字符串:" + (new string(srcbytes)));
}
}