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:com.facebook.FacebookSdk.java

/**
 * Internal call please don't use directly.
 * @param context The application context.
 * @return The application signature.//www .  j av  a 2s .  com
 */
public static String getApplicationSignature(Context context) {
    Validate.sdkInitialized();
    if (context == null) {
        return null;
    }
    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:id.ridon.keude.AppDetailsData.java

/**
 * If passed null, this will show a message to the user ("Could not find app ..." or something
 * like that) and then finish the activity.
 *///w w  w. jav a  2 s.  c  o m
private void setApp(App newApp) {

    if (newApp == null) {
        Toast.makeText(this, getString(R.string.no_such_app), Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    app = newApp;

    startingIgnoreAll = app.ignoreAllUpdates;
    startingIgnoreThis = app.ignoreThisUpdate;

    // Get the signature of the installed package...
    mInstalledSignature = null;
    mInstalledSigID = null;

    if (app.isInstalled()) {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(app.id, PackageManager.GET_SIGNATURES);
            mInstalledSignature = pi.signatures[0];
            Hasher hash = new Hasher("MD5", mInstalledSignature.toCharsString().getBytes());
            mInstalledSigID = hash.getHash();
        } catch (NameNotFoundException e) {
            Log.d(TAG, "Failed to get installed signature");
        } catch (NoSuchAlgorithmException e) {
            Log.d(TAG, "Failed to calculate signature MD5 sum");
            mInstalledSignature = null;
        }
    }
}

From source file:com.jungle.base.utils.MiscUtils.java

public static String getPackageSign(Context context, String packageName) {
    PackageInfo info = null;//from   w  w w .  j  a v  a 2  s.c o  m
    try {
        info = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return null;
    }

    MessageDigest md5 = null;
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }

    for (int i = 0; i < info.signatures.length; ++i) {
        byte[] bytes = info.signatures[i].toByteArray();
        if (bytes != null) {
            md5.update(bytes);
        }
    }

    return MiscUtils.serializationBytesToHex(md5.digest());
}

From source file:android.content.pm.PackageParser.java

public static PackageInfo generatePackageInfo(PackageParser.Package p, int gids[], int flags,
        long firstInstallTime, long lastUpdateTime, Set<String> grantedPermissions, PackageUserState state,
        int userId) {

    if (!checkUseInstalledOrHidden(flags, state)) {
        return null;
    }//  w  ww.  j  a v a  2s.com
    PackageInfo pi = new PackageInfo();
    pi.packageName = p.packageName;
    pi.splitNames = p.splitNames;
    pi.versionCode = p.mVersionCode;
    pi.baseRevisionCode = p.baseRevisionCode;
    pi.splitRevisionCodes = p.splitRevisionCodes;
    pi.versionName = p.mVersionName;
    pi.sharedUserId = p.mSharedUserId;
    pi.sharedUserLabel = p.mSharedUserLabel;
    pi.applicationInfo = generateApplicationInfo(p, flags, state, userId);
    pi.installLocation = p.installLocation;
    pi.coreApp = p.coreApp;
    if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
            || (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
        pi.requiredForAllUsers = p.mRequiredForAllUsers;
    }
    pi.restrictedAccountType = p.mRestrictedAccountType;
    pi.requiredAccountType = p.mRequiredAccountType;
    pi.overlayTarget = p.mOverlayTarget;
    pi.firstInstallTime = firstInstallTime;
    pi.lastUpdateTime = lastUpdateTime;
    if ((flags & PackageManager.GET_GIDS) != 0) {
        pi.gids = gids;
    }
    if ((flags & PackageManager.GET_CONFIGURATIONS) != 0) {
        int N = p.configPreferences != null ? p.configPreferences.size() : 0;
        if (N > 0) {
            pi.configPreferences = new ConfigurationInfo[N];
            p.configPreferences.toArray(pi.configPreferences);
        }
        N = p.reqFeatures != null ? p.reqFeatures.size() : 0;
        if (N > 0) {
            pi.reqFeatures = new FeatureInfo[N];
            p.reqFeatures.toArray(pi.reqFeatures);
        }
        N = p.featureGroups != null ? p.featureGroups.size() : 0;
        if (N > 0) {
            pi.featureGroups = new FeatureGroupInfo[N];
            p.featureGroups.toArray(pi.featureGroups);
        }
    }
    if ((flags & PackageManager.GET_ACTIVITIES) != 0) {
        int N = p.activities.size();
        if (N > 0) {
            if ((flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
                pi.activities = new ActivityInfo[N];
            } else {
                int num = 0;
                for (int i = 0; i < N; i++) {
                    if (p.activities.get(i).info.enabled)
                        num++;
                }
                pi.activities = new ActivityInfo[num];
            }
            for (int i = 0, j = 0; i < N; i++) {
                final Activity activity = p.activities.get(i);
                if (activity.info.enabled || (flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
                    pi.activities[j++] = generateActivityInfo(p.activities.get(i), flags, state, userId);
                }
            }
        }
    }
    if ((flags & PackageManager.GET_RECEIVERS) != 0) {
        int N = p.receivers.size();
        if (N > 0) {
            if ((flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
                pi.receivers = new ActivityInfo[N];
            } else {
                int num = 0;
                for (int i = 0; i < N; i++) {
                    if (p.receivers.get(i).info.enabled)
                        num++;
                }
                pi.receivers = new ActivityInfo[num];
            }
            for (int i = 0, j = 0; i < N; i++) {
                final Activity activity = p.receivers.get(i);
                if (activity.info.enabled || (flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
                    pi.receivers[j++] = generateActivityInfo(p.receivers.get(i), flags, state, userId);
                }
            }
        }
    }
    if ((flags & PackageManager.GET_SERVICES) != 0) {
        int N = p.services.size();
        if (N > 0) {
            if ((flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
                pi.services = new ServiceInfo[N];
            } else {
                int num = 0;
                for (int i = 0; i < N; i++) {
                    if (p.services.get(i).info.enabled)
                        num++;
                }
                pi.services = new ServiceInfo[num];
            }
            for (int i = 0, j = 0; i < N; i++) {
                final Service service = p.services.get(i);
                if (service.info.enabled || (flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
                    pi.services[j++] = generateServiceInfo(p.services.get(i), flags, state, userId);
                }
            }
        }
    }
    if ((flags & PackageManager.GET_PROVIDERS) != 0) {
        int N = p.providers.size();
        if (N > 0) {
            if ((flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
                pi.providers = new ProviderInfo[N];
            } else {
                int num = 0;
                for (int i = 0; i < N; i++) {
                    if (p.providers.get(i).info.enabled)
                        num++;
                }
                pi.providers = new ProviderInfo[num];
            }
            for (int i = 0, j = 0; i < N; i++) {
                final Provider provider = p.providers.get(i);
                if (provider.info.enabled || (flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
                    pi.providers[j++] = generateProviderInfo(p.providers.get(i), flags, state, userId);
                }
            }
        }
    }
    if ((flags & PackageManager.GET_INSTRUMENTATION) != 0) {
        int N = p.instrumentation.size();
        if (N > 0) {
            pi.instrumentation = new InstrumentationInfo[N];
            for (int i = 0; i < N; i++) {
                pi.instrumentation[i] = generateInstrumentationInfo(p.instrumentation.get(i), flags);
            }
        }
    }
    if ((flags & PackageManager.GET_PERMISSIONS) != 0) {
        int N = p.permissions.size();
        if (N > 0) {
            pi.permissions = new PermissionInfo[N];
            for (int i = 0; i < N; i++) {
                pi.permissions[i] = generatePermissionInfo(p.permissions.get(i), flags);
            }
        }
        N = p.requestedPermissions.size();
        if (N > 0) {
            pi.requestedPermissions = new String[N];
            pi.requestedPermissionsFlags = new int[N];
            for (int i = 0; i < N; i++) {
                final String perm = p.requestedPermissions.get(i);
                pi.requestedPermissions[i] = perm;
                // The notion of required permissions is deprecated but for compatibility.
                pi.requestedPermissionsFlags[i] |= PackageInfo.REQUESTED_PERMISSION_REQUIRED;
                if (grantedPermissions != null && grantedPermissions.contains(perm)) {
                    pi.requestedPermissionsFlags[i] |= PackageInfo.REQUESTED_PERMISSION_GRANTED;
                }
            }
        }
    }
    if ((flags & PackageManager.GET_SIGNATURES) != 0) {
        int N = (p.mSignatures != null) ? p.mSignatures.length : 0;
        if (N > 0) {
            pi.signatures = new Signature[N];
            System.arraycopy(p.mSignatures, 0, pi.signatures, 0, N);
        }
    }
    return pi;
}

From source file:jp.mixi.android.sdk.MixiContainerImpl.java

/**
 * ?/*  ww w .  j a  va2 s  . c  om*/
 * 
 * @param activity ?Activity
 * @param intent Intent(?)
 * @return
 */
private boolean validateOfficialAppsForIntent(Context activity, Intent intent, int target,
        int supportedVersion) {
    String packageName = null;
    if (target == VALIDATE_OFFICIAL_FOR_ACTIVITY) {
        ResolveInfo resolveInfo = activity.getPackageManager().resolveActivity(intent, 0);
        if (resolveInfo == null) {
            Log.d(TAG, "official application not found");
            return false;
        }
        packageName = resolveInfo.activityInfo.packageName;
    } else if (target == VALIDATE_OFFICIAL_FOR_SERVICE) {
        ResolveInfo resolveInfo = activity.getPackageManager().resolveService(intent, 0);
        if (resolveInfo == null) {
            Log.d(TAG, "official application not found");
            return false;
        }
        packageName = resolveInfo.serviceInfo.packageName;
    } else {
        Log.d(TAG, "do not support option");
        return false;
    }
    try {
        PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(packageName,
                PackageManager.GET_SIGNATURES);
        if (packageInfo.versionCode < supportedVersion) {
            Log.d(TAG, "Unsupported version" + packageInfo.versionCode);
            return false;
        }
        // ?????
        return validateSignature(packageInfo.signatures);
    } catch (NameNotFoundException e) {
        Log.d(TAG, "NameNotFoundException");
        return false;
    }

}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
* Returns a list with the current signatures of the 
* application.//from  w  w  w  . jav a2s.c o  m
* 
* @param context   Application context
* @param appPackageName   The package name of the application.
* @return   A list or null if no signatures are found or error.
*/
public static List<String> application_getSignatures(Context context, String appPackageName) {
    List<String> appSignatures = null;

    try {
        if (appPackageName != null && appPackageName.length() > 0) {
            PackageInfo info = context.getPackageManager().getPackageInfo(appPackageName,
                    PackageManager.GET_SIGNATURES);
            appSignatures = new ArrayList<String>();
            String signatureString = null;
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                signatureString = android.util.Base64.encodeToString(md.digest(), android.util.Base64.DEFAULT);
                Log.d(ToolBox.TAG, "KeyHash (" + appPackageName + "): " + signatureString);
                appSignatures.add(signatureString);
            }
        } else {
            Log.d(ToolBox.TAG, "No package name to get signaturs from.");
        }
    } catch (NameNotFoundException e) {
        Log.e(ToolBox.TAG, "Error getting application (" + appPackageName + ") signatures. Package not found ["
                + e.getMessage() + "].", e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(ToolBox.TAG, "Error getting application (" + appPackageName
                + ") signatures. Algorithm SHA not found [" + e.getMessage() + "].", e);
    }

    return appSignatures;
}

From source file:com.eleybourn.bookcatalogue.utils.Utils.java

/**
 * Return the MD5 hash of the public key that signed this app, or a useful 
 * text message if an error or other problem occurred.
 *//*  w  ww  . j a  v  a2s.  c  o  m*/
public static String signedBy(Context context) {
    // Get value if no cached value exists
    if (mSignedBy == null) {
        try {
            // Get app info
            PackageManager manager = context.getPackageManager();
            PackageInfo appInfo = manager.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_SIGNATURES);
            // Each sig is a PK of the signer:
            //     https://groups.google.com/forum/?fromgroups=#!topic/android-developers/fPtdt6zDzns
            for (Signature sig : appInfo.signatures) {
                if (sig != null) {
                    final MessageDigest sha1 = MessageDigest.getInstance("MD5");
                    final byte[] publicKey = sha1.digest(sig.toByteArray());
                    // Turn the hex bytes into a more traditional MD5 string representation.
                    final StringBuffer hexString = new StringBuffer();
                    boolean first = true;
                    for (int i = 0; i < publicKey.length; i++) {
                        if (!first) {
                            hexString.append(":");
                        } else {
                            first = false;
                        }
                        String byteString = Integer.toHexString(0xFF & publicKey[i]);
                        if (byteString.length() == 1)
                            hexString.append("0");
                        hexString.append(byteString);
                    }
                    String fingerprint = hexString.toString();

                    // Append as needed (theoretically could have more than one sig */
                    if (mSignedBy == null)
                        mSignedBy = fingerprint;
                    else
                        mSignedBy += "/" + fingerprint;
                }
            }

        } catch (NameNotFoundException e) {
            // Default if package not found...kind of unlikely
            mSignedBy = "NOPACKAGE";

        } catch (Exception e) {
            // Default if we die
            mSignedBy = e.getMessage();
        }
    }
    return mSignedBy;
}