Example usage for android.content.pm Signature toByteArray

List of usage examples for android.content.pm Signature toByteArray

Introduction

In this page you can find the example usage for android.content.pm Signature toByteArray.

Prototype

public byte[] toByteArray() 

Source Link

Usage

From source file:selfie.time.HelloFacebookSampleActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }/*from  w  w  w .j  a  va 2 s  .co  m*/
    context = this;
    setContentView(R.layout.main);
    try {
        PackageInfo info = context.getPackageManager().getPackageInfo("selfie.time",
                PackageManager.GET_SIGNATURES); //Your package name here
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.e("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }
    final Typeface mFont = Typeface.createFromAsset(getAssets(), "bg.otf");
    final ViewGroup mContainer = (ViewGroup) findViewById(android.R.id.content).getRootView();
    Util.setAppFont(mContainer, mFont, false);

    et = (EditText) findViewById(R.id.editText1);
    loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
        @Override
        public void onUserInfoFetched(GraphUser user) {
            HelloFacebookSampleActivity.this.user = user;
            updateUI();
            handlePendingAction();
        }
    });

    profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
    greeting = (TextView) findViewById(R.id.greeting);

    postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
    postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Session session = Session.getActiveSession();
            if (session != null)
                onClickPostStatusUpdate();
            else
                Util.showInfoDialog(context, "Please login with Facebook first.");
        }
    });

    postPhotoButton = (Button) findViewById(R.id.postPhotoButton);
    postPhotoButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickPostPhoto();
        }
    });

    pickFriendsButton = (Button) findViewById(R.id.pickFriendsButton);
    pickFriendsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickPickFriends();
        }
    });

    postSelfieButton = (Button) findViewById(R.id.postSelfieButton);
    postSelfieButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Session session = Session.getActiveSession();
            if (!Util.isNetworkAvailable(context))
                Util.showWifiDialog(context);
            else if (et.getText().toString().length() == 0)
                Util.showInfoDialog(context, "Please enter text to share with this selfie.");
            else if (session == null || !session.isOpened())
                Util.showInfoDialog(context, "Please login with Facebook first.");
            else
                initCapturePhoto(REQUEST_IMAGE_CAPTURE);
        }
    });

    controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);

    final FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment != null) {
        // If we're being re-created and have a fragment, we need to a) hide the main UI controls and
        // b) hook up its listeners again.
        controlsContainer.setVisibility(View.GONE);
        if (fragment instanceof FriendPickerFragment) {
            setFriendPickerListeners((FriendPickerFragment) fragment);
        } else if (fragment instanceof PlacePickerFragment) {
            setPlacePickerListeners((PlacePickerFragment) fragment);
        }
    }

    // Listen for changes in the back stack so we know if a fragment got popped off because the user
    // clicked the back button.
    fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (fm.getBackStackEntryCount() == 0) {
                // We need to re-show our UI.
                controlsContainer.setVisibility(View.VISIBLE);
            }
        }
    });

    // Can we present the share dialog for regular links?
    canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
    // Can we present the share dialog for photos?
    canPresentShareDialogWithPhotos = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.PHOTOS);
}

From source file:com.prad.yahooweather.YahooWeatherActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }//from w  ww.  ja v a2  s .  com

    setContentView(R.layout.weather_layout);
    mImageView = (ImageView) findViewById(R.id.feed_image);

    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo("com.prad.yahooweather",
                PackageManager.GET_SIGNATURES);
        // 9Q4TYYAtIO1mNDFa+Y57Ausm5lE=

        // Yahoo Weather
        // App ID: 612655528781332
        // App Secret: c6ae83d7cf1aeba1c01045bd37f1db31

        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (Exception e) {

    }

    View f = (View) findViewById(R.id.resultTable);
    f.setVisibility(View.GONE);

    searchText = (EditText) findViewById(R.id.searchText);
    searchButton = (Button) findViewById(R.id.search_button);
    radioGroup = (RadioGroup) findViewById(R.id.searchTypeRadioGroup);

    mImageView.setLongClickable(true);
    mImageView.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            Session session = Session.getActiveSession();
            if (session != null) {
                session.closeAndClearTokenInformation();
            } else {
                Session session2 = Session.openActiveSession(YahooWeatherActivity.this, false, null);
                if (session2 != null)
                    session2.closeAndClearTokenInformation();
            }

            return true;
        }
    });

    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String searchType = "";
            boolean isValidInput = false;
            hideKeyboard();
            String searchString = searchText.getText().toString();

            if (searchString == null || "".equals(searchString)) {
                Toast.makeText(YahooWeatherActivity.this, "Text field is empty. Please enter zip or city name.",
                        Toast.LENGTH_SHORT).show();
            } else {

                if (checkIfValidZip(searchString)) {
                    searchType = "zip";
                    isValidInput = true;
                } else {
                    if (checkIfValidCity(searchString)) {
                        searchType = "city";
                        isValidInput = true;
                    }
                }

            }

            if (isValidInput) {

                new GetJSON().execute(searchString, searchType, getTempTyep());
            }

        }
    });

    postStatusUpdateButton = (TextView) findViewById(R.id.current_weather);
    postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            pendingAction = PendingAction.CURRENT_WEATHER;

            showFacebookshareDialog("Post Current Weather");

        }
    });

    postPhotoButton = (TextView) findViewById(R.id.weather_forecast);
    postPhotoButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            pendingAction = PendingAction.WEATHER_FORECAST;

            showFacebookshareDialog("Post Weather Forecast");

        }
    });

    canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
    canPresentShareDialog = true;
}

