加密解密种之二
加密解密类之二
加密实例:
/** * 3DES 解密(byte[]). */ private static byte[] desDecrypt(SecretKey key, byte[] crypt){ try { Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(crypt); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 生成3DES密钥. * @param key_byte seed key * @return SecretKey Generated DES key */ private static SecretKey genDESKey(byte[] key_byte) { return new SecretKeySpec(key_byte, "DESede"); } /** * 拼凑或者截取制定长度的字符串 * @param key * @param max * @return */ private static String getLimStr(String key,int max) { if(null==key){ key = ""; } int keyLength=key.getBytes().length; if(keyLength==max){ return key; } //填充 StringBuffer keyB = new StringBuffer(key); if(keyLength<max){ for(int i=0;i<max-keyLength;i++){ keyB.append("0"); } } key = keyB.toString(); String str = ""; int i = 0; while (i <key.length() && (str+key.charAt(i)).getBytes().length<=max) { str += key.charAt(i); i++; } return str; } /** * byte数组转16进制字符串 * @param b * @return */ private static String byteArrayToHexString(byte b[]) { StringBuffer result = new StringBuffer(); for (int i = 0; i < b.length; i++) result.append( byteToHexString(b[i])); return result.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) n = 256 + n; int d1 = n / 16; int d2 = n % 16; return hexCode[d1] + hexCode[d2]; } static public String hexCode[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" }; private static byte[] hexStringToBytes(String src){ byte[] ret = new byte[src.length()/2]; byte[] tmp = src.getBytes(); for(int i=0; i<src.length()/2; i++){ ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]); } return ret; } /* 将两个ASCII字符合成一个字节; * 如:"EF"--> 0xEF * @param src0 byte * @param src1 byte * @return byte */ private static byte uniteBytes(byte src0, byte src1) { byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue(); _b0 = (byte)(_b0 << 4); byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue(); byte ret = (byte)(_b0 ^ _b1); return ret; } public static void main(String[] args) { System.out.println(encrypt("wmba")); System.out.println(decrypt("41666AFABEC36AC9")); }
加密实例:
result = SecurityUtil.encrypt(((EsbAdminUserInfo)getForm()).getPassWord());