Loading... **自定义对称加密方法**:利用线性同余生成器进行十六进制加解密 ```java import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; public class DFEncDecUtilsOld { /** * 获取解密所需要的相关参数 * @param pwd * @return */ private static Map<String, Object> getDecryptMeta(String pwd) { if (pwd == null || "".equals(pwd.trim())) { return null; } StringBuffer prandSb = new StringBuffer(); for (int i = 0; i < pwd.length(); i++) { prandSb.append(Integer.valueOf(pwd.charAt(i))); } String prand = prandSb.toString(); int sPos = (int) Math.floor(prand.length() / 5); StringBuffer sb = new StringBuffer(); for (int i = 1; i <= 5; i++) { try { sb.append(prand.charAt(sPos * i)); } catch (Exception e) { } } int mult = Integer.parseInt(sb.toString()); int incr = (int) Math.ceil(Double.parseDouble(pwd.length() + "") / 2); long modu = (long) (Math.pow(2, 31) - 1); while (prand.length() > 8) { BigDecimal bd1 = new BigDecimal(prand.substring(0, 8)); BigDecimal bd2 = new BigDecimal(prand.substring(8, prand.length())); bd2 = bd2.add(bd1); prand = bd2.toString(); } Double lprand = Double.parseDouble(prand); lprand = (mult * lprand + incr) % modu; Map<String, Object> meta = new HashMap<String, Object>(); meta.put("incr", incr); meta.put("modu", modu); meta.put("mult", mult); meta.put("lprand", lprand); return meta; } /** * 加密 * * @param str * @param pwd * @return */ public static String encrypt(String str, String pwd) { Map<String, Object> meta = getDecryptMeta(pwd); if (null == str || "".equals(str.trim()) || meta == null || meta.isEmpty()) { return null; } int incr = (Integer) meta.get("incr"); int mult = (Integer) meta.get("mult"); long modu = (Long) meta.get("modu"); Double lprand = (Double) meta.get("lprand"); int enc_chr; StringBuffer enc_str = new StringBuffer(); for (int i = 0; i < str.length(); i++) { enc_chr = (Integer.valueOf(str.charAt(i))) ^ ((int) (Math.floor((lprand / modu) * 255))); if (enc_chr < 16) { enc_str.append("0").append(Integer.toHexString(enc_chr)); } else { enc_str.append(Integer.toHexString(enc_chr)); } lprand = (mult * lprand + incr) % modu; } return enc_str.toString(); } /** * 根据meta,解密原加密串 * * @param str * @param pwd * @return */ public static String decrypt(String str, String pwd) { Map<String, Object> meta = getDecryptMeta(pwd); if (null == str || "".equals(str.trim()) || meta == null || meta.isEmpty()) { return null; } int incr = (Integer) meta.get("incr"); int mult = (Integer) meta.get("mult"); long modu = (Long) meta.get("modu"); Double lprand = (Double) meta.get("lprand"); int enc_chr; StringBuffer enc_str = new StringBuffer(); for (int i = 0; i < str.length(); i += 2) { enc_chr = (Integer.parseInt(str.substring(i, i + 2), 16) ^ (int) (Math.floor((lprand / modu) * 255))); enc_str.append((char) (enc_chr)); lprand = (mult * lprand + incr) % modu; } return enc_str.toString(); } ``` © Allow specification reprint Support Appreciate the author AliPayWeChat Like 1 If you think my article is useful to you, please feel free to appreciate