代码片段--加密

MD5加密代码

public static String md5(String value) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] byteDigest = md.digest(value.getBytes(StandardCharsets.UTF_8));
        StringBuffer sb = new StringBuffer();
        for (byte b : byteDigest) {
            sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    } catch (NoSuchAlgorithmException e) {
        Logger.getLogger("").info("MD5加密失败!");
    }
    return "";
}

SHA-1加密代码

public static String SHA1(final String value) {
    MessageDigest digest;
    try {
        digest = java.security.MessageDigest.getInstance("SHA-1");
        digest.update(value.getBytes());
        byte messageDigest[] = digest.digest();
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++) {
            String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }
        return hexString.toString();
    } catch (NoSuchAlgorithmException e) {
        Logger.getLogger("").info("SHA1 安全哈希算法加密失败!");
    }
    return "";
}

测试

public static void main(String args[]) {
    String md5 = md5("This a md5 test!");
    System.out.println(md5); // fdedaafb043d41ff06b6ef249ef53be9

    String sha1 = SHA1("This a sha1 test!");
    System.out.println(sha1); // 46a7ff34d0625f5562093f67a6e4fd68e9d7b352
}

你可能感兴趣的:(代码片段--加密)