java sha256hash_在Java中的SHA-256哈希加密 - Break易站

时间:2025-03-10 07:05:16

SHA-256定义:

在密码学中,SHA是加密散列函数,它将输入作为20字节并以十六进制数形式呈现散列值,大约40位数。

SHA-256消息摘要类:

要在Java中计算加密散列值,请在包下使用MessageDigest类。

MessagDigest类提供以下加密哈希函数来查找文本的哈希值,它们是:

MD5

SHA-1

SHA-256

算法在名为getInstance()的静态方法中初始化。选择算法后,它会计算摘要值并以字节数组的形式返回结果。

使用BigInteger类,它将结果字节数组转换为符号幅度表示。此表示形式将转换为十六进制格式以获取MessageDigest

例子:

HashCode Generated by SHA-256 for:

breakyizhan : 56ada93a5a17f0f0ebe0dbea116e90e8581cf236adee96434007b13c0c47710

hello world : b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

在Java中的SHA-256哈希加密的例子

import ;

import ;

import ;

// Java program to calculate SHA hash value

class GFG {

public static String getSHA(String input)

{

try {

// Static getInstance method is called with hashing SHA

MessageDigest md = ("SHA-256");

// digest() method called

// to calculate message digest of an input

// and return array of byte

byte[] messageDigest = (());

// Convert byte array into signum representation

BigInteger no = new BigInteger(1, messageDigest);

// Convert message digest into hex value

String hashtext = (16);

while (() < 32) {

hashtext = "0" + hashtext;

}

return hashtext;

}

// For specifying wrong message digest algorithms

catch (NoSuchAlgorithmException e) {

("Exception thrown"

+ " for incorrect algorithm: " + e);

return null;

}

}

// Driver code

public static void main(String args[]) throws NoSuchAlgorithmException

{

("HashCode Generated by SHA-256 for:");

String s1 = "breakyizhan";

("\n" + s1 + " : " + getSHA(s1));

String s2 = "hello world";

("\n" + s2 + " : " + getSHA(s2));

}

}

输出:

HashCode Generated by SHA-256 for:

breakyizhan : 56ada93a5a17f0f0ebe0dbea116e90e8581cf236adee96434007b13c0c47710

hello world : b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

应用:

加密

数据的完整性