Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

generate hash in java

import java.security.MessageDigest;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;
 
/**
 * Demonstrates how to generate SHA256 hash in Java
 * @author JJ
 */
public class SHA256InJava {
 
    public static void main(String[] args) {
        Scanner sn = new Scanner(System.in);
        System.out.print("Please enter data for which SHA256 is required:");
        String data = sn.nextLine();
         
        SHA256InJava sj = new SHA256InJava();
        String hash = sj.getSHA256Hash(data);
        System.out.println("The SHA256 (hexadecimal encoded) hash is:"+hash);
    }
 
    /**
     * Returns a hexadecimal encoded SHA-256 hash for the input String.
     * @param data
     * @return 
     */
    private String getSHA256Hash(String data) {
        String result = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(data.getBytes("UTF-8"));
            return bytesToHex(hash); // make it printable
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
     
    /**
     * Use javax.xml.bind.DatatypeConverter class in JDK to convert byte array
     * to a hexadecimal string. Note that this generates hexadecimal in upper case.
     * @param hash
     * @return 
     */
    private String  bytesToHex(byte[] hash) {
        return DatatypeConverter.printHexBinary(hash);
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: compare 2 hashmap 
Java :: switch statement in java 
Java :: navigation bottom android 
Java :: can abstract class have non abstract methods in java 
Java :: convert string array to string 
Java :: java to kotlin 
Java :: generic variable java 
Java :: splash full screen android 
Java :: insert node at end of doubly linked list 
Java :: declaring java variables 
Java :: runtime exception in java 
Java :: logcat android 
Java :: why string is immutable in java 
Java :: inorder traversal 
Java :: string comparison using == in java 
Java :: Java Access LinkedList elements 
Java :: create fragment constructor in arrayadapter 
Java :: netbens setdefaultbutton 
Java :: assign a random number in a set without replacement javva 
Java :: session management in java spring boot for login logut 
Java :: java gui bank account program 
Java :: AccountDriver.java 
Java :: split by asterisk java 
Java :: java %2C 
Java :: transform primitive float array to float array 
Java :: Java Remove Elements 
Java :: setlist arraylist java swing example 
Java :: java plugin spigot messsage console 
Java :: android diagonal gradle 
Java :: how to get data from array list to set java 
ADD CONTENT
Topic
Content
Source link
Name
7+3 =