Returns a String Object which contains the SHA256 Hash value of the input - Android java.lang

Android examples for java.lang:String Hash

Description

Returns a String Object which contains the SHA256 Hash value of the input

Demo Code


//package com.java2s;

import java.security.MessageDigest;

public class Main {
    /**/* w  w  w  .j av  a  2 s  .  c om*/
     * Returns a String Object which contains the SHA256 Hash value of the input
     *
     * @param input a String object for which SHA256 should be calculated
     * @return SHA256 of the input String
     */
    public static String getSHA256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes("UTF-8"));
            StringBuilder hexString = new StringBuilder();

            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                if (hex.length() == 1)
                    hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related Tutorials