/*
* 加密
*/
public static String EncryptString(String strText, String sKey) {
// MD5加密
// String md5s = EncryptMD5.getMD5(strText);
try {
SecureRandom random = new SecureRandom();
byte[] bkey =(sKey.substring(0,8)).getBytes();
DESKeySpec deskey = new DESKeySpec(bkey);
// 创建一个密钥工厂,然后用它把DESKeyspec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(deskey);
// cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
// cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
// 用密钥初化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
// 现在,获取数据并加密
// // 正式执行加密操作
// String str = md5s + strText;
byte[] t = strText.getBytes("UTF-8");
byte[] bResult = cipher.doFinal(t);
// 1、加密完byte[] 后,需要将加密了的byte[] 转换成base64保存,如:
// BASE64Encoder base64encoder = new BASE64Encoder();
// String encode=base64encoder.encode(bytes);
return base64Eecoder.encode(bResult);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
/*
* 解密
*/
public static String DecryptString(String strText, String sKey) {
// DES算法要求有一个可信任的随机数源
SecureRandom random = new SecureRandom();
// 创建一个DesKeySpec对象
byte[] bkey = (sKey.substring(0,8)).getBytes();
DESKeySpec desKey = null;
try {
desKey = new DESKeySpec(bkey);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
// 创建一个密钥工厂
SecretKeyFactory keyFactory = null;
try {
keyFactory = SecretKeyFactory.getInstance("DES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将DESKeySpec对象转换成SecretKey对象
SecretKey secreKey = null;
try {
secreKey = keyFactory.generateSecret(desKey);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
// Cipher对象实际完成解密操作
Cipher cipher = null;
try {
cipher = Cipher.getInstance("DES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
// 用密钥初始化Cipher对象
try {
cipher.init(Cipher.DECRYPT_MODE, secreKey, random);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
// 真正开始解密
// 2、解密前,需要将加密后的字符串从base64转回来再解密,如:
// BASE64Decoder base64decoder = new BASE64Decoder();
// byte[] encodeByte = base64decoder.decodeBuffer(s);
byte[] encodeByte;
byte[] b;
try {
encodeByte = base64Decoder.decodeBuffer(new String( strText.getBytes(),"UTF-8"));
b = cipher.doFinal(encodeByte);
String s = new String(b, "UTF-8");
return s;
} catch (IOException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}