/**
* 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;
}
/**
* 字符串摘要
*
* @author gavin.xiong 2018/8/24
*/
public class MDer {
public static String MD2 = "MD2";
public static String MD5 = "MD5";
public static String SHA1 = "SHA-1";
public static String SHA224 = "SHA-224";
public static String SHA256 = "SHA-256";
public static String SHA384 = "SHA-384";
public static String SHA512 = "SHA-512";
private static char[] sHex = "0123456789ABCDEF".toCharArray();
public static String digest(String algorithm, String input) {
return digest(algorithm, input, null);
}
public static String digest(String algorithm, String input, String salt) {
if (input == null) return "";
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
if (salt != null) digest.update(salt.getBytes());
byte[] bytes = digest.digest(input.getBytes());
return bytes2Hex(bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
private static String bytes2Hex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
int v = bytes[i] & 0xFF;
hexChars[i * 2] = sHex[v >>> 4];
hexChars[i * 2 + 1] = sHex[v & 0x0F];
}
return new String(hexChars);
}
}