加密分為對稱加密和非對稱加密。非對稱加密加密和解密使用不同的密鑰,如RSA;對稱加密使用相同的密鑰加密和解密,如DES。雖然非對稱加密安全性更高,但是計算過程復雜耗時,一般只對關鍵信息(如賬號密碼等)使用,對於非關鍵信息,一般使用對稱加密,如DES。
DES的全稱是Data Encryption Standard,即數據加密標准,不論明文是什麼字符,加密後的密文都是0-F這16個字符組成的字符串。
加密主要代碼如下:
private static byte[] encrypt(byte[] data, byte[] key) throws Exception { SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey securekey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); return cipher.doFinal(data); }
解密主要代碼如下:
private static byte[] decrypt(byte[] data, byte[] key) throws Exception { SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey securekey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, securekey, sr); return cipher.doFinal(data); }