JAVA BASE64 & 字符串消息摘要

/**
 * 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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容