java实现对数据的SHA-256加密算法
时间: 2024-06-13 07:08:35 浏览: 134
JAVA实现的sha256加密算法
5星 · 资源好评率100%
以下是Java实现对数据的SHA-256加密算法的示例代码:
```java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA256Util {
public static String sha256(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
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();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
```
使用示例:
```java
String input = "hello world";
String sha256 = SHA256Util.sha256(input);
System.out.println(sha256); // 输出:b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
```
阅读全文