package com.xiucaike.common; import java.security.MessageDigest; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.apache.log4j.Logger; import org.junit.Test; import sun.misc.BASE64Encoder;/**
-
@author fnyexx
-
加密、类型转换工具
*/
@SuppressWarnings("restriction")
public class UtilCrpts {private static final Logger logger = Logger.getLogger(UtilCrpts.class);
/** 定义 加密算法,可用 DES,DESede,Blowfish- 默认 DES*/
private String Algorithm ="DES";public String getAlgorithm() {
return Algorithm;
}public void setAlgorithm(String algorithm) {
Algorithm = algorithm;
}/** 生成密钥,随机生成 * @return byte[] 返回生成的密钥 */ public String createSecretKey() { KeyGenerator keygen = null; try { keygen = KeyGenerator.getInstance(Algorithm); } catch (Exception e) { logger.error("NoSuchAlgorithmException!"); } SecretKey deskey = keygen.generateKey(); return byte2hex(deskey.getEncoded()); } /** * 将指定的数据根据提供的密钥进行加密 * @param input 需要加密的数据 * @param key 密钥 * @return byte[] 加密后的数据 * @throws Exception */ public byte[] encryptData(String input, String key) { SecretKey deskey = new javax.crypto.spec.SecretKeySpec(stringToByte(key.replace(":", "")), Algorithm); Cipher c1 = null; byte[] cipherByte = null; try { c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.ENCRYPT_MODE, deskey); cipherByte = c1.doFinal(input.getBytes()); } catch (Exception e) { logger.error("error!"); } return cipherByte; } /** * 将给定的已加密的数据通过指定的密钥进行解密 * @param input 待解密的数据 * @param key 密钥 * @return byte[] 解密后的数据 * @throws UnsupportedEncodingException * @throws Exception */ public String decryptData(String input, String key) { SecretKey deskey = new javax.crypto.spec.SecretKeySpec(stringToByte(key.replace(":", "")), Algorithm); Cipher c1 = null; byte[] clearByte = null; String decryptStr = null; try { c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.DECRYPT_MODE, deskey); clearByte = c1.doFinal(stringToByte(input.replace(":", ""))); decryptStr = new String(clearByte,"utf-8"); } catch (Exception e) { logger.error("error"); } return decryptStr; } /** * 对密码进行MD5加密(非对称加密,不能解密,适用于密码匹配) * @param : String 原始密码 * @return: String 密码密文 */ public String MD5Encrypt(String pwd){ MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { logger.error("NoSuchAlgorithmException!"); } md.update(pwd.getBytes()); byte[] result = md.digest(); return byteToString(result); } /** * 字节码转换成16进制字符串 * @param byte[]b 输入要转换的字节码 * @return String 返回转换后的16进制字符串 */ public String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) hs = hs + "0" + stmp; else hs = hs + stmp; if (n < b.length - 1) hs = hs + ":"; } return hs.toUpperCase(); } /** * 16进制字符串转换为byte数组 "1212"={12,12} * @param strIn * 需要转换的字符串 * @return 转换后的byte数组 * @throws IllegalArgumentException */ public byte[] stringToByte(String hex) throws IllegalArgumentException { if (hex.length() % 2 != 0) { throw new IllegalArgumentException(); } char[] arr = hex.toCharArray(); byte[] b = new byte[hex.length() / 2]; for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) { String swap = "" + arr[i++] + arr[i]; int byteint = Integer.parseInt(swap, 16) & 0xFF; b[j] = new Integer(byteint).byteValue(); } return b; } /** * 二进制 byte[] 转字符串 {12,12}="1212" * @param : byte[] * @return: String * @throws AppException */ public String byteToString(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) { hs = hs + "0" + stmp; } else { hs = hs + stmp; } if (n < (b.length - 1)) { hs = hs + ""; } } return hs; } /** * int类型转换为byte[]类型 * @param input 待转换的int值 * @return byte[] */ public byte[] intTobyte(int input) { byte[] output = new byte[4]; output[0] = (byte) (input & 0xff); output[1] = (byte) ((input >> 8) & 0xff); output[2] = (byte) ((input >> 16) & 0xff); output[3] = (byte) (input >>> 24); return output; } /** * byte[]类型转换为int类型 * @param input 待转换的byte值 * @return int */ public int byteToint(byte[] input) { int output = 0; if (input.length != 4) { logger.error("error!"); } output = (input[0] & 0xff) | ((input[1] << 8) & 0xff00) | ((input[2] << 24) >>> 8) | (input[3] << 24); return output; } /** * 字节数组使用Base64进行编码 * @param value 待编码的字节数组 * @return 使用Base64进行编码的字节数组 */ public String encdoeStrUsingBase64(byte[] value){ String encodeTxt = ""; if( value!=null && value.length>0 ){ encodeTxt= new BASE64Encoder().encode(value); } return encodeTxt; } //DES测试 DESede,Blowfish操作一样 @Test public void test(){ String key = createSecretKey(); String text = "123asdf んぁ”●☆我是好人/.,"; String crpt = byte2hex(encryptData(text , key)); System.out.println("生成KEY:" + key); System.out.println("末加密原文 :" + text); System.out.println("MD5加密后密文:" + MD5Encrypt(text)); System.out.println("DES加密后密文:" + crpt); System.out.println("DES解密后的原文:" + decryptData(crpt, key)); }
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于