Quantcast
Channel: CodeSection,代码区,网络安全 - CodeSec
Viewing all articles
Browse latest Browse all 12749

在代码中如何获取应用签名及 sha1 值

0
0

在需要微信分享、支付的项目中,会涉及到应用签名,这里主要讨论怎么在应用里获取应用的签名信息。

不多说了,直接上代码:

PackageManager packageManager = context.getPackageManager();

//请注意需要 PackageManager.GET_SIGNATURES 这个flag

PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),

PackageManager.GET_SIGNATURES);

Signature[] signs = packageInfo.signatures; Signature sign = signs[0];

// X509证书,X.509是一种非常通用的证书格式

CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

X509Certificate cert = (X509Certificate) certFactory

.generateCertificate(new ByteArrayInputStream(sign.toByteArray()));

MessageDigest md = MessageDigest.getInstance("MD5");

// 获得公钥

byte[] b = md.digest(cert.getEncoded());

//key即为应用签名

String key=byte2HexFormatted(b).replace(":", "");

* 将获取到得编码进行16进制转换

* @param arr

* @return

private static String byte2HexFormatted(byte[] arr) {

StringBuilder str = new StringBuilder(arr.length * 2);

for (int i = 0; i < arr.length; i++) {

String h = Integer.toHexString(arr[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 < (arr.length - 1))

str.append(':');

return str.toString();

最后在附上如何获取sha1值:

* 获得app 的sha1值 *

* @param context

* @return */

public static String getAppSignSha1(Context context) {

try {

PackageManager packageManager = context.getPackageManager();

PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),PackageManager.GET_SIGNATURES);

// X509证书,X.509是一种非常通用的证书格式

Signature[] signs = packageInfo.signatures; Signature sign = signs[0];

CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

X509Certificate cert = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(sign.toByteArray()));// md5

MessageDigest md = MessageDigest.getInstance("SHA1");

// 获得公钥 byte[] b = md.digest(cert.getEncoded());

return byte2HexFormatted(b);

} catch (Exception e) {

e.printStackTrace();

return null; }


Viewing all articles
Browse latest Browse all 12749