熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

Java中3DES加密解密調用示例

2022-06-13   來源: JSP教程 

  在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)));
}
}


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19363.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.