背景
服务端为每个APP自动生成安卓证书JKS文件,在APP构建过程中会把其放入APP包中。在安卓应用上架的过程中,需要提供应用的 SHA-1 指纹主要是用于验证应用签名的有效性和安全性。
读取JKS文件SHA1和SHA256值
package com.ocean.angel.tool.util;
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.security.*;
import java.security.cert.Certificate;
@Slf4j
public class CertificateUtil {
public static void main(String[] args) throws Exception {
// JKS file文件路径
String jksFile = "D:\\myworkplace\\study\\file-handler\\src\\main\\resources\\file\\jks\\uwukwq.jks";
// keystore密码
String storePassword = "z1yucrwh";
// certificate名称
String alias = "thk9yd";
// keystore
KeyStore keystore = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream(jksFile);
keystore.load(fis, storePassword.toCharArray());
fis.close();
// 获取证书
Certificate cert = keystore.getCertificate(alias);
// 证书 sha1
String sha1 = formatHexWithColons(calculateSHA1(cert).toUpperCase());
log.info("sha1: {}", sha1);
// 证书 sha256
String sha256 = formatHexWithColons(calculateSHA256(cert).toUpperCase());
log.info("sha256: {}", sha256);
}
// 计算 SHA-1 哈希值
private static String calculateSHA1(Certificate cert) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] encodedCert = cert.getEncoded();
byte[] sha1 = digest.digest(encodedCert);
return bytesToHex(sha1); // Convert byte array to hexadecimal string
}
// 计算 SHA-256 哈希值
private static String calculateSHA256(Certificate cert) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedCert = cert.getEncoded();
byte[] sha256 = digest.digest(encodedCert);
return bytesToHex(sha256); // 转换成十六进制字符串
}
// Method to convert byte array to hexadecimal string
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
private static String formatHexWithColons(String hex) {
StringBuilder formattedHex = new StringBuilder();
for (int i = 0; i < hex.length(); i += 2) {
formattedHex.append(hex, i, i + 2).append(":");
}
// 移除末尾多余的冒号
return formattedHex.substring(0, formattedHex.length() - 1);
}
}
读取结果截图: