java sha256加密解密
时间: 2023-09-07 10:15:03 浏览: 52
Java中可以使用Java.security.MessageDigest类来进行SHA-256加密和解密。下面是一个简单的示例代码:
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA256Example {
public static void main(String[] args) throws NoSuchAlgorithmException {
String originalString = "Hello, world!";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedHash = digest.digest(originalString.getBytes());
System.out.println("Original String: " + originalString);
System.out.println("Encoded Hash: " + bytesToHex(encodedHash));
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
```
运行结果:
```
Original String: Hello, world!
Encoded Hash: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
```
这里我们使用了一个名为 `bytesToHex` 的 helper 方法,用于将字节数组转换为十六进制字符串。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)