Example usage for android.content.pm PackageManager GET_SIGNATURES

List of usage examples for android.content.pm PackageManager GET_SIGNATURES

Introduction

In this page you can find the example usage for android.content.pm PackageManager GET_SIGNATURES.

Prototype

int GET_SIGNATURES

To view the source code for android.content.pm PackageManager GET_SIGNATURES.

Click Source Link

Document

PackageInfo flag: return information about the signatures included in the package.

Usage

From source file:android_network.hetnet.vpn_service.Util.java

public static String getFingerprint(Context context) {
    try {//from  ww  w. j av  a  2s.  c o  m
        PackageManager pm = context.getPackageManager();
        String pkg = context.getPackageName();
        PackageInfo info = pm.getPackageInfo(pkg, PackageManager.GET_SIGNATURES);
        byte[] cert = info.signatures[0].toByteArray();
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        byte[] bytes = digest.digest(cert);
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes)
            sb.append(Integer.toString(b & 0xff, 16).toLowerCase());
        return sb.toString();
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        return null;
    }
}

From source file:org.droid2droid.internal.AbstractRemoteAndroidImpl.java

public void pushMe(final Context context, final PublishListener listener, final int bufsize, final int flags,
        final long timeout) throws RemoteException, IOException {
    new AsyncTask<PublishListener, Integer, Object>() {

        private PublishListener listener;

        @Override/*from w w  w.  j ava  2 s . c  o  m*/
        protected Object doInBackground(PublishListener... params) {
            listener = params[0];
            FileInputStream in = null;
            int fd = -1;
            int connid = -1;
            int s;
            byte[] buf = new byte[bufsize];
            byte[] signature = null;
            try {
                PackageManager pm = context.getPackageManager();
                ApplicationInfo info = Droid2DroidManagerImpl.sAppInfo;
                String label = context.getString(info.labelRes);
                PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
                File filename = new File(info.publicSourceDir);

                int versionCode = pi.versionCode;
                signature = pi.signatures[0].toByteArray();

                long length = filename.length();
                connid = getConnectionId();
                if (V)
                    Log.v(TAG_INSTALL, PREFIX_LOG + "CLI propose apk " + info.packageName);
                fd = proposeApk(connid, label, info.packageName, versionCode, signature, length, flags,
                        timeout);
                if (fd > 0) {
                    // TODO: ask sender before send datas
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI it's accepted");
                    in = new FileInputStream(filename);
                    StringBuilder prog = new StringBuilder();
                    // TODO: multi thread for optimize read latency ?
                    long timeoutSendFile = 30000; // FIXME: Time out pour send file en dur.
                    long pos = 0;
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI send file");
                    while ((s = in.read(buf, 0, buf.length)) > 0) {
                        if (V) {
                            prog.append('*');
                            if (V)
                                Log.v(TAG_INSTALL, PREFIX_LOG + "" + prog.toString()); // TODO: A garder ?
                        }
                        if (!sendFileData(connid, fd, buf, s, pos, length, timeoutSendFile)) {
                            if (E)
                                Log.e(TAG_INSTALL, PREFIX_LOG + "Impossible to send file data");
                            throw new RemoteException();
                        }
                        pos += s;
                        publishProgress((int) ((double) pos / length * 10000L));
                    }
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI send file done");
                    if (installApk(connid, label, fd, flags, timeout)) {
                        if (V)
                            Log.v(TAG_INSTALL, PREFIX_LOG + "CLI apk is installed");
                        return 1;
                    } else {
                        if (V)
                            Log.v(TAG_INSTALL, PREFIX_LOG + "CLI install apk is canceled");
                        return new CancellationException("Install apk " + pi.packageName + " is canceled");
                    }
                } else {
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI install apk is accepted (" + fd + ")");
                    return fd;
                }
            } catch (NameNotFoundException e) {
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } catch (IOException e) {
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } catch (RemoteException e) {
                if (D)
                    Log.d(TAG_INSTALL, "Impossible to push apk (" + e.getMessage() + ")", e);
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // Ignore
                    }
                }
            }
        }

        private void cancelCurrentUpload(final long timeout, int fd, int connid) {
            if (connid != -1 && fd != -1) {
                try {
                    cancelFileData(connid, fd, timeout);
                } catch (RemoteException e1) {
                    // Ignore
                }
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            postPublishProgress(listener, values[0]);
        }

        @Override
        protected void onPostExecute(Object result) {
            if (result instanceof Throwable) {
                postPublishError(listener, (Throwable) result);
            } else
                postPublishFinish(listener, ((Integer) result).intValue());
        }
    }.execute(listener);
}

From source file:com.android.tv.settings.users.AppRestrictionsFragment.java

