Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static final String MD5 = "MD5";
    public static final String SHA1 = "SHA-1";
    public static final String SHA256 = "SHA-256";
    public static final String SHA384 = "SHA-384";
    public static final String SHA512 = "SHA-512";

    public static String getStringDigestEncrypt(String s, String algorithm) {
        return getBytesDigestEncrypt(s.getBytes(), algorithm);
    }

    public static String getBytesDigestEncrypt(byte[] bytes, String algorithm) {
        if (algorithm.equals(MD5) || algorithm.equals(SHA1) || algorithm.equals(SHA256) || algorithm.equals(SHA384)
                || algorithm.equals(SHA512)) {
            MessageDigest digest = null;
            try {
                digest = MessageDigest.getInstance(algorithm);
                digest.update(bytes);
                return bytes2String(digest.digest());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String bytes2String(byte digest[]) {
        String str = "";
        String tempStr = "";
        for (int i = 0; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            } else {
                str += tempStr;
            }
        }
        return str;
    }
}