本文目录导读:

在Java中实现SHA(安全散列算法)加密,最常用的方法是使用java.security.MessageDigest类,这里为你提供几种常见的SHA加密案例。
基础SHA加密工具类
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHAUtil {
// 将字节数组转换为十六进制字符串
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// SHA-256 加密
public static String sha256(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(input.getBytes());
return bytesToHex(hash);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
// SHA-512 加密
public static String sha512(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] hash = md.digest(input.getBytes());
return bytesToHex(hash);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String text = "Hello, SHA加密!";
System.out.println("原文: " + text);
System.out.println("SHA-256: " + sha256(text));
System.out.println("SHA-512: " + sha512(text));
}
}
支持多种SHA算法的通用方法
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class GenericSHAExample {
public static String sha(String input, String algorithm) {
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] hash = md.digest(input.getBytes());
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) {
System.out.println("不支持的算法: " + algorithm);
return null;
}
}
public static void main(String[] args) {
String text = "Hello, SHA加密!";
String[] algorithms = {"SHA-1", "SHA-224", "SHA-256", "SHA-384", "SHA-512"};
System.out.println("原文: " + text);
System.out.println("==============================");
for (String algorithm : algorithms) {
String result = sha(text, algorithm);
System.out.println(algorithm + ": " + result + " (" + result.length() + "位)");
}
}
}
带有UTF-8编码处理的版本
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHAWithEncoding {
public static String sha256WithEncoding(String input, String charset) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
// 使用指定编码处理字符串
byte[] hash = md.digest(input.getBytes(charset));
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 | UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String text = "Hello, SHA加密!";
System.out.println("使用UTF-8编码: " + sha256WithEncoding(text, "UTF-8"));
System.out.println("使用GBK编码: " + sha256WithEncoding(text, "GBK"));
}
}
文件SHA值计算
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileSHAExample {
public static String calculateFileSHA(String filePath, String algorithm) {
try (FileInputStream fis = new FileInputStream(filePath);
DigestInputStream dis = new DigestInputStream(fis,
MessageDigest.getInstance(algorithm))) {
// 读取文件内容
byte[] buffer = new byte[8192];
while (dis.read(buffer) != -1) {
// 读取过程中自动计算摘要
}
// 获取摘要结果
byte[] hash = dis.getMessageDigest().digest();
// 转换为十六进制字符串
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 | IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
// 替换为实际文件路径
String filePath = "path/to/your/file.txt";
String sha256 = calculateFileSHA(filePath, "SHA-256");
String sha512 = calculateFileSHA(filePath, "SHA-512");
System.out.println("文件SHA-256: " + sha256);
System.out.println("文件SHA-512: " + sha512);
}
}
使用Apache Commons Codec(第三方库)
如果项目中使用了Maven,可以添加以下依赖:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
import org.apache.commons.codec.digest.DigestUtils;
public class CommonsCodecExample {
public static void main(String[] args) {
String text = "Hello, SHA加密!";
System.out.println("SHA-1: " + DigestUtils.sha1Hex(text));
System.out.println("SHA-256: " + DigestUtils.sha256Hex(text));
System.out.println("SHA-384: " + DigestUtils.sha384Hex(text));
System.out.println("SHA-512: " + DigestUtils.sha512Hex(text));
}
}
注意事项
-
算法选择:SHA-256和SHA-512是目前推荐的算法,SHA-1已被认为不够安全
-
编码问题:处理不同语言的字符串时,注意使用统一的编码(推荐UTF-8)
-
不可逆性:SHA是单向散列函数,不可解密,只能验证
-
彩虹表攻击:存储密码时,应使用加盐(salt)的SHA,增加破解难度
-
性能考虑:SHA-512比SHA-256慢,但同时提供了更高的安全性
这些示例涵盖了Java中实现SHA加密的常见场景,你可以根据实际需求选择合适的实现方式。