import java.security.SecureRandom; import java.util.jar.JarEntry; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec;
/** * function:对账号密码进行验证,使用EDS进行加密解密 */ public class DESUtil { /** * EDS的加密解密代码 */ private static final byte[] DES_KEY = { 51, 1, -1, -5, -32, -85, 28, -65,32,52,68 }; public static JsonData encryptBasedDes(String data) { String encryptedData = null; try { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(DES_KEY); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(deskey); // 加密对象 Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 加密,并把字节数组编码成字符串 encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes())); } catch (Exception e) { // log.error("加密错误,错误信息:", e); // throw new RuntimeException("加密错误,错误信息:", e); return JsonData.buildError("加密错误,错误信息",400); } return JsonData.buildSuccess(encryptedData,200); } /** * function:对DES进行解密 * @param cryptData * @return */ public static JsonData decryptBasedDes(String cryptData) { String decryptedData = null; try { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(DES_KEY); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(deskey); // 解密对象 Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key, sr); // 把字符串进行解码,解码为为字节数组,并解密 decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData))); } catch (Exception e) { // throw new RuntimeException("解密错误,错误信息:", e); return JsonData.buildError("解密错误,错误信息",400); } return JsonData.buildSuccess(decryptedData,200); } }
这样就可以直接调用了