import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import com.sun.crypto.provider.SunJCE;
import java.io.Serializable;
/**
* 提供加密算法,可以對輸入的字符串進(jìn)行加密、解密操作
*/
public class EncryptData
{
byte[] encryptKey;
DESedeKeySpec spec;
SecretKeyFactory keyFactory;
SecretKey theKey;
Cipher cipher;
IvParameterSpec IvParameters;
public EncryptData()
{
try
{
// 檢測是否有 TripleDES 加密的供應(yīng)程序
// 如無,明確地安裝SunJCE 供應(yīng)程序
try{ Cipher c = Cipher.getInstance("DESede"); }
catch (Exception e)
{
System.err.println("Installling SunJCE provider.");
Provider sunjce = new com.sun.crypto.provider.SunJCE();
Security.addProvider(sunjce);
}
// 創(chuàng)建一個(gè)密鑰
encryptKey = "This is a test DESede Key".getBytes();
// 為上一密鑰創(chuàng)建一個(gè)指定的 DESSede key
spec = new DESedeKeySpec(encryptKey);
// 得到 DESSede keys
keyFactory = SecretKeyFactory.getInstance("DESede");
// 生成一個(gè) DESede 密鑰對象
theKey = keyFactory.generateSecret(spec);
// 創(chuàng)建一個(gè) DESede 密碼
cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
// 為 CBC 模式創(chuàng)建一個(gè)用于初始化的 vector 對象
IvParameters =
new IvParameterSpec(new byte[]{12,34,56,78,90,87,65,43} );
}
catch (Exception exc)
{
// 記錄加密或解密操作錯(cuò)誤
}
}
/**
* 加密算法
* @param password 等待加密的密碼
* @return 加密以后的密碼
* @throws Exception
*/
public byte[] encrypt(String password)
{
String encrypted_password = null;
byte[] encrypted_pwd = null;
try
{
// 以加密模式初始化密鑰
cipher.init(Cipher.ENCRYPT_MODE,theKey,IvParameters);
// 加密前的密碼(舊)
byte[] plainttext = password.getBytes();
// 加密密碼
encrypted_pwd = cipher.doFinal(plainttext);
// 轉(zhuǎn)成字符串,得到加密后的密碼(新)
encrypted_password = new String(encrypted_pwd);
}
catch(Exception ex)
{
// 記錄加密錯(cuò)誤
}
return encrypted_pwd;
}
/**
* 解密算法
* @param password 加過密的密碼
* @return 解密后的密碼
*/
public String decrypt(byte[] password)
{
String decrypted_password = null;
try
{
// 以解密模式初始化密鑰
cipher.init(Cipher.DECRYPT_MODE,theKey,IvParameters);
// 構(gòu)造解密前的密碼
byte[] decryptedPassword = password;
// 解密密碼
byte[] decrypted_pwd = cipher.doFinal(decryptedPassword);
// 得到結(jié)果
decrypted_password = new String(decrypted_pwd);
}
catch(Exception ex)
{
// 記錄解密錯(cuò)誤
}
return decrypted_password;
}
}