package com.withiter.utils; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.Security; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; /** * @author cross */ public class DesUtils { private static String strDefaultKey = "quhao"; private Cipher encryptCipher = null; private Cipher decryptCipher = null; public static String byteArr2HexStr(byte[] arrB) { int iLen = arrB.length; StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i < iLen; i++) { int intTmp = arrB[i]; while (intTmp < 0) { intTmp = intTmp + 256; } if (intTmp < 16) { sb.append("0"); } sb.append(Integer.toString(intTmp, 16)); } return sb.toString(); } public static byte[] hexStr2ByteArr(String strIn) { byte[] arrB = strIn.getBytes(); int iLen = arrB.length; byte[] arrOut = new byte[iLen / 2]; for (int i = 0; i < iLen; i = i + 2) { String strTmp = new String(arrB, i, 2); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16); } return arrOut; } public DesUtils() { this(strDefaultKey); } public DesUtils(String strKey) { Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes()); try { encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } } public byte[] encrypt(byte[] arrB) throws IllegalBlockSizeException, BadPaddingException { return encryptCipher.doFinal(arrB); } public String encrypt(String strIn) { try { return byteArr2HexStr(encrypt(strIn.getBytes())); } catch (IllegalBlockSizeException e) { e.printStackTrace(); return null; } catch (BadPaddingException e) { e.printStackTrace(); return null; } } public byte[] decrypt(byte[] arrB) throws IllegalBlockSizeException, BadPaddingException { return decryptCipher.doFinal(arrB); } public String decrypt(String strIn) { try { return new String(decrypt(hexStr2ByteArr(strIn))); } catch (IllegalBlockSizeException e) { e.printStackTrace(); return null; } catch (BadPaddingException e) { e.printStackTrace(); return null; } } private Key getKey(byte[] arrBTmp) { byte[] arrB = new byte[8]; for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key; } }