CryptoTools加密與解密java
java經常使用的加密算法有MD5(Message Digest algorithm 5,信息摘要算法)算法
BASE64(嚴格地說,屬於編碼格式,而非加密算法) 安全
SHA(Secure Hash Algorithm,安全散列算法)編碼
HMAC(Hash Message Authentication Code,散列消息鑑別碼)加密
CryptoTools (對稱分組式加密)spa
前四種是經常使用的也是基本耳熟的加密算法,這裏主要解釋CryptoTools算法,現將代碼貼與這裏,與你們分享。code
package com.lzjs.lzgdesbgateway.util;對象
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;ip
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class CryptoTools {
private final byte[] DESkey = "lzgdesb@123".getBytes("UTF-8");// 設置密鑰,略去
private final byte[] DESIV = {0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};//
設置向量,略去
private AlgorithmParameterSpec iv = null;// 加密算法的參數接口,IvParameterSpec是它的一個實現
private Key key = null;
public CryptoTools() throws Exception {
DESKeySpec keySpec = new DESKeySpec(DESkey);// 設置密鑰參數
iv = new IvParameterSpec(DESIV);// 設置向量
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 得到密鑰工廠
key = keyFactory.generateSecret(keySpec);// 獲得密鑰對象
}
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 base64Encoder.encode(pasByte);
}
public String decode(String data) throws Exception {
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 = "4132413241241324"; CryptoTools des = new CryptoTools(); System.out.println("加密前的字符:"+test); System.out.println("加密後的字符:"+des.encode(test)); System.out.println("解密後的字符:"+des.decode(des.encode(test))); } catch (Exception e) { e.printStackTrace(); } }}