DES加密
加密分为对称加密和非对称加密。非对称加密加密和解密使用不同的密钥,如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); }