Java SHA256 sha256Encode(String message)

Here you can find the source of sha256Encode(String message)

Description

sha Encode

License

Apache License

Declaration

public static String sha256Encode(String message) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static final boolean toUpperCase = true;

    public static String sha256Encode(String message) {
        return encode("SHA-256", message);
    }/*from  w  ww.j a va  2s .c  o m*/

    public static String sha256Encode(byte[] message) {
        return encode("SHA-256", message);
    }

    private static String encode(String code, String message) {
        return encode(code, message.getBytes());
    }

    private static String encode(String code, byte[] message) {
        MessageDigest md;
        String encode = null;
        try {
            md = MessageDigest.getInstance(code);
            encode = byteArrayToHexString(md.digest(message));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encode;
    }

    private static String byteArrayToHexString(byte[] digest) {
        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < digest.length; i++) {
            if (Integer.toHexString(0xFF & digest[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & digest[i]));
            } else {
                String hex = Integer.toHexString(0xFF & digest[i]);
                if (toUpperCase) {
                    hex = hex.toUpperCase();
                }
                md5StrBuff.append(hex);
            }
        }
        return md5StrBuff.toString();
    }
}

Related

  1. SHA256Binary(String toHash)
  2. SHA256byte(String input)
  3. sha256digest(@Nonnull byte[] data)
  4. sha256Digest(byte[] bytes)
  5. sha256Digest(final InputStream data)
  6. sha256encrypt(String phrase)
  7. sha256Hash()
  8. sha256Hash(byte[] data)
  9. sha256Hash(File file)