Java 中使用 SHA.sha1() 方法需要引入的包
在 Java 中使用 SHA.sha1() 方法时,需要引入 'java.security' 包来支持 SHA-1 算法。
代码示例:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1Example {
public static void main(String[] args) throws NoSuchAlgorithmException {
String message = "Hello world!";
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] hash = digest.digest(message.getBytes("UTF-8"));
System.out.println(bytesToHex(hash));
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
注意:
SHA-1算法是一种加密哈希算法,它将任意长度的字符串转换为固定长度的哈希值。- 在使用 SHA-1 算法时,需要确保引入 'java.security' 包。
- 以上代码示例展示了如何使用 SHA-1 算法生成哈希值。
原文地址: https://www.cveoy.top/t/topic/opzQ 著作权归作者所有。请勿转载和采集!