Android Studio获取SHA1和MD5
程序员文章站
2022-03-09 16:15:01
...
方法一:
如下图所示:
a、点击1处,双击2处,即可出现底部窗口(MD5和SHA1),若底部窗口未出现(MD5和SHA1),请点击3处即可。
b、如果没有1处窗口,点击4处、5处、6处,即可出现1处窗口,然后重复a操作。
方法二:
1、通过代码获取SHA1:
public static String getSHA1(Context context) {
try {
PackageManager pm = context.getPackageManager();// 获取包管理器
String packageName = context.getPackageName(); //获取包名
PackageInfo info = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
byte[] cert = info.signatures[0].toByteArray();
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] publicKey = md.digest(cert);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < publicKey.length; i++) {
String appendString = Integer.toHexString(0xFF & publicKey[i]).toUpperCase(Locale.US);
if (appendString.length() == 1) {
hexString.append("0");
}
hexString.append(appendString);
hexString.append(":");
}
String result = hexString.toString();
return result.substring(0, result.length() - 1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2、通过代码获取MD5:
public static String getMD5(Context context) {
try {
PackageManager pm = context.getPackageManager();// 获取包管理器
String packageName = context.getPackageName(); //获取包名
PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
Signature[] signatures = packageInfo.signatures;// 签名信息
byte[] signatureByte = signatures[0].toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(signatureByte);// 将签名转换为字节数组流
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");// 证书工厂类,这个类实现了出厂合格证算法的功能
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);// X509证书,X.509是一种非常通用的证书格式
MessageDigest md = MessageDigest.getInstance("MD5");// MD5加密算法
byte[] publicKey = md.digest(cert.getEncoded());//获得公钥
StringBuilder str = new StringBuilder(publicKey.length * 2);
for (int i = 0; i < publicKey.length; i++) {
String h = Integer.toHexString(publicKey[i]);
int l = h.length();
if (l == 1)
h = "0" + h;
if (l > 2)
h = h.substring(l - 2, l);
str.append(h.toUpperCase());
if (i < (publicKey.length - 1))
str.append(':');
}
return str.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}