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); } }