字符串加/解密 Base64 & MD5 & S
2017-03-30 本文已影响53人
熊er
/**
* Base64 编码
*/
public static String toBase64(String string) {
byte[] b = null;
String result = null;
try {
b = string.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (b != null) {
result = Base64.encodeToString(b, Base64.DEFAULT);
}
return result;
}
/**
* Base64 解码
*/
public static String fromBase64(String string) {
byte[] b;
String result = null;
if (string != null) {
try {
b = Base64.decode(string, Base64.DEFAULT);
result = new String(b, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
/**
* 字符串 MD5 加密
*/
public static String md5(String string) {
if (string == null) {
return "";
}
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(string.getBytes());
String result = "";
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xFF);
if (temp.length() == 1) {
temp = "0" + temp;
}
result += temp;
}
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
/**
* 字符串 SHA-1 加密
*/
public static String sha1(String string) {
if (string == null) {
return "";
}
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
byte bytes[] = sha1.digest(string.getBytes());
String result = "";
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xFF);
if (temp.length() < 2) {
result += "0";
}
result += temp;
}
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}