package com.fr.plugin.tools; import com.fanruan.api.log.LogKit; import com.fr.plugin.UASSLOGINConfig; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; /** * */ public class ToolDES { //public final static String PRIVACY_KEY = WebContant.DES_PRIVACYKEY; public final static String PRIVACY_KEY; private static final String Algorithm = "DESede"; // 定义 private static final String encoding = "UTF8"; // 密钥 private static byte[] keyBytes = null; static { // String temp = "chinamobileimpgwandother" ; PRIVACY_KEY = UASSLOGINConfig.getInstance().getSecret(); keyBytes = UASSLOGINConfig.getInstance().getSecret().getBytes(StandardCharsets.UTF_8); } // keybyte为加密密钥,长度为24字节 // src为被加密的数据缓冲区(源) public static byte[] encryptMode(byte[] keybyte, byte[] src) { try { // 生成密钥 SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); // 加密 Cipher c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.ENCRYPT_MODE, deskey); return c1.doFinal(src); } catch (java.lang.Exception e) { LogKit.error("", e); } return null; } // keybyte为加密密钥,长度为24字节 // src为加密后的缓冲区 public static byte[] decryptMode(byte[] keybyte, byte[] src) throws Exception { // 生成密钥 SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); // 解密 Cipher c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.DECRYPT_MODE, deskey); return c1.doFinal(src); } // 转换成十六进制字符串 private static String byte2hexString(byte[] bytes) { StringBuffer buf = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { if (((int) bytes[i] & 0xff) < 0x10) { buf.append("0"); } buf.append(Long.toString((int) bytes[i] & 0xff, 16)); } return buf.toString(); } // 将十六进制字符串byte数组 private static byte[] hexString2byte(String hexString) { if (hexString == null || hexString.length() % 2 != 0) { return null; } byte[] hanzi = new byte[hexString.length() / 2]; for (int i = 0; i < hexString.length(); i += 2) { hanzi[i / 2] = (byte) (Integer.parseInt(hexString.substring(i, i + 2), 16) & 0xff); } return hanzi; } /** * 加密字符串 * * @param src 源字符串 * @return 加密后的字符串 */ public static String encrypt(String src) { String key = PRIVACY_KEY; String result = null; if (src == null) { return result; } try { EncryptTool ent = new EncryptTool(); // 加密字符串 LogKit.debug("加密字符串:" + ent); result = ent.encryptString(src, key); } catch (Exception e) { LogKit.error("Exception occurred while encrypting [ " + src + " ] ,key[" + key + "],", e); return null; } return result; } public static byte[] getKeyBytes(String key) { if (key != null && "".equals(key)) { key = PRIVACY_KEY; } if (key != null) { keyBytes = key.getBytes(); } return keyBytes; } }