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:Main.java

/**
 * Returns the key hashes of the signatures of the app with the specified package name
 * which may be needed when integrating with 3rd party services such as Facebook. Note that
 * Android apps usually only have one signature.
 *
 * @param context/* w ww.  j a v a 2s .  com*/
 * @param packageName The package name of the app
 * @return The key hashes
 */
public static List<String> getKeyHashes(Context context, String packageName) {
    try {
        List<String> hashes = new ArrayList<>();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName,
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            hashes.add(Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
        return hashes;
    } catch (PackageManager.NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }
    return null;
}

From source file:com.github.javiersantos.piracychecker.LibraryUtils.java

@SuppressLint("PackageManagerGetSignatures")
static String getCurrentSignature(Context context) {
    String res = "";
    try {/*  w w  w  .  jav a  2s.  c  o m*/
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_SIGNATURES);
        for (Signature signature : packageInfo.signatures) {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            messageDigest.update(signature.toByteArray());
            res = Base64.encodeToString(messageDigest.digest(), Base64.DEFAULT);
        }
    } catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException ignored) {
    }
    return res.trim();
}

From source file:Main.java

private static Signature[] getSignatures(final Context context) throws PackageManager.NameNotFoundException {
    PackageInfo packageInfo = context.getPackageManager().getPackageInfo(getPackageName(context),
            PackageManager.GET_SIGNATURES);
    Signature[] signatures = packageInfo.signatures;
    return signatures;
}

From source file:Main.java

/**
 * Because of a BUG of Android (API 13-),
 * get signature info by using "getPackageArchiveInfo" of "PackageManager"
 * always causes "NullPointerException".
 * Lack of code in method "getPackageArchiveInfo":
 *     if ((flags & GET_SIGNATURES) != 0)
 *     {/*from ww  w.  ja  va 2  s .c  om*/
 *         packageParser.collectCertificates(pkg, 0);
 *     }
 */
