SHA-2加密散列函数系列由六个散列函数组成。这些是:
SHA-224,具有224位散列值
SHA-256,具有256位哈希值
SHA-384,具有384位哈希值
SHA-512,具有512位哈希值
SHA-512/224,具有512位散列值
SHA-512/256,具有512位哈希值
其中,SHA-256和SHA-512是最常被接受和使用的散列函数,分别用32位和64位字计算。SHA-224和SHA-384分别是SHA-256和SHA-512的截断版本,使用不同的初始值计算。
要在Java中计算加密散列值,请在java.security包下使用MessageDigest类。
MessagDigest类提供以下加密哈希函数来查找文本的哈希值,如下所示:
MD2
MD5
SHA-1
SHA-224
SHA-256
SHA-384
SHA-512
这些算法在名为getInstance()的静态方法中初始化。选择算法后,将计算消息摘要值,并将结果作为字节数组返回。使用BigInteger类将结果字节数组转换为其signum表示。然后将此表示转换为十六进制格式以获得预期的MessageDigest。
例子:
输入:hello world
输出:
2f05477fc24bb4faefd86517156dafdecec45b8ad3cf2522a563582b
输入:Breakyizhan
输出:
6c88a4d5219bd4f845f335d337cee237a1440e9c46e4f22aee511713
下面的程序显示了Java中SHA-224哈希的实现
// Java program to calculate SHA-224 hash value
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class GFG {
public static String encryptThisString(String input)
{
try {
// getInstance() method is called with algorithm SHA-224
MessageDigest md = MessageDigest.getInstance("SHA-224");
// digest() method is called
// to calculate message digest of the input string
// returned as array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
// Add preceding 0s to make it 32 bit
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
// return the HashText
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException
{
System.out.println("HashCode Generated by SHA-224 for: ");
String s1 = "Breakyizhan";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));
String s2 = "hello world";
System.out.println("\n" + s2 + " : " + encryptThisString(s2));
}
}
输出:
HashCode Generated by SHA-224 for:
Breakyizhan : 6c88a4d5219bd4f845f335d337cee237a1440e9c46e4f22aee511713
hello world : 2f05477fc24bb4faefd86517156dafdecec45b8ad3cf2522a563582b
应用:
加密
数据的完整性