private void populateApps() {
    final Context context = getActivity();
    if (context == null)
        return;/*w  w  w  .jav  a  2s  . com*/
    final PackageManager pm = mPackageManager;
    final int userId = mUser.getIdentifier();

    // Check if the user was removed in the meantime.
    if (getExistingUser(mUserManager, mUser) == null) {
        return;
    }
    mAppList.removeAll();
    addLocationAppRestrictionsPreference();
    Intent restrictionsIntent = new Intent(Intent.ACTION_GET_RESTRICTION_ENTRIES);
    final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(restrictionsIntent, 0);
    for (AppRestrictionsHelper.SelectableAppInfo app : mHelper.getVisibleApps()) {
        String packageName = app.packageName;
        if (packageName == null)
            continue;
        final boolean isSettingsApp = packageName.equals(context.getPackageName());
        AppRestrictionsPreference p = new AppRestrictionsPreference(getPreferenceManager().getContext());
        final boolean hasSettings = resolveInfoListHasPackage(receivers, packageName);
        if (isSettingsApp) {
            // Settings app should be available to restricted user
            mHelper.setPackageSelected(packageName, true);
            continue;
        }
        PackageInfo pi = null;
        try {
            pi = mIPm.getPackageInfo(packageName,
                    PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.GET_SIGNATURES, userId);
        } catch (RemoteException e) {
            // Ignore
        }
        if (pi == null) {
            continue;
        }
        if (mRestrictedProfile && isAppUnsupportedInRestrictedProfile(pi)) {
            continue;
        }
        p.setIcon(app.icon != null ? app.icon.mutate() : null);
        p.setChecked(false);
        p.setTitle(app.activityName);
        p.setKey(getKeyForPackage(packageName));
        p.setPersistent(false);
        p.setOnPreferenceChangeListener(this);
        p.setSummary(getPackageSummary(pi, app));
        if (pi.requiredForAllUsers || isPlatformSigned(pi)) {
            p.setChecked(true);
            p.setImmutable(true);
            // If the app is required and has no restrictions, skip showing it
            if (!hasSettings)
                continue;
        } else if (!mNewUser && isAppEnabledForUser(pi)) {
            p.setChecked(true);
        }
        if (app.masterEntry == null && hasSettings) {
            requestRestrictionsForApp(packageName, p);
        }
        if (app.masterEntry != null) {
            p.setImmutable(true);
            p.setChecked(mHelper.isPackageSelected(packageName));
        }
        p.setOrder(MAX_APP_RESTRICTIONS * (mAppList.getPreferenceCount() + 2));
        mHelper.setPackageSelected(packageName, p.isChecked());
        mAppList.addPreference(p);
    }
    mAppListChanged = true;
    // If this is the first time for a new profile, install/uninstall default apps for profile
    // to avoid taking the hit in onPause(), which can cause race conditions on user switch.
    if (mNewUser && mFirstTime) {
        mFirstTime = false;
        mHelper.applyUserAppsStates(this);
    }
}

From source file:com.master.metehan.filtereagle.Util.java

public static boolean hasValidFingerprint(Context context) {
    try {//from  w  w  w  .ja va  2s  . c o  m
        PackageManager pm = context.getPackageManager();
        String pkg = context.getPackageName();
        PackageInfo info = pm.getPackageInfo(pkg, PackageManager.GET_SIGNATURES);
        byte[] cert = info.signatures[0].toByteArray();
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        byte[] bytes = digest.digest(cert);
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes)
            sb.append(Integer.toString(b & 0xff, 16).toLowerCase());
        String calculated = sb.toString();
        String expected = context.getString(R.string.fingerprint);
        return calculated.equals(expected);
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        return false;
    }
}

From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java

@SuppressLint("PackageManagerGetSignatures")
private List<String> getApkCertificateDigests() {
    List<String> apkCertificateDigests = new ArrayList<>();
    PackageManager pm = context.getPackageManager();
    PackageInfo packageInfo;//from   www  . j  a  va2s. co m
    try {
        packageInfo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException wtf) {
        return apkCertificateDigests;
    }
    Signature[] signatures = packageInfo.signatures;
    for (Signature signature : signatures) {
        try {
            MessageDigest md = MessageDigest.getInstance(SHA_256);
            md.update(signature.toByteArray());
            byte[] digest = md.digest();
            apkCertificateDigests.add(Base64.encodeToString(digest, Base64.NO_WRAP));
        } catch (NoSuchAlgorithmException ignored) {
        }
    }
    return apkCertificateDigests;
}

From source file:dentex.youtube.downloader.utils.Utils.java

