數(shù)據(jù)加密標(biāo)準(zhǔn)(英語(yǔ):Data Encryption Standard,縮寫為 DES)是一種對(duì)稱密鑰加密塊密碼算法,1976年被美國(guó)聯(lián)邦政府的國(guó)家標(biāo)準(zhǔn)局確定為聯(lián)邦資料處理標(biāo)準(zhǔn)(FIPS),隨后在國(guó)際上廣泛流傳開來(lái)。它基于使用56位密鑰的對(duì)稱算法。這個(gè)算法因?yàn)榘恍C(jī)密設(shè)計(jì)元素,相對(duì)短的密鑰長(zhǎng)度以及懷疑內(nèi)含美國(guó)國(guó)家安全局(NSA)的后門而在開始時(shí)有爭(zhēng)議,DES因此受到了強(qiáng)烈的學(xué)院派式的審查,并以此推動(dòng)了現(xiàn)代的塊密碼及其密碼分析的發(fā)展。??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ---維基百科?
一、DES簡(jiǎn)介
1、DES:數(shù)據(jù)加密標(biāo)準(zhǔn),是對(duì)稱加密算法領(lǐng)域中的典型算法
2、特點(diǎn):秘鑰偏短(56位),生命周期短
3、JDK內(nèi)部提供了算法的實(shí)現(xiàn)
二、相關(guān)代碼
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 要加密的原始數(shù)據(jù)
* @param key? 密鑰
* @return 加密后的數(shù)據(jù)
* @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 要解密的數(shù)據(jù)
* @param key? 密鑰
* @return 解密后的數(shù)據(jù)
* @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、字節(jié)轉(zhuǎn)十六進(jìn)制
/**
* 字節(jié)轉(zhuǎn)十六進(jìn)制
*
* @param resultBytes
*? ? ? ? ? ? 輸入源
* @return 十六進(jìn)制字符串
*/
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();
}