vuhung3990
8/31/2015 - 9:39 AM

calculate SHA1 of string ( cannot revert )

calculate SHA1 of string ( cannot revert )

/**
     * calculate SHA1 of string
     * @param encryptString string to encrypt
     * @return encrypted sha1 or NULL
     */
    public static String sha1Encrypt(String encryptString)
    {
        // return null (default) if calculator fail
        String sha1 = null;
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            // be careful with character encode, if not exist it will throw UnsupportedEncodingException
            crypt.update(encryptString.getBytes("UTF-8"));

            // convert byte to hex
            Formatter formatter = new Formatter();
            for (byte b : crypt.digest())
            {
                formatter.format("%02x", b);
            }
            String result = formatter.toString();
            formatter.close();
            sha1 = result;
        }
        catch(NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return sha1;
    }