From source file:com.ved.musicmapapp.LoginAcitivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_login_facebook);
    checkGooglePlayService();/*from  w  ww .j ava  2s  .  c o  m*/

    isMusics = false;
    isMovies = false;
    isBooks = false;
    isGames = false;
    isMe = false;

    prefs = getSharedPreferences("MUSIC_MAP", MODE_PRIVATE);
    edt = prefs.edit();

    btnLogin = findViewById(R.id.btn_login);
    TextView discover_heading = (TextView) findViewById(R.id.discover_heading);
    Typeface tf = Typeface.createFromAsset(getAssets(), "open_sans_regular.ttf");
    discover_heading.setTypeface(tf);

    btnLogin.setOnClickListener(this);

    pd = new ProgressDialog(this);
    pd.setMessage("Logging...");
    pd.setCancelable(false);

    if (getIntent().getBooleanExtra("LOGOUT", false)) {
        onClickLogout();
    }

    initFacebook(savedInstanceState);

    try {
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("PXR", com.ved.musicmapapp.utils.Base64.encodeBytes(md.digest()));
        }
    } catch (NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }

    updateView();
}

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.
 *///from  www .  j av  a  2 s  .  co  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;
}

From source file:com.appdupe.flamer.LoginUsingFacebook.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);//from ww  w .  ja  va  2 s. c  o m

    /**
     * This code is required only once, to get the KeyHash, which will be
     * used in facebook while signing the app. The KeyHash will be displayed
     * in LogCat. Once the Keyhash has been generated, use it for signing
     * app, and then comment the code. Replace the package name with your
     * package name.
     */
    try {
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {
        Log.e(TAG, "Exception(NameNotFoundException) : " + e);

    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Exception(NoSuchAlgorithmException) : " + e);
    }

    res = getResources();
    initdata();
    context = getApplicationContext();

    imagelist = new ArrayList<GellaryData>();
    mAdapterForGalery = new HomeAdapter(this, imagelist);
    galleryforsuprvisore.setAdapter(mAdapterForGalery);

    getTemplateFromResource();
    galleryforsuprvisore.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // logDebug("onItemSelected  ");
            // try
            // {

            System.out.println("Item Selected Position=======>>>" + pos);
            System.out.println("Item Selected Position=======>>>  count" + count);
            for (int i = 0; i < count; i++) {
                page_text[i].setTextColor(android.graphics.Color.GRAY);
            }
            page_text[pos].setTextColor(android.graphics.Color.BLUE);
            // } catch (Exception e)
            // //{
            // logError("onItemSelected  Exception "+e);
            // }

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });

    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    // logDebug("onCreate session "+session);
    if (session == null) {
        // logDebug("onCreate savedInstanceState "+savedInstanceState);
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            // logDebug("onCreate savedInstanceState restore session   "+session);
        }
        if (session == null) {
            session = new Session(this);
            // logDebug("onCreate savedInstanceState create session   "+session);
        }
        Session.setActiveSession(session);
        logDebug("onCreate savedInstanceState state session    " + session.getState());
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
            // session.openForRead(new
            // Session.OpenRequest(this).setPermissions(Arrays.asList("user_birthday",
            // "email","user_relationships","user_photos")).setCallback(statusCallback));
        }
    }
    animeBottomTOUp = AnimationUtils.loadAnimation(this, R.anim.helpscreen_in_to_out);
    gellarybottom = AnimationUtils.loadAnimation(this, R.anim.helpscreen_in_to_out);
    gellarybottom.setFillAfter(true);

    gellarybottom.setAnimationListener(new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
        }
    });

    updateView();

    cd = new ConnectionDetector(getApplicationContext());
    if (cd.isConnectingToInternet()) {
        if (checkPlayServices()) {
            regid = getRegistrationId(this);
            if (regid.isEmpty()) {
                registerInBackground();
            } else {
                logDebug("reg id saved : " + regid);
            }
        } else {
            return;
        }

        // LocationManager locationManager = (LocationManager)
        // getSystemService(LOCATION_SERVICE);
        // if
        // (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
        // {
        // newLocationFinder = new LocationFinder();
        // newLocationFinder.getLocation(LoginUsingFacebook.this,
        // mLocationResult);
        // } else {
        // showGPSDisabledAlertToUser();
        //
        // }
    } else {
        AlertDialogManager.internetConnetionErrorAlertDialog(LoginUsingFacebook.this);
    }
}

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

/**
* Returns a list with the current signatures of the 
* application.//from   w w w  .  java2  s  .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;
}