【Java】分享一個使用DES加密和解密的演算法
分享一個使用DES加密和解密的演算法,當前這個演算法已經應用到專案中:
package com。util;
import java。net。URLDecoder;
import java。net。URLEncoder;
import java。security。Key;
import java。security。spec。AlgorithmParameterSpec;
import javax。crypto。Cipher;
import javax。crypto。SecretKeyFactory;
import javax。crypto。spec。DESKeySpec;
import javax。crypto。spec。IvParameterSpec;
import org。apache。commons。lang3。StringUtils;
import sun。misc。BASE64Decoder;
import sun。misc。BASE64Encoder;
/**
* 加密/解密工具
*/
public class EncrypDES {
private final byte[] DESIV = new byte[] { 0x12, 0x34, 0x56, 120, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef };// 向量
public static final String key_System = “9ba45bfd500642328ec03ad8ef1b6e75”;// 自定義金鑰
private AlgorithmParameterSpec iv = null;// 加密演算法的引數介面
private Key key = null;
private String charset = “utf-8”;//預設編碼
/**
* 初始化
* @param deSkey 金鑰
* @throws Exception
*/
public EncrypDES(String deSkey, String charset) throws Exception {
if (StringUtils。isNotBlank(charset)) {
this。charset = charset;
}
DESKeySpec keySpec = new DESKeySpec(deSkey。getBytes(this。charset));// 設定金鑰引數
iv = new IvParameterSpec(DESIV);// 設定向量
SecretKeyFactory keyFactory = SecretKeyFactory。getInstance(“DES”);// 獲得金鑰工廠
key = keyFactory。generateSecret(keySpec);// 得到金鑰物件
}
/**
* 加密
* @param data
* @return
* @throws Exception
*/
public String encode(String data) throws Exception {
Cipher enCipher = Cipher。getInstance(“DES/CBC/PKCS5Padding”);// 得到加密物件Cipher
enCipher。init(Cipher。ENCRYPT_MODE, key, iv);// 設定工作模式為加密模式,給出金鑰和向量
byte[] pasByte = enCipher。doFinal(data。getBytes(“utf-8”));
BASE64Encoder base64Encoder = new BASE64Encoder();
return URLEncoder。encode(base64Encoder。encode(pasByte));
}
/**
* 解密
* @param data
* @return
* @throws Exception
*/
public String decode(String data) throws Exception {
data=URLDecoder。decode(data);
Cipher deCipher = Cipher。getInstance(“DES/CBC/PKCS5Padding”);
deCipher。init(Cipher。DECRYPT_MODE, key, iv);
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] pasByte = deCipher。doFinal(base64Decoder。decodeBuffer(data));
return new String(pasByte, “UTF-8”);
}
public static void main(String[] args) {
try {
String test = “www。java112。com”;
EncrypDES des = new EncrypDES(EncrypDES。key_System, “utf-8”);
System。out。println(“加密前的字元:” + test);
System。out。println(“加密後的字元:” + des。encode(test));
System。out。println(“解密後的字元:” + des。decode(des。encode(test)));
} catch (Exception e) {
e。printStackTrace();
}
}
}
喜歡這樣文章的可以關注我,我會持續更新,你們的關注是我更新的動力!需要更多java學習資料的也可以私信我!
祝關注我的人都:身體健康,財源廣進,福如東海,壽比南山,早生貴子,從不掉髮!