android.content.pm.Signature Java Examples

The following examples show how to use android.content.pm.Signature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RealPosClientTest.java    From point-of-sale-android-sdk with Apache License 2.0 6 votes vote down vote up
private void installApp(String packageName, int versionCode, Signature signature) {
  ResolveInfo resolveInfo = new ResolveInfo();
  resolveInfo.activityInfo = new ActivityInfo();
  resolveInfo.activityInfo.packageName = packageName;
  chargeActivities.add(resolveInfo);
  PackageInfo packageInfo = new PackageInfo();
  packageInfo.versionCode = versionCode;
  packageInfo.packageName = packageName;
  packageInfo.signatures = new Signature[1];
  packageInfo.signatures[0] = signature;
  try {
    when(context.getPackageManager().getPackageInfo(eq(packageName), anyInt())).thenReturn(
        packageInfo);
  } catch (PackageManager.NameNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 
Example #2
Source File: Facebook.java    From facebook-api-android-maven with Apache License 2.0 6 votes vote down vote up
/**
 * Query the signature for the application that would be invoked by the
 * given intent and verify that it matches the FB application's signature.
 * 
 * @param context
 * @param packageName
 * @return true if the app's signature matches the expected signature.
 */
private boolean validateAppSignatureForPackage(Context context, String packageName) {

    PackageInfo packageInfo;
    try {
        packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (NameNotFoundException e) {
        return false;
    }

    for (Signature signature : packageInfo.signatures) {
        if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
            return true;
        }
    }
    return false;
}
 
Example #3
Source File: PackageSignatures.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void writeCertsListXml(XmlSerializer serializer, ArrayList<Signature> writtenSignatures,
        Signature[] signatures, int[] flags) throws IOException {
    for (int i=0; i<signatures.length; i++) {
        serializer.startTag(null, "cert");
        final Signature sig = signatures[i];
        final int sigHash = sig.hashCode();
        final int numWritten = writtenSignatures.size();
        int j;
        for (j=0; j<numWritten; j++) {
            Signature writtenSig = writtenSignatures.get(j);
            if (writtenSig.hashCode() == sigHash && writtenSig.equals(sig)) {
                serializer.attribute(null, "index", Integer.toString(j));
                break;
            }
        }
        if (j >= numWritten) {
            writtenSignatures.add(sig);
            serializer.attribute(null, "index", Integer.toString(numWritten));
            serializer.attribute(null, "key", sig.toCharsString());
        }
        if (flags != null) {
            serializer.attribute(null, "flags", Integer.toString(flags[i]));
        }
        serializer.endTag(null, "cert");
    }
}
 
Example #4
Source File: AppSignatureHelper.java    From identity-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Get all the app signatures for the current package
 * @return
 */
public ArrayList<String> getAppSignatures() {
    ArrayList<String> appCodes = new ArrayList<>();

    try {
        // Get all package signatures for the current package
        String packageName = getPackageName();
        PackageManager packageManager = getPackageManager();
        Signature[] signatures = packageManager.getPackageInfo(packageName,
                PackageManager.GET_SIGNATURES).signatures;

        // For each signature create a compatible hash
        for (Signature signature : signatures) {
            String hash = hash(packageName, signature.toCharsString());
            if (hash != null) {
                appCodes.add(String.format("%s", hash));
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "Unable to find package to obtain hash.", e);
    }
    return appCodes;
}
 
Example #5
Source File: OPFIabUtils.java    From OPFIab with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves signature form supplied package.
 *
 * @param context     Context object to get {@link PackageManager} from.
 * @param packageName Package to retrieve signature for.
 *
 * @return Signature object if package found, null otherwise.
 */
@SuppressWarnings("PackageManagerGetSignatures")
@NonNull
public static Signature[] getPackageSignatures(@NonNull final Context context,
                                               @NonNull final String packageName) {
    final PackageManager packageManager = context.getPackageManager();
    try {
        final PackageInfo info = packageManager.getPackageInfo(packageName, GET_SIGNATURES);
        final Signature[] signatures = info.signatures;
        if (signatures != null) {
            return signatures;
        }
    } catch (PackageManager.NameNotFoundException exception) {
        OPFLog.e("", exception);
    }
    return new Signature[0];
}
 
Example #6
Source File: SecurityHelper.java    From input-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the fingerprint of the signed certificate of a package.
 */
public static String getFingerprint(PackageInfo packageInfo, String packageName) throws
        PackageManager.NameNotFoundException, IOException, NoSuchAlgorithmException,
        CertificateException {
    Signature[] signatures = packageInfo.signatures;
    if (signatures.length != 1) {
        throw new SecurityException(packageName + " has " + signatures.length + " signatures");
    }
    byte[] cert = signatures[0].toByteArray();
    try (InputStream input = new ByteArrayInputStream(cert)) {
        CertificateFactory factory = CertificateFactory.getInstance("X509");
        X509Certificate x509 = (X509Certificate) factory.generateCertificate(input);
        MessageDigest md = MessageDigest.getInstance("SHA256");
        byte[] publicKey = md.digest(x509.getEncoded());
        return toHexFormat(publicKey);
    }
}
 
Example #7
Source File: MiuiPushActivateService.java    From MiPushFramework with GNU General Public License v3.0 6 votes vote down vote up
private boolean verifySignatures(String str) {
    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(str, PackageManager.GET_SIGNATURES);
        if (packageInfo.signatures != null) {
            for (Object obj : packageInfo.signatures) {
                for (Signature equals : MIUI_PLATFORM_SIGNATURES) {
                    if (equals.equals(obj)) {
                        return true;
                    }
                }
            }
        }
    } catch (NameNotFoundException e) {
    }
    return false;
}
 
Example #8
Source File: WebViewUpdater.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private static boolean providerHasValidSignature(WebViewProviderInfo provider,
        PackageInfo packageInfo, SystemInterface systemInterface) {
    if (systemInterface.systemIsDebuggable()) {
        return true;
    }
    // If no signature is declared, instead check whether the package is included in the
    // system.
    if (provider.signatures == null || provider.signatures.length == 0) {
        return packageInfo.applicationInfo.isSystemApp();
    }
    if (packageInfo.signatures.length != 1) return false;

    // Return whether the package signature matches any of the valid signatures
    for (Signature signature : provider.signatures) {
        if (signature.equals(packageInfo.signatures[0])) return true;
    }
    return false;
}
 
Example #9
Source File: AppUtils.java    From Aria with Apache License 2.0 6 votes vote down vote up
/**
 * 获取相应的类型的字符串(把签名的byte[]信息转换成16进制)
 */
public static String getSignatureString(Signature sig, String type) {
  byte[] hexBytes = sig.toByteArray();
  String fingerprint = "error!";
  try {
    MessageDigest digest = MessageDigest.getInstance(type);
    if (digest != null) {
      byte[] digestBytes = digest.digest(hexBytes);
      StringBuilder sb = new StringBuilder();
      for (byte digestByte : digestBytes) {
        sb.append((Integer.toHexString((digestByte & 0xFF) | 0x100)).substring(1, 3));
      }
      fingerprint = sb.toString();
    }
  } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
  }

  return fingerprint;
}
 
Example #10
Source File: ShortcutPackageInfo.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public static ShortcutPackageInfo generateForInstalledPackageForTest(
        ShortcutService s, String packageName, @UserIdInt int packageUserId) {
    final PackageInfo pi = s.getPackageInfoWithSignatures(packageName, packageUserId);
    // retrieve the newest sigs
    SigningInfo signingInfo = pi.signingInfo;
    if (signingInfo == null) {
        Slog.e(TAG, "Can't get signatures: package=" + packageName);
        return null;
    }
    // TODO (b/73988180) use entire signing history in case of rollbacks
    Signature[] signatures = signingInfo.getApkContentsSigners();
    final ShortcutPackageInfo ret = new ShortcutPackageInfo(pi.getLongVersionCode(),
            pi.lastUpdateTime, BackupUtils.hashSignatureArray(signatures), /* shadow=*/ false);

    ret.mBackupSourceBackupAllowed = s.shouldBackupApp(pi);
    ret.mBackupSourceVersionCode = pi.getLongVersionCode();
    return ret;
}
 
Example #11
Source File: Facebook.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
/**
 * Query the signature for the application that would be invoked by the
 * given intent and verify that it matches the FB application's signature.
 * 
 * @param context
 * @param packageName
 * @return true if the app's signature matches the expected signature.
 */
private boolean validateAppSignatureForPackage(Context context, String packageName) {

    PackageInfo packageInfo;
    try {
        packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (NameNotFoundException e) {
        return false;
    }

    for (Signature signature : packageInfo.signatures) {
        if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
            return true;
        }
    }
    return false;
}
 
Example #12
Source File: ServiceWatcher.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public static boolean isSignatureMatch(Signature[] signatures,
        List<HashSet<Signature>> sigSets) {
    if (signatures == null) return false;

    // build hashset of input to test against
    HashSet<Signature> inputSet = new HashSet<Signature>();
    for (Signature s : signatures) {
        inputSet.add(s);
    }

    // test input against each of the signature sets
    for (HashSet<Signature> referenceSet : sigSets) {
        if (referenceSet.equals(inputSet)) {
            return true;
        }
    }
    return false;
}
 
Example #13
Source File: ShortcutPackageInfo.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void refreshSignature(ShortcutService s, ShortcutPackageItem pkg) {
    if (mIsShadow) {
        s.wtf("Attempted to refresh package info for shadow package " + pkg.getPackageName()
                + ", user=" + pkg.getOwnerUserId());
        return;
    }
    // Note use mUserId here, rather than userId.
    final PackageInfo pi = s.getPackageInfoWithSignatures(
            pkg.getPackageName(), pkg.getPackageUserId());
    if (pi == null) {
        Slog.w(TAG, "Package not found: " + pkg.getPackageName());
        return;
    }
    // retrieve the newest sigs
    SigningInfo signingInfo = pi.signingInfo;
    if (signingInfo == null) {
        Slog.w(TAG, "Not refreshing signature for " + pkg.getPackageName()
                + " since it appears to have no signing info.");
        return;
    }
    // TODO (b/73988180) use entire signing history in case of rollbacks
    Signature[] signatures = signingInfo.getApkContentsSigners();
    mSigHashes = BackupUtils.hashSignatureArray(signatures);
}
 
Example #14
Source File: SecurityHelper.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public static boolean containSign(Signature asignature[], String s)
{
    if (asignature != null && s != null)
    {
        int i = asignature.length;
        int j = 0;
        while (j < i) 
        {
            if (s.equals(MD5.hexdigest(asignature[j].toByteArray())))
            {
                return true;
            }
            j++;
        }
    }
    return false;
}
 
Example #15
Source File: AppSignatureHelper.java    From android-credentials with Apache License 2.0 6 votes vote down vote up
/**
 * Get all the app signatures for the current package
 * @return
 */
public ArrayList<String> getAppSignatures() {
    ArrayList<String> appCodes = new ArrayList<>();

    try {
        // Get all package signatures for the current package
        String packageName = getPackageName();
        PackageManager packageManager = getPackageManager();
        Signature[] signatures = packageManager.getPackageInfo(packageName,
                PackageManager.GET_SIGNATURES).signatures;

        // For each signature create a compatible hash
        for (Signature signature : signatures) {
            String hash = hash(packageName, signature.toCharsString());
            if (hash != null) {
                appCodes.add(String.format("%s", hash));
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "Unable to find package to obtain hash.", e);
    }
    return appCodes;
}
 
Example #16
Source File: IApkManagerImpl.java    From letv with Apache License 2.0 6 votes vote down vote up
private Signature[] readSignatures(String packageName) {
    List<String> fils = PluginDirHelper.getPluginSignatureFiles(this.mContext, packageName);
    List<Signature> signatures = new ArrayList(fils.size());
    int i = 0;
    for (String file : fils) {
        try {
            byte[] data = Utils.readFromFile(new File(file));
            if (data != null) {
                Signature sin = new Signature(data);
                signatures.add(sin);
                JLog.log("plugin", "读取签名信息 包名=" + packageName + ",i=" + i + ",签名md5=" + Utils.md5(sin.toByteArray()));
                i++;
            } else {
                JLog.log("plugin", "读取签名信息失败 i=" + i);
                return null;
            }
        } catch (Exception e) {
            JLog.log("plugin", "读取签名信息失败 e=" + e.getMessage());
            return null;
        }
    }
    return (Signature[]) signatures.toArray(new Signature[signatures.size()]);
}
 
Example #17
Source File: VPackageManagerService.java    From container with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
	synchronized (mPackages) {
		PackageParser.Package pkg = mPackages.get(packageName);
		if (pkg != null) {
			AppSetting setting = (AppSetting) pkg.mExtras;
			if ((flags & PackageManager.GET_SIGNATURES) != 0 && pkg.mSignatures == null) {
				if (pkg.mAppMetaData != null && pkg.mAppMetaData.containsKey(Constants.FEATURE_FAKE_SIGNATURE)) {
					String sig = pkg.mAppMetaData.getString("fake-signature");
					if (sig != null) {
						pkg.mSignatures = new Signature[] {new Signature(sig)};
					}
				} else {
					PackageParserCompat.collectCertificates(setting.parser, pkg, PackageParser.PARSE_IS_SYSTEM);
				}
			}
			PackageInfo packageInfo = PackageParserCompat.generatePackageInfo(pkg, flags,
					getFirstInstallTime(pkg), getLastInstallTime(pkg));
			if (packageInfo != null) {
				ComponentFixer.fixApplicationInfo(setting, packageInfo.applicationInfo, userId);
				return packageInfo;
			}
		}
	}
	return null;
}
 
Example #18
Source File: Update.java    From styT with Apache License 2.0 6 votes vote down vote up
private void setViewPager() {
    final String packname = getPackageName();
    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(packname, PackageManager.GET_SIGNATURES);
        Signature[] signs = packageInfo.signatures;
        Signature sign = signs[0];
        int code = sign.hashCode();
        if (code != 312960342) {
            ti();
        } else {
            //
        }
    } catch (PackageManager.NameNotFoundException ignored) {
    }
    fragments = new ArrayList<Fragment>();
    viewPager.setAdapter(viewPagerAdapter);
    mTabLayout.setupWithViewPager(viewPager);
    mTabLayout.setTabsFromPagerAdapter(viewPagerAdapter);
}
 
Example #19
Source File: PackageInfoAssembler.java    From under-the-hood with Apache License 2.0 6 votes vote down vote up
/**
 * Creates page-entries for all the apks signatures and shows sh256 hash of it
 *
 * @param packageInfo  from {@link PackageManager#getPackageInfo(String, int)} requiring {@link PackageManager#GET_SIGNATURES} flag
 * @param refSha256Map a map of key: name of signature and value: first x digits of sha256 hash of signature; used for adding name to specific signature (i.e. "debug key")
 * @return entries
 */
public static List<PageEntry<?>> createPmSignatureHashInfo(@NonNull PackageInfo packageInfo, @NonNull Map<String, String> refSha256Map) {
    List<PageEntry<?>> entries = new ArrayList<>();
    try {
        for (Signature signature : packageInfo.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(signature.toByteArray());

            String sha256 = HoodUtil.byteToHex(md.digest());
            String key = "apk-signature-sha256";
            for (Map.Entry<String, String> refEntry : refSha256Map.entrySet()) {
                if (sha256.toLowerCase().startsWith(refEntry.getValue().toLowerCase())) {
                    key += " (" + refEntry.getKey() + ")";
                }
            }
            entries.add(Hood.get().createPropertyEntry(key, sha256, true));
        }
    } catch (Exception e) {
        throw new IllegalStateException("could not create hash", e);
    }
    return entries;
}
 
Example #20
Source File: AndroidUtilities.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
public static String getCertificateSHA256Fingerprint() {
    PackageManager pm = ApplicationLoader.applicationContext.getPackageManager();
    String packageName = ApplicationLoader.applicationContext.getPackageName();
    try {
        PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        Signature[] signatures = packageInfo.signatures;
        byte[] cert = signatures[0].toByteArray();
        InputStream input = new ByteArrayInputStream(cert);
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        X509Certificate c = (X509Certificate) cf.generateCertificate(input);
        return Utilities.bytesToHex(Utilities.computeSHA256(c.getEncoded()));
    } catch (Throwable ignore) {

    }
    return "";
}
 
Example #21
Source File: c.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public static boolean a(Context context, Signature asignature[], boolean flag)
{
    if (!flag)
    {
        com.tencent.mm.sdk.b.a.c("MicroMsg.SDK.WXMsgImplComm", "ignore wechat app signature validation");
        return true;
    }
    int i = asignature.length;
    for (int j = 0; j < i; j++)
    {
        String s = asignature[j].toCharsString().toLowerCase();
        com.tencent.mm.sdk.b.a.c("MicroMsg.SDK.WXMsgImplComm", (new StringBuilder("check signature:")).append(s).toString());
        if (s.equals("308202eb30820254a00302010202044d36f7a4300d06092a864886f70d01010505003081b9310b300906035504061302383631123010060355040813094775616e67646f6e673111300f060355040713085368656e7a68656e31353033060355040a132c54656e63656e7420546563686e6f6c6f6779285368656e7a68656e2920436f6d70616e79204c696d69746564313a3038060355040b133154656e63656e74204775616e677a686f7520526573656172636820616e6420446576656c6f706d656e742043656e7465723110300e0603550403130754656e63656e74301e170d3131303131393134333933325a170d3431303131313134333933325a3081b9310b300906035504061302383631123010060355040813094775616e67646f6e673111300f060355040713085368656e7a68656e31353033060355040a132c54656e63656e7420546563686e6f6c6f6779285368656e7a68656e2920436f6d70616e79204c696d69746564313a3038060355040b133154656e63656e74204775616e677a686f7520526573656172636820616e6420446576656c6f706d656e742043656e7465723110300e0603550403130754656e63656e7430819f300d06092a864886f70d010101050003818d0030818902818100c05f34b231b083fb1323670bfbe7bdab40c0c0a6efc87ef2072a1ff0d60cc67c8edb0d0847f210bea6cbfaa241be70c86daf56be08b723c859e52428a064555d80db448cdcacc1aea2501eba06f8bad12a4fa49d85cacd7abeb68945a5cb5e061629b52e3254c373550ee4e40cb7c8ae6f7a8151ccd8df582d446f39ae0c5e930203010001300d06092a864886f70d0101050500038181009c8d9d7f2f908c42081b4c764c377109a8b2c70582422125ce545842d5f520aea69550b6bd8bfd94e987b75a3077eb04ad341f481aac266e89d3864456e69fba13df018acdc168b9a19dfd7ad9d9cc6f6ace57c746515f71234df3a053e33ba93ece5cd0fc15f3e389a3f365588a9fcb439e069d3629cd7732a13fff7b891499"))
        {
            com.tencent.mm.sdk.b.a.c("MicroMsg.SDK.WXMsgImplComm", "pass");
            return true;
        }
    }

    return false;
}
 
