Java DES 加密和解密


DES算法簡介
DES(Data Encryption Standard)是發明最早的最廣泛使用的分組對稱加密算法。DES算法的入口參數有三個:Key、Data、Mode。其中Key為8個字節共64位,是DES算法的工作密鑰;Data也為8個字節64位,是要被加密或被解密的數據;Mode為DES的工作方式,有兩種:加密或解密。

 

項目中的加密和解密工具類:

public class DesUtils {

public final static String DES = "DES";
public static void main(String[] args) throws Exception {
String KEY = "wang!@#$%";

String s1 = DesUtils.encrypt("maechannelopr", KEY);
String s2 = DesUtils.decrypt(s1, KEY);
String s3 = DesUtils.encrypt("maechannel", KEY);
String s4 = DesUtils.decrypt(s3, KEY);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);

}

/**
* Description 根據鍵值進行加密
* 
* @param data
* @param key
* 加密鍵byte數組
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
byte[] bt = encrypt(data.getBytes(), key.getBytes());
String strs = new BASE64Encoder().encode(bt);
return strs;
}

/**
* Description 根據鍵值進行解密
* 
* @param data
* @param key
* 加密鍵byte數組
* @return
* @throws IOException
* @throws Exception
*/
public static String decrypt(String data, String key) throws IOException, Exception {
if (data == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf, key.getBytes());
return new String(bt);
}

/**
* Description 根據鍵值進行加密
* 
* @param data
* @param key
* 加密鍵byte數組
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一個可信任的隨機數源
SecureRandom sr = new SecureRandom();

// 從原始密鑰數據創建DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);

// 創建一個密鑰工廠,然后用它把DESKeySpec轉換成SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);

// Cipher對象實際完成加密操作
Cipher cipher = Cipher.getInstance(DES);

// 用密鑰初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

return cipher.doFinal(data);
}

/**
* Description 根據鍵值進行解密
* 
* @param data
* @param key
* 加密鍵byte數組
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
// 生成一個可信任的隨機數源
SecureRandom sr = new SecureRandom();

// 從原始密鑰數據創建DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);

// 創建一個密鑰工廠,然后用它把DESKeySpec轉換成SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);

// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance(DES);

// 用密鑰初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

return cipher.doFinal(data);
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM