在java中调用sun公司提供的DES加密解密算法时需要使用到$JAVA_HOME/jre/lib/目录下如下的个jar包
jcejar
security/US_export_policyjar
security/local_policyjar
ext/sunjce_providerjar
Java运行时会自动加载这些包因此对于带main函数的应用程序不需要设置到CLASSPATH环境变量中对于WEB应用不需要把这些包加到WEBINF/lib目录下
以下是java中调用sun公司提供的DES加密解密算法的样本代码
/*字符串 DESede(DES) 加密*/
import javasecurity*;
import javaxcrypto*;
import javaxcryptospecSecretKeySpec;
public class ThreeDes {
private static final String Algorithm = DESede; //定义 加密算法可用 DESDESedeBlowfish
//keybyte为加密密钥长度为字节
//src为被加密的数据缓沖区(源)
public static byte[] encryptMode(byte[] keybyte byte[] src) {
try {
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte Algorithm);
//加密
Cipher c = CiphergetInstance(Algorithm);
cinit(CipherENCRYPT_MODE deskey);
return cdoFinal(src);
}
catch (javasecurityNoSuchAlgorithmException e) {
eprintStackTrace();
}
catch (javaxcryptoNoSuchPaddingException e) {
eprintStackTrace();
}
catch (javalangException e) {
eprintStackTrace();
}
return null;
}
//keybyte为加密密钥长度为字节
//src为加密后的缓沖区
public static byte[] decryptMode(byte[] keybyte byte[] src) {
try {
//生成密钥
SecretKey deskey = new SecretKeySpec(keybyte Algorithm);
//解密
Cipher c = CiphergetInstance(Algorithm);
cinit(CipherDECRYPT_MODE deskey);
return cdoFinal(src);
}
catch (javasecurityNoSuchAlgorithmException e) {
eprintStackTrace();
}
catch (javaxcryptoNoSuchPaddingException e) {
eprintStackTrace();
}
catch (javalangException e) {
eprintStackTrace();
}
return null;
}
//转换成十六进制字符串
public static String bytehex(byte[] b) {
String hs=;
String stmp=;
for (int n=;n<blength;n++) {
stmp=(javalangIntegertoHexString(b[n] & XFF));
if (stmplength()==) hs=hs++stmp;
else hs=hs+stmp;
if (n<blength) hs=hs+:;
}
return hstoUpperCase();
}
public static void main(String[] args){
//添加新安全算法如果用JCE就要把它添加进去
SecurityaddProvider(new comsuncryptoproviderSunJCE());
final byte[] keyBytes = {x x xF x
(byte)x x x x x x x x
(byte)xCB (byte)xDD x x x x x
(byte)x x x x (byte)xE
}; //字节的密钥
String szSrc = This is a DES test 测试;
Systemoutprintln(加密前的字符串: + szSrc);
byte[] encoded = encryptMode(keyBytes szSrcgetBytes());
Systemoutprintln(加密后的字符串: + new String(encoded));
byte[] srcBytes = decryptMode(keyBytes encoded);
Systemoutprintln(解密后的字符串: + (new String(srcBytes)));
}
}