search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Create an Instance of MessageDigest
Update Data to Be Hashed
Generate the Hash
Example: Complete SHA-256 Hashing Code
Home Java javaTutorial How to use MessageDigest for hashing in Java?

How to use MessageDigest for hashing in Java?

Dec 02, 2025 am 01:45 AM
Hash

Using MessageDigest for hashing requires three steps: obtain the instance MessageDigest.getInstance("SHA-256"), update the data md.update(input), generate the hash md.digest() and convert it to a hexadecimal string. SHA-256 is recommended, avoid MD5 and SHA-1.

How to use MessageDigest for hashing in Java?

To use MessageDigest for hashing in Java, you need to follow a few straightforward steps. This class, part of the java.security package, provides applications the functionality of a message digest algorithm, such as MD5, SHA-1, or SHA-256.

Create an Instance of MessageDigest

Choose a supported algorithm (eg, SHA-256) and get an instance using the getInstance() method.

  • MessageDigest md = MessageDigest.getInstance("SHA-256");

Update Data to Be Hashed

Feed the data you want to hash into the digest using the update() method. You can pass data as a byte array or incrementally process chunks.

  • byte[] input = "Hello, World!".getBytes(StandardCharsets.UTF_8);
  • md.update(input);

Generate the Hash

Call digest() to compute the hash. This method returns a byte array representing the hashed value.

  • byte[] hash = md.digest();

If you need a hexadecimal string representation, convert the byte array manually:

  • StringBuilder sb = new StringBuilder();
  • for (byte b : hash) {
  • sb.append(String.format(" x", b));
  • }
  • String hexHash = sb.toString();

Example: Complete SHA-256 Hashing Code

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;

public class HashExample {
    public static String sha256(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : hash) {
                sb.append(String.format(" x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(sha256("Hello, World!"));
    }
}

Common algorithms include:

  • MD5 – Fast but cryptographically weak (avoid for security-sensitive uses)
  • SHA-1 – Deprecated due to vulnerabilities
  • SHA-256 – Recommended for most purposes

Basically just pick a secure algorithm, feed your data, and extract the hash. Make sure to handle exceptions and avoid hardcoding sensitive logic in production without additional protections like salting or using higher-level APIs.

The above is the detailed content of How to use MessageDigest for hashing in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A simple article explaining what a hash algorithm is! What is a hash algorithm? A simple article explaining what a hash algorithm is! What is a hash algorithm? Mar 14, 2024 am 11:46 AM

When understanding Bitcoin investment and blockchain technology, hash algorithms can be said to appear frequently. It is said in the currency circle that hip-hop has hip-hop and algorithms have hashes. As for the word "algorithm", it is currently used vaguely by domestic users. Sometimes it refers to the consensus mechanism, and sometimes it refers to the specific Hash algorithm. As a blockchain algorithm, the Hash algorithm has always been obscure to the general public. So, what is Hash algorithm? Hash algorithm? Next, the editor of the currency circle will give you a simple explanation of what a hash algorithm is? I hope that investors can understand the hash algorithm after reading this article. What is a hash algorithm? Hash is transliterated from "Hash", also known as "hash". Essentially a computer program that accepts any

How to write a hash lookup algorithm in Python? How to write a hash lookup algorithm in Python? Sep 21, 2023 pm 02:37 PM

How to write a hash lookup algorithm in Python? Hash search algorithm, also known as hash search algorithm, is a data search method based on hash table. Compared with traditional search algorithms such as linear search and binary search, the hash search algorithm has higher search efficiency. In Python, we can use a dictionary to implement a hash table and then implement a hash lookup. The basic idea of ​​the hash search algorithm is to convert the keyword to be searched into an index value through a hash function, and then search it in the hash table based on the index value.

How to use hash search algorithm in C++ How to use hash search algorithm in C++ Sep 19, 2023 pm 02:49 PM

How to use the hash search algorithm in C++ The hash search algorithm is an efficient search and storage technology. It converts keywords into a fixed-length index through a hash function, and then uses this index in the data structure Search. In C++, we can implement hash search algorithms by using hash containers and hash functions from the standard library. This article will introduce how to use the hash search algorithm in C++ and provide specific code examples. Introducing header files and namespaces First, before using the hash search algorithm in C++

Python underlying technology revealed: how to implement hash algorithm Python underlying technology revealed: how to implement hash algorithm Nov 08, 2023 pm 06:40 PM

Revealing the underlying technology of Python: How to implement the hash algorithm, specific code examples are required Summary: The hash algorithm is one of the commonly used technologies in the computer field and is used to quickly determine the unique identification of data. As a high-level language, Python provides many built-in hash functions, such as the hash() function and the implementation of various hash algorithms. This article will reveal the principles of hashing algorithms and the details of Python's underlying implementation, and provide specific code examples. Introduction to Hash Algorithm Hash algorithm, also known as hash algorithm, is a method of converting data of any length into

In PHP, what does hash function mean? In PHP, what does hash function mean? Sep 03, 2023 am 08:49 AM

A hash function is any function that can be used to map data of any size to data of a fixed size. The value returned by a hash function is called a hash value, hash code, digest, or simply hash. Syntax stringhash(string$algo,string$data[,bool$raw_output=FALSE]) Parameter algo The name of the selected hash algorithm (such as "md5", "sha256", "haval160,4", etc.) data to be hashed information. When raw_output is set to TRUE, raw binary data is output. FALSE outputs lowercase hexadecimal. Example<?php &nbsp

Best encryption and hashing techniques in PHP development Best encryption and hashing techniques in PHP development May 27, 2023 am 08:21 AM

In today's digital age, with the development of the Internet and the increasing importance of information, data confidentiality and security have become increasingly important. To ensure that data is not stolen or tampered with during transmission, PHP developers often use encryption and hashing techniques to protect sensitive data. This article will introduce the most commonly used encryption and hashing technologies in PHP development, as well as their advantages and disadvantages. 1. Encryption technology Encryption is a technology that protects data security. It uses algorithms to convert data into meaningless forms. Only the person holding the key can restore it to readable

How to handle hashing and encryption functions in accounting systems - Development methods for hashing and encryption using PHP How to handle hashing and encryption functions in accounting systems - Development methods for hashing and encryption using PHP Sep 26, 2023 pm 01:15 PM

How to handle hashing and encryption functions in accounting systems - Development methods for hashing and encryption using PHP Introduction: With the advent of the digital age, the security of various information systems has become more and more important. When designing and developing accounting systems, protecting user privacy data is crucial. Among them, the use of hashing and encryption functions can effectively protect users' sensitive information. This article will introduce how to use PHP to implement hashing and encryption functions in accounting systems, and provide specific code examples. 1. Implementation of hash function Hash is a one-way encryption algorithm

PHP Load Balancing Diversity: Understanding the Pros and Cons of Different Technologies PHP Load Balancing Diversity: Understanding the Pros and Cons of Different Technologies Mar 02, 2024 pm 02:50 PM

Introduction In today's fast-paced and connected digital world, ensuring high availability of applications is critical. Load balancing technology enables applications to distribute incoming traffic across multiple servers, improving performance and reliability. PHP provides support for a range of load balancing technologies, each with its own unique advantages and limitations. Round Robin Round Robin is a simple and effective load balancing technique that distributes requests to a server pool in order. This approach is easy to implement and ensures that requests are evenly distributed among servers. $servers=array("server1","server2","server3");$index=0;while(true)

Related articles