首页 > 代码库 > Java DES 加密和解密

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 =http://www.mamicode.com/= 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);}}