Example #22
Source File: Util.java    From Popeens-DSub with GNU General Public License v3.0 6 votes vote down vote up
public static boolean validateAppSignature(Context context) {
	try {
		// get the signature form the package manager
		PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
		Signature[] appSignatures = packageInfo.signatures;
		// this sample only checks the first certificate
		for (Signature signature : appSignatures) {
			byte[] signatureBytes = signature.toByteArray();
			// calc sha1 in hex
			String currentSignature = calcSHA1(signatureBytes);
			// compare signatures
			Log.i("ValidateSigningCert", "Signature is " + currentSignature + " (" + CERTIFICATE_SHA1 + ")");
			return CERTIFICATE_SHA1.equalsIgnoreCase(currentSignature);
		}
	} catch (Exception e) { // if error assume failed to validate
		return false;
	}

	return false;
}
 
Example #23
Source File: TalkProtocol.java    From kakao-android-sdk-standalone with Apache License 2.0 6 votes vote down vote up
private static boolean validateTalkSignatureAndMinVersion(final Context context, final String packageName, final int minVersion) {
    PackageInfo talkPackageInfo;
    try {
        talkPackageInfo = context.getPackageManager().getPackageInfo(packageName,
                PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }

    if(minVersion > 0){
        if(talkPackageInfo.versionCode < minVersion)
            return false;
    }

    for (Signature signature : talkPackageInfo.signatures) {
        String signatureCharsString = signature.toCharsString();
        if (signatureCharsString.equals(RELEASE_TAlk_SIGNATURE) ||
            signatureCharsString.equals(DEBUG_TAlk_SIGNATURE)) {
            return true;
        }
    }
    return false;
}
 
Example #24
Source File: PackageUtils.java    From android_packages_apps_GmsCore with Apache License 2.0 6 votes vote down vote up
@Nullable
public static String firstSignatureDigest(PackageManager packageManager, String packageName) {
    final PackageInfo info;
    try {
        info = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException e) {
        return null;
    }
    if (info != null && info.signatures != null && info.signatures.length > 0) {
        for (Signature sig : info.signatures) {
            String digest = sha1sum(sig.toByteArray());
            if (digest != null) {
                return digest;
            }
        }
    }
    return null;
}
 
Example #25
Source File: SignaturesUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 判断 debug 签名还是 release 签名
 * @param signatures {@link Signature}[]
 * @return {@code true} debug.keystore, {@code false} release.keystore
 */
public static boolean isDebuggable(final Signature[] signatures) {
    // 默认属于 debug 签名
    boolean debuggable = true;
    if (signatures != null) {
        try {
            for (int i = 0, len = signatures.length; i < len; i++) {
                Signature s = signatures[i];
                if (s != null) {
                    X509Certificate cert = getX509Certificate(s);
                    debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
                    if (debuggable) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            LogPrintUtils.eTag(TAG, e, "isDebuggable");
        }
    }
    return debuggable;
}
 
Example #26
Source File: IApkManagerImpl.java    From letv with Apache License 2.0 6 votes vote down vote up
public PackageInfo getPackageInfo(String packageName, int flags) throws RemoteException {
    waitForReadyInner();
    try {
        String pkg = getAndCheckCallingPkg(packageName);
        if (pkg != null) {
            enforcePluginFileExists();
            PluginPackageParser parser = (PluginPackageParser) this.mPluginCache.get(pkg);
            if (parser != null) {
                PackageInfo packageInfo = parser.getPackageInfo(flags);
                if (packageInfo == null || (flags & 64) == 0 || packageInfo.signatures != null) {
                    return packageInfo;
                }
                packageInfo.signatures = (Signature[]) this.mSignatureCache.get(packageName);
                return packageInfo;
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
    return null;
}
 
Example #27
Source File: AppProtocolTest.java    From rides-android-sdk with MIT License 6 votes vote down vote up
private void stubAppSignature(String... sig) {
    when(activity.getPackageName()).thenReturn(AppProtocol.RIDER_PACKAGE_NAMES[0]);
    when(activity.getPackageManager()).thenReturn(packageManager);

    Signature[] signatures = new Signature[sig.length];
    for (int i = 0; i < sig.length; i++) {
        signatures[i] = new Signature(sig[i]);
    }

    packageInfo.signatures = signatures;

    try {
        when(packageManager.getPackageInfo(eq(AppProtocol.RIDER_PACKAGE_NAMES[0]), anyInt()))
                .thenReturn(packageInfo);
    } catch (PackageManager.NameNotFoundException e) {
        fail("Unable to mock Package Manager");
    }
}
 
Example #28
Source File: CrashApplication.java    From NClientV2 with Apache License 2.0 6 votes vote down vote up
private boolean signatureCheck(){
    try {
        @SuppressLint("PackageManagerGetSignatures")
        PackageInfo packageInfo = getPackageManager().getPackageInfo(
                getPackageName(), PackageManager.GET_SIGNATURES);
        //note sample just checks the first signature

        for (Signature signature : packageInfo.signatures) {
            // MD5 is used because it is not a secure data
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(signature.toByteArray());
            String hash = new BigInteger(1, m.digest()).toString(16);
            LogUtility.d("Find signature: " + hash);
            if(SIGNATURE_GITHUB.equals(hash))return true;
        }
    }catch (NullPointerException|PackageManager.NameNotFoundException| NoSuchAlgorithmException e){
        e.printStackTrace();
    }
    return false;
}
 
Example #29
Source File: Util.java    From android-perftracking with MIT License 6 votes vote down vote up
/**
 * Check if the application is debuggable.
 *
 * <p>This method check if the application is signed by a debug key.
 * https://stackoverflow.com/questions/7085644/how-to-check-if-apk-is-signed-or-debug-build
 *
 * @param context application context
 * @return true if app is debuggable, false otherwise
 */
@RestrictTo(LIBRARY)
@VisibleForTesting(otherwise = PACKAGE_PRIVATE)
static boolean isAppDebuggable(@NonNull final Context context) {
  try {
    PackageManager packageManager = context.getPackageManager();
    PackageInfo packageInfo =
        packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
    Signature[] signatures = packageInfo.signatures;

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

    for (Signature signature : signatures) {
      ByteArrayInputStream stream = new ByteArrayInputStream(signature.toByteArray());
      X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(stream);
      String principal = cert.getSubjectX500Principal().toString().toUpperCase();
      return principal.contains("C=US")
          && principal.contains("O=ANDROID")
          && principal.contains("CN=ANDROID DEBUG");
    }
  } catch (Exception e) {
    // Things went south, anyway the app is not debuggable.
  }
  return false;
}
 
Example #30
Source File: HwPushManager.java    From imsdk-android with MIT License 6 votes vote down vote up
/**
 * 获取相应的类型的字符串(把签名的byte[]信息转换成16进制)
 *
 * @param sig
 * @param type
 *
 * @return
 */
public static String getSignatureString(Signature sig, String type)
{
    byte[] hexBytes = sig.toByteArray();
    String fingerprint = "error!";
    try
    {
        MessageDigest digest = MessageDigest.getInstance(type);
        if (digest != null)
        {
            byte[] digestBytes = digest.digest(hexBytes);
            StringBuilder sb = new StringBuilder();
            for (byte digestByte : digestBytes)
            {
                sb.append((Integer.toHexString((digestByte & 0xFF) | 0x100)).substring(1, 3));
            }
            fingerprint = sb.toString();
        }
    }
    catch (NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }

    return fingerprint;
}