String, file, stream MD5 encryption

Keywords: SHA1 SSL Java

Article catalog

MD5 introduction

MD5 message digest algorithm * * (English: MD5 message digest algorithm), a widely used cryptographic hash function, can generate a 128 bit (16 byte) hash value to ensure the integrity and consistency of information transmission. MD5 was designed by Ronald Lin Rivest, an American cryptographer, and was released in 1992 to replace MD4 algorithm. The program of this algorithm is standardized in RFC 1321 standard. After 1996, the algorithm has been proved to be weak and can be cracked. For data requiring high security, experts generally recommend using other algorithms, such as SHA-2. In 2004, it was proved that MD5 algorithm can not prevent collision, so it is not suitable for security authentication, such as SSL public key authentication or digital signature.

use

Here is a java tool class directly. You can call the method directly. Some comments are also available

public class MD5 {
    // First, initialize a character array to store each hexadecimal character
    private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * Get the MD5 value of a string
     * 
     * @param input String entered
     * @return MD5 value of input string
     * 
     */
    public static String md5(String input) {
        if (input == null)
            return null;

        try {
            // Get an MD5 converter (if you want to change SHA1 parameter to "SHA1")
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // The input string is converted to a byte array
            byte[] inputByteArray = new byte[0];
            try {
                inputByteArray = input.getBytes("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // inputByteArray is an array of bytes converted from an input string
            messageDigest.update(inputByteArray);
            // Convert and return the result, which is also a byte array, containing 16 elements
            byte[] resultByteArray = messageDigest.digest();
            // Character array conversion to string return
            return byteArrayToHex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * Get MD5 value of file
     * 
     * @param file
     * @return
     */
    public static String md5(File file) {
        try {
            if (!file.isFile()) {
                System.err.println("file" + file.getAbsolutePath() + "Does not exist or is not a file");
                return null;
            }

            FileInputStream in = new FileInputStream(file);

            String result = md5(in);

            in.close();

            return result;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String md5(InputStream in) {

        try {
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");

            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = in.read(buffer)) != -1) {
                messagedigest.update(buffer, 0, read);
            }

            in.close();

            String result = byteArrayToHex(messagedigest.digest());

            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String byteArrayToHex(byte[] byteArray) {
        // new an array of characters, which is used to form the result string (explain: a byte is an eight bit binary, that is, two hexadecimal characters (the 8th power of 2 is equal to the 2nd power of 16))
        char[] resultCharArray = new char[byteArray.length * 2];
        // Traverse byte array, convert to character and put it into character array through bit operation (high efficiency of bit operation)
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }

        // Character array combined into string return
        return new String(resultCharArray);

    }

}

Posted by Madzz on Thu, 21 May 2020 07:47:29 -0700