public static int getSigHash(Activity act) {
    int currentHash = 0;
    try {/*from w w  w. j ava2s  . c  o  m*/
        Signature[] sigs = act.getPackageManager().getPackageInfo(act.getPackageName(),
                PackageManager.GET_SIGNATURES).signatures;

        for (Signature sig : sigs) {
            currentHash = sig.hashCode();
            logger("d", "getSigHash: App signature " + currentHash, DEBUG_TAG);
        }
    } catch (NameNotFoundException e) {
        Log.e(DEBUG_TAG, "getSigHash: App signature not found; " + e.getMessage());
    }
    return currentHash;
}

From source file:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java

@Nullable
private String getAppSignature() {
    // Cache this so we don't need to calculate the signature on every request
    if (mAppSignature != null) {
        return mAppSignature;
    }//from   w ww  .ja  v a 2  s .  c  o  m

    try {
        // Get signatures for the package
        Signature[] sigs = getPackageManager().getPackageInfo(getPackageName(),
                PackageManager.GET_SIGNATURES).signatures;

        // There should only be one signature, anything else is suspicious
        if (sigs == null || sigs.length > 1 || sigs.length == 0) {
            Log.w(TAG, "Either 0 or >1 signatures, returning null");
            return null;
        }

        byte[] certBytes = sigs[0].toByteArray();

        InputStream input = new ByteArrayInputStream(certBytes);
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(input);

        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] publicKey = md.digest(cert.getEncoded());

        // Build a hex string of the SHA1 Digest
        StringBuilder hexString = new StringBuilder();
        for (byte aPublicKey : publicKey) {
            // Convert each byte to hex
            String appendString = Integer.toHexString(0xFF & aPublicKey);
            if (appendString.length() == 1) {
                hexString.append("0");
            }

            // Convert to upper case and add ":" separators so it matches keytool output
            appendString = appendString.toUpperCase() + ":";

            hexString.append(appendString);
        }

        // Convert to string, chop off trailing colon
        String signature = hexString.toString();
        if (signature.endsWith(":")) {
            signature = signature.substring(0, signature.length() - 1);
        }

        // Set and return
        mAppSignature = signature;
        return mAppSignature;
    } catch (Exception e) {
        Log.e(TAG, "getSignature", e);
    }

    return null;
}

From source file:biz.bokhorst.xprivacy.Util.java

@SuppressLint("DefaultLocale")
public static boolean hasValidFingerPrint(Context context) {
    try {/*from   w  w  w. j  a  va  2  s . c om*/
        PackageManager pm = context.getPackageManager();
        String packageName = context.getPackageName();
        PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        byte[] cert = packageInfo.signatures[0].toByteArray();
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        byte[] bytes = digest.digest(cert);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; ++i)
            sb.append((Integer.toHexString((bytes[i] & 0xFF) | 0x100)).substring(1, 3).toLowerCase());
        String calculated = sb.toString();
        String expected = context.getString(R.string.fingerprint);
        return calculated.equals(expected);
    } catch (Throwable ex) {
        bug(null, ex);
        return false;
    }
}

From source file:com.facebook.Settings.java

public static String getApplicationSignature(Context context) {
    if (context == null) {
        return null;
    }//from  w  w  w  .java  2s.c o m
    PackageManager packageManager = context.getPackageManager();
    if (packageManager == null) {
        return null;
    }

    String packageName = context.getPackageName();
    PackageInfo pInfo;
    try {
        pInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException e) {
        return null;
    }

    Signature[] signatures = pInfo.signatures;
    if (signatures == null || signatures.length == 0) {
        return null;
    }

    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        return null;
    }

    md.update(pInfo.signatures[0].toByteArray());
    return Base64.encodeToString(md.digest(), Base64.URL_SAFE | Base64.NO_PADDING);
}

From source file:com.google.android.apps.dashclock.DashClockService.java

private CallbackData createCallbackData(int uid) {
    boolean hasDashClockSignature = false;
    String packageName = null;//  ww  w .ja  v  a2s.c o m
    PackageManager pm = getPackageManager();
    String[] packages = pm.getPackagesForUid(uid);
    if (packages != null && packages.length > 0) {
        try {
            PackageInfo pi = pm.getPackageInfo(packages[0], PackageManager.GET_SIGNATURES);
            packageName = pi.packageName;
            if (pi.signatures != null && pi.signatures.length == 1
                    && DashClockSignature.SIGNATURE.equals(pi.signatures[0])) {
                hasDashClockSignature = true;
            }
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    }

    CallbackData data = new CallbackData();
    data.mUid = uid;
    data.mPackage = packageName;
    data.mHasDashClockSignature = hasDashClockSignature;
    return data;
}