@SuppressWarnings("unchecked")
public static PackageInfo getPackageArchiveInfo(String archiveFilePath, int flags) {
    try {
        Class packageParserClass = Class.forName("android.content.pm.PackageParser");
        Class[] innerClasses = packageParserClass.getDeclaredClasses();
        Class packageParserPackageClass = null;
        for (Class innerClass : innerClasses) {
            if (0 == innerClass.getName().compareTo("android.content.pm.PackageParser$Package")) {
                packageParserPackageClass = innerClass;
                break;
            }
        }
        Constructor packageParserConstructor = packageParserClass.getConstructor(String.class);
        Method parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class,
                String.class, DisplayMetrics.class, int.class);
        Method collectCertificatesMethod = packageParserClass.getDeclaredMethod("collectCertificates",
                packageParserPackageClass, int.class);
        Method generatePackageInfoMethod = packageParserClass.getDeclaredMethod("generatePackageInfo",
                packageParserPackageClass, int[].class, int.class, long.class, long.class);
        packageParserConstructor.setAccessible(true);
        parsePackageMethod.setAccessible(true);
        collectCertificatesMethod.setAccessible(true);
        generatePackageInfoMethod.setAccessible(true);

        Object packageParser = packageParserConstructor.newInstance(archiveFilePath);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        displayMetrics.setToDefaults();

        final File sourceFile = new File(archiveFilePath);

        Object pkg = parsePackageMethod.invoke(packageParser, sourceFile, archiveFilePath, displayMetrics, 0);
        if (pkg == null) {
            return null;
        }

        if ((flags & PackageManager.GET_SIGNATURES) != 0) {
            collectCertificatesMethod.invoke(packageParser, pkg, 0);
        }

        return (PackageInfo) generatePackageInfoMethod.invoke(null, pkg, null, flags, 0, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.commonsware.android.signature.dump.SigSaver.java

@Override
protected void onHandleWork(@NonNull Intent intent) {
    String packageName = intent.getStringExtra(EXTRA_PACKAGE);

    try {//  w ww . j  av a2s . c  o m
        PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName,
                PackageManager.GET_SIGNATURES);
        File output = new File(getExternalFilesDir(null), packageInfo.packageName.replace('.', '_') + ".bin");

        if (output.exists()) {
            output.delete();
        }

        Signature[] signatures = packageInfo.signatures;
        byte[] raw = signatures[0].toByteArray();

        try {
            FileOutputStream fos = new FileOutputStream(output.getPath());

            fos.write(raw);
            fos.close();
        } catch (java.io.IOException e) {
            Log.e(getClass().getSimpleName(), "Exception in writing signature file", e);
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(getClass().getSimpleName(), "Exception loading package info: " + packageName, e);
    }
}

From source file:com.commonsware.android.signature.dump.MainActivity.java

@Override
public List<PackageInfo> getPackageList() {
    List<PackageInfo> result = mgr.getInstalledPackages(PackageManager.GET_SIGNATURES);

    Collections.sort(result, new Comparator<PackageInfo>() {
        @Override/*w  ww .ja v  a 2  s.co  m*/
        public int compare(final PackageInfo a, final PackageInfo b) {
            return (a.packageName.compareTo(b.packageName));
        }
    });

    return (result);
}

From source file:com.hkm.Application.appWork.java

private void showpackagesigning() {
    PackageInfo packageInfo;/*www. j  a v a 2  s. com*/
    try {
        packageInfo = getPackageManager().getPackageInfo("com.hkm.oc.app", PackageManager.GET_SIGNATURES);
        for (Signature signature : packageInfo.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            String key = new String(Base64.encode(md.digest(), 0));
            // String key = new String(Base64.encodeBytes(md.digest()));
            Log.e("Hash key", sha1Hash(key));
        }
    } catch (PackageManager.NameNotFoundException e1) {
        Log.e("Name not found", e1.toString());
    } catch (NoSuchAlgorithmException e) {
        Log.e("No such an algorithm", e.toString());
    } catch (Exception e) {
        Log.e("Exception", e.toString());
    }
}

From source file:com.ibm.mobileclientaccess.fbauth.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    infoTextView = (TextView) findViewById(R.id.info);

    MCAAuthorizationManager.createInstance(this);

    Logger.setSDKDebugLoggingEnabled(true);

    /*/*from  w w w. j a va  2 s  .  co  m*/
    There may be issues with the hash key for the app, because it may not be correct when using from command line
    https://developers.facebook.com/docs/android/getting-started#release-key-hash (troubleshoot section)
    Add this code (and remove after getting the correct key (debug? release)) for this will print to log the correct hash code.
     */
    try {
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }

    try {
        //Register to the server with backendroute and GUID
        BMSClient.getInstance().initialize(this, backendRoute, backendGUID, BMSClient.REGION_UK);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Register the default delegate for Facebook
    FacebookAuthenticationManager.getInstance().register(this);
    Logger.setSDKDebugLoggingEnabled(true);
}

From source file:com.facebook.samples.sessionlogin.LoginUsingActivityActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);/*  w w  w  .ja va  2  s  .c  o  m*/
    Log.v("msg", "hello");
    try {
        PackageInfo info = getPackageManager().getPackageInfo("com.facebook.samples.sessionlogin",
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

    buttonLoginLogout = (Button) findViewById(R.id.buttonLoginLogout);
    textInstructionsOrLink = (TextView) findViewById(R.id.instructionsOrLink);

    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session == null) {
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
        }
        if (session == null) {
            session = new Session(this);
        }
        Session.setActiveSession(session);
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        }
    }
    Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this,
            Arrays.asList("friends_birthday"));
    session.requestNewReadPermissions(newPermissionsRequest);
    updateView();
}

From source file:br.com.hotforms.FacebookHash.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false otherwise.
 *//*ww w. j  a  va2s.c  om*/
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
        throws JSONException {
    Log.v(TAG, "Executing action: " + action);
    final Activity activity = this.cordova.getActivity();
    final Window window = activity.getWindow();

    if ("getHash".equals(action)) {
        try {
            String packageName = activity.getClass().getPackage().getName();
            PackageManager packageManager = activity.getPackageManager();
            PackageInfo info = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String hash = Base64.encodeToString(md.digest(), Base64.DEFAULT);

                String result = String.format("{ FacebookHash : \"%s\", PackageName : \"%s\"}", hash.trim(),
                        packageName);
                callbackContext.success(result);
            }
        } catch (NameNotFoundException e) {
            callbackContext.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            callbackContext.error(e.getMessage());
        }
        return true;
    }

    return false;
}