數據加密標準(英語:Data Encryption Standard,縮寫為 DES)是一種對稱密鑰加密塊密碼算法,1976年被美國聯邦政府的國家標準局確定為聯邦資料處理標準(FIPS),隨后在國際上廣泛流傳開來。它基于使用56位密鑰的對稱算法。這個算法因為包含一些機密設計元素,相對短的密鑰長度以及懷疑內含美國國家安全局(NSA)的后門而在開始時有爭議,DES因此受到了強烈的學院派式的審查,并以此推動了現代的塊密碼及其密碼分析的發展。??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ---維基百科?
一、DES簡介
1、DES:數據加密標準,是對稱加密算法領域中的典型算法
2、特點:秘鑰偏短(56位),生命周期短
3、JDK內部提供了算法的實現
二、相關代碼
1、生成密鑰
public static byte[] getKey() throws Exception
{
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
keyGen.init(56);
SecretKey secretKey = keyGen.generateKey();
return secretKey.getEncoded();
}
2、DES加密
/**
* DES加密
* @param data 要加密的原始數據
* @param key? 密鑰
* @return 加密后的數據
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception
{
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(data);
}
3、DES解密
/**
* DES解密
* @param data 要解密的數據
* @param key? 密鑰
* @return 解密后的數據
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception
{
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
}
4、字節轉十六進制
/**
* 字節轉十六進制
*
* @param resultBytes
*? ? ? ? ? ? 輸入源
* @return 十六進制字符串
*/
public static String fromBytesToHex(byte[] resultBytes) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < resultBytes.length; i++) {
if (Integer.toHexString(0xFF & resultBytes[i]).length() == 1) {
builder.append("0").append(Integer.toHexString(0xFF & resultBytes[i]));
} else {
builder.append(Integer.toHexString(0xFF & resultBytes[i]));
}
}
return builder.toString();
}