/** * 24位秘钥 **/ private static final int DES_LENGTH = 24;
/** * Description: 加密 * * @param content * @param desKey * @return */ public static String encrypt(String content, String desKey) { String str = null; try { if(StringUtil.isEmpty(desKey) || DES_LENGTH != desKey.length()) { log.error("3des key's length must be 24"); return ""; } if(StringUtil.isEmpty(content)) { return ""; } SecretKeySpec key = new SecretKeySpec(desKey.getBytes("utf-8"), "DESede"); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptBytes = cipher.doFinal(content.getBytes("utf-8")); str = new BASE64Encoder().encode(encryptBytes); }catch (Exception e) { log.error("加密失败!", e); } return str; }
/** * Description: 解密 * * @param content * @param desKey * @return */ public static String decrypt(String content, String desKey) { try { if(StringUtil.isEmpty(desKey) || DES_LENGTH != desKey.length()) { log.error("3des key's length must be 24"); return ""; } if(StringUtil.isEmpty(content)) { return ""; } byte[] decryptBytes = null; decryptBytes = new BASE64Decoder().decodeBuffer(content); // decryptBytes = new // BASE64Decoder().decodeBuffer(decryptBytes.toString()); SecretKeySpec key = new SecretKeySpec(desKey.getBytes("utf-8"), "DESede"); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.DECRYPT_MODE, key); return new String(cipher.doFinal(decryptBytes), "utf-8"); }catch (Exception e) { log.error("解密失败!", e); } return null; }
/** * * 签名处理 * * @param key * @param content * @param signType * @return */ public static String sign(String key, String content, String signType) { String digestResult = null; if(SHA_256_HEX.equalsIgnoreCase(signType)) { digestResult = DigestUtils.sha256Hex(key + content); } return digestResult; }
DigestUtils为org.apache.commons.codec.digest包下的工具类。