SHA-1 哈希
SHA-1 或安全散列算法 1 是一个加密散列函数,它接受输入并产生一个 160 位(20 字节)的散列值。这个哈希值被称为消息摘要。该消息摘要通常呈现为 40 位长的十六进制数。它是美国联邦信息处理标准,由美国国家安全局设计。
自 2005 年以来,SHA-1 现在被认为是不安全的。到 2017 年,像微软、谷歌、苹果和 Mozilla 这样的主要科技巨头浏览器已经停止接受 SHA-1 SSL 证书。
为了计算 Java 中的加密散列值,使用了包 java.security 下的消息摘要类。
MessagDigest 类提供以下加密哈希函数来查找文本的哈希值,如下所示:
- MD2
- 讯息摘要 5
- SHA-1
- SHA-224
- SHA-256
- SHA-384
- SHA-512
这些算法在名为 getInstance() 的静态方法中初始化。选择算法后,计算消息摘要值,并将结果作为字节数组返回。使用 BigInteger 类,将结果字节数组转换为它的符号表示。然后,该表示被转换为十六进制格式,以获得预期的消息摘要。
示例:
输入 : hello world 输出:2a e6c 35 c94 fcfb 415 DBE 95 f408 b9ce 91 ee 846 ed
输入 : GeeksForGeeks 输出:addf 120 b 430021 c 36 c 232 c 99 ef 8d 926 ea2a cd6b
下面的程序展示了 SHA-1 哈希在 Java 中的实现。
// Java program to calculate SHA-1 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-1
MessageDigest md = MessageDigest.getInstance("SHA-1");
// 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-1 for: ");
String s1 = "GeeksForGeeks";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));
String s2 = "hello world";
System.out.println("\n" + s2 + " : " + encryptThisString(s2));
}
}
Output:
HashCode Generated by SHA-1 for:
GeeksForGeeks : addf120b430021c36c232c99ef8d926aea2acd6b
hello world : 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
应用:
- 密码系统
- 数据完整性
版权属于:月萌API www.moonapi.com,转载请注明出处