有关信息加密解密--java
是这样,最近有一个关于秒杀的项目,为了防止一些用户,利用时间信息,刷接口,所以需要对时间进行加密之后传输,当然只是加密是不行的,需要有对应的解密,不然,自己也无法获取时间信息,话不多说,上代码。
/** * DES加密 工具类 * @Author yanjun.hou * @Date 2021/10/27 19:14 */ public class DESUtils { /** * 加解密对应的key */ public final static String KEY = "weqeqwasd21ewsdfsdfa"; /** * DES加密 * */ public static String encrypt(String data, String key) { String encryptedData = null; try { // 随机数源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(key.getBytes()); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(deskey); // 加密对象 Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr); // 加密,并把字节数组编码成字符串 encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes())); } catch (Exception e) { throw new RuntimeException("加密错误,错误信息:", e); } return encryptedData; } /** * DES解密 * */ protected static String decrypt(String cryptData,String key) { String decryptedData = null; try { // 随机数源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(key.getBytes()); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(deskey); // 解密对象 Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, secretKey, sr); // 把字符串解码为字节数组并解密 decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData))); } catch (Exception e) { throw new RuntimeException("解密错误,错误信息:", e); } return decryptedData; } }