导言:
由于数据的安全性,所以需要进行数据加密和解密处理,当然有很多算法,但其中MD5不可逆,3DES(DESede)是DES的升级版,所以本文只是笔记
步骤:
1:MD5加密,很简单,直接将需要加密的字符串传入即可.
public static String MD5Tool(String str) {
if (TextUtils.isEmpty(str)) {
return "";
}
try {
MessageDigest mDigest = MessageDigest.getInstance("MD5");
byte[] bytes = mDigest.digest(str.getBytes());
String result = "";
for (byte bt : bytes) {
String temp = Integer.toHexString(bt & 0xff);
if (temp.length() == 1) {
temp = "0" + temp;
}
result += temp;
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
2:3DES重要加密解密类
public class DES3Util {
private static final String TYPE = "DESede";
//加密
public static byte[] encryptMode(byte[] keybyte, byte[] src) {
try {
SecretKey deskey = new SecretKeySpec(keybyte, TYPE);
Cipher c1 = Cipher.getInstance(TYPE);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
//解密
public static byte[] decryptMode(byte[] keybyte, byte[] src) {
try {
SecretKey deskey = new SecretKeySpec(keybyte, TYPE);
Cipher c1 = Cipher.getInstance(TYPE);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
//byte->hexString
public static 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();
}
//hexString->byte
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
3:使用3DES加密解密样例
//三个不同秘钥
String key = "B1B2B3B4B5B6B7B8" + "A1A2A3A4A5A6A7A8" + "A1B2A3A4A5A6A7F8";
Sting src="[email protected]";
//加密
String encryResult = byte2hex(encryptMode(hexStringToBytes(key), src.getBytes("UTF-8")));
//解密
String decryptResult = new String(decryptMode(hexStringToBytes(key), hexStringToBytes(encryResult)), "UTF-8");
结束