import android.content.pm.Signature;

/**
     * 获取apk签名
     */
    public static String getSignature(Activity activity) {
        StringBuffer signStr = new StringBuffer();
        Signature[] signs = getRawSignature(activity, activity.getPackageName());
        if (signs != null && signs.length > 0) {
            for (Signature sign : signs) {
                String signMd5 = getMessageDigest(sign.toByteArray());
                signStr.append(signMd5);
            }
        }
        return signStr.toString();
    }

    private static Signature[] getRawSignature(Context context, String packageName) {
        if (!TextUtils.isEmpty(packageName)) {
            PackageManager pkgMgr = context.getPackageManager();
            try {
                PackageInfo info = pkgMgr.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
                if (info != null) {
                    return info.signatures;
                }
            } catch (PackageManager.NameNotFoundException e) {
                return null;
            }
        }
        return null;
    }

    private static String getMessageDigest(byte[] buffer) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                int k2 = k + 1;
                str[k] = hexDigits[(byte0 >>> 4) & 15];
                k = k2 + 1;
                str[k2] = hexDigits[byte0 & 15];
            }
            return new String(str);
        } catch (Exception e) {
            return "";
        }
    }

以上方法参考微信开放平台的->获取安装到手机的第三方应用签名的apk包  源码

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