1.MD5這裡就不做描述,詳細可以查閱後續文章
2.DES 數據加密處理:如下
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class test
{
public static void main(String[] args)
throws UnsupportedEncodingException
{
//待加密內容
String str = “我是中國人”;
//密碼,長度要是8的倍數
String password = “alnton08″;
byte[] result = desCrypto(str.getBytes(), password);
System.out.println(“加密後內容為:” + new String(result));
//直接將如上內容解密
try
{
byte[] decryResult = decrypt(result, password);
System.out.println(“加密前內容為:” + new String(decryResult));
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
/**
* <對字符串進行Des加密,將字符串轉化為字節數組解密>
*/
public static byte[] desCrypto(byte[] datasource, String password)
{
try
{
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(password.getBytes());
//創建一個密匙工廠,然後用它把DESKeySpec轉換成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(“DES”);
SecretKey securekey = keyFactory.generateSecret(desKey);
//Cipher對象實際完成加密操作
Cipher cipher = Cipher.getInstance(“DES”);
//用密匙初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
//現在,獲取數據並加密
//正式執行加密操作
return cipher.doFinal(datasource);
}
catch (Throwable e)
{
e.printStackTrace();
}
return null;
}
/**
* <將加密的密文字節數組轉化為明文字節數組>
*/
public static byte[] decrypt(byte[] src, String password)
throws Exception
{
// DES算法要求有一個可信任的隨機數源
SecureRandom random = new SecureRandom();
// 創建一個DESKeySpec對象
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 創建一個密匙工廠
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(“DES”);
// 將DESKeySpec對象轉換成SecretKey對象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance(“DES”);
// 用密匙初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正開始解密操作
return cipher.doFinal(src);
}
}