private void loadData(Bundle savedInstanceState, Uri appUri) {
    mAppSettings = new ApiDataAccessObject(this).getApiAppSettings(appUri);

    // get application name and icon from package manager
    String appName;
    Drawable appIcon = null;
    PackageManager pm = getApplicationContext().getPackageManager();
    try {
      ApplicationInfo ai = pm.getApplicationInfo(mAppSettings.getPackageName(), 0);

      appName = (String) pm.getApplicationLabel(ai);
      appIcon = pm.getApplicationIcon(ai);
    } catch (PackageManager.NameNotFoundException e) {
      // fallback
      appName = mAppSettings.getPackageName();
    }
    mAppNameView.setText(appName);
    mAppIconView.setImageDrawable(appIcon);

    Uri accountsUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ACCOUNTS).build();
    Log.d(Constants.TAG, "accountsUri: " + accountsUri);
    Uri allowedKeysUri = appUri.buildUpon().appendPath(KeychainContract.PATH_ALLOWED_KEYS).build();
    Log.d(Constants.TAG, "allowedKeysUri: " + allowedKeysUri);
    startListFragments(savedInstanceState, accountsUri, allowedKeysUri);
  }
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // set displayed values
    if (getArguments() != null) {
      if (getArguments().containsKey(ARG_QUERY)) {
        String query = getArguments().getString(ARG_QUERY);
        mQueryEditText.setText(query, TextView.BufferType.EDITABLE);

        Log.d(Constants.TAG, "query: " + query);
      }

      if (getArguments().containsKey(ARG_KEYSERVER)) {
        String keyserver = getArguments().getString(ARG_KEYSERVER);
        int keyserverPos = mServerAdapter.getPosition(keyserver);
        mServerSpinner.setSelection(keyserverPos);

        Log.d(Constants.TAG, "keyserver: " + keyserver);
      }

      if (getArguments().getBoolean(ARG_DISABLE_QUERY_EDIT, false)) {
        mQueryEditText.setEnabled(false);
      }
    }
  }
  public boolean moveCursor(int position) {
    if (position >= getItemCount() || position < -1) {
      Log.w(TAG, "Position: %d is invalid for this data set!");
      return false;
    }

    if (!mDataValid) {
      Log.d(TAG, "Attempt to move cursor over invalid data set!");
    }

    return mCursor.moveToPosition(position);
  }
  /**
   * Send message back to handler which is initialized in a activity
   *
   * @param what Message integer you want to send
   */
  private void sendMessageToHandler(Integer what) {
    Message msg = Message.obtain();
    msg.what = what;

    try {
      mMessenger.send(msg);
    } catch (RemoteException e) {
      Log.w(Constants.TAG, "Exception sending message, Is handler present?", e);
    } catch (NullPointerException e) {
      Log.w(Constants.TAG, "Messenger is null!", e);
    }
  }
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mPubMasterKeyIds =
        getActivity().getIntent().getLongArrayExtra(CertifyKeyActivity.EXTRA_KEY_IDS);
    if (mPubMasterKeyIds == null) {
      Log.e(Constants.TAG, "List of key ids to certify missing!");
      getActivity().finish();
      return;
    }

    ArrayList<Boolean> checkedStates;
    if (savedInstanceState != null) {
      checkedStates = (ArrayList<Boolean>) savedInstanceState.getSerializable(ARG_CHECK_STATES);
      // key spinner and the checkbox keep their own state
    } else {
      checkedStates = null;

      // preselect certify key id if given
      long certifyKeyId =
          getActivity()
              .getIntent()
              .getLongExtra(CertifyKeyActivity.EXTRA_CERTIFY_KEY_ID, Constants.key.none);
      if (certifyKeyId != Constants.key.none) {
        try {
          CachedPublicKeyRing key =
              (new ProviderHelper(getActivity())).getCachedPublicKeyRing(certifyKeyId);
          if (key.canCertify()) {
            mCertifyKeySpinner.setPreSelectedKeyId(certifyKeyId);
          }
        } catch (PgpKeyNotFoundException e) {
          Log.e(Constants.TAG, "certify certify check failed", e);
        }
      }
    }

    mUserIdsAdapter = new MultiUserIdsAdapter(getActivity(), null, 0, checkedStates);
    mUserIds.setAdapter(mUserIdsAdapter);
    mUserIds.setDividerHeight(0);

    getLoaderManager().initLoader(0, null, this);

    OperationResult result =
        getActivity().getIntent().getParcelableExtra(CertifyKeyActivity.EXTRA_RESULT);
    if (result != null) {
      // display result from import
      result.createNotify(getActivity()).show();
    }
  }
 public static PGPPublicKey getEncryptPublicKey(Context context, long masterKeyId) {
   PGPPublicKeyRing keyRing =
       ProviderHelper.getPGPPublicKeyRingByMasterKeyId(context, masterKeyId);
   if (keyRing == null) {
     Log.e(Constants.TAG, "keyRing is null!");
     return null;
   }
   Vector<PGPPublicKey> encryptKeys = getUsableEncryptKeys(keyRing);
   if (encryptKeys.size() == 0) {
     Log.e(Constants.TAG, "encryptKeys is null!");
     return null;
   }
   return encryptKeys.get(0);
 }
  public static WrappedSignature fromBytes(byte[] data) {
    PGPObjectFactory factory = new PGPObjectFactory(data);
    PGPSignatureList signatures = null;
    try {
      if ((signatures = (PGPSignatureList) factory.nextObject()) == null || signatures.isEmpty()) {
        Log.e(Constants.TAG, "No signatures given!");
        return null;
      }
    } catch (IOException e) {
      Log.e(Constants.TAG, "Error while converting to PGPSignature!", e);
      return null;
    }

    return new WrappedSignature(signatures.get(0));
  }
 static {
   try {
     NEW_LINE = "\r\n".getBytes("UTF-8");
   } catch (UnsupportedEncodingException e) {
     Log.e(Constants.TAG, "UnsupportedEncodingException", e);
   }
 }
  @Override
  public ArrayList<ImportKeysListEntry> search(String query)
      throws QueryFailedException, QueryNeedsRepairException {
    ArrayList<ImportKeysListEntry> results = new ArrayList<>();

    if (query.startsWith("0x")) {
      // cut off "0x" if a user is searching for a key id
      query = query.substring(2);
    }
    if (query.isEmpty()) {
      throw new QueryTooShortException();
    }

    try {
      KeybaseQuery keybaseQuery = new KeybaseQuery(new OkHttpKeybaseClient());
      keybaseQuery.setProxy(mProxy);
      Iterable<Match> matches = keybaseQuery.search(query);
      for (Match match : matches) {
        results.add(makeEntry(match, query));
      }
    } catch (KeybaseException e) {
      Log.e(Constants.TAG, "keybase result parsing error", e);
      throw new QueryFailedException(
          "Unexpected structure in keybase search result: " + e.getMessage());
    }

    return results;
  }
  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(Constants.TAG, "PassphraseCacheService, onDestroy()");

    unregisterReceiver(mIntentReceiver);
  }
  private void showPassphraseDialog(final long secretKeyId) {
    // Message is received after passphrase is cached
    Handler returnHandler =
        new Handler() {
          @Override
          public void handleMessage(Message message) {
            if (message.what == PassphraseDialogFragment.MESSAGE_OKAY) {
              startSigning();
            }
          }
        };

    // Create a new Messenger for the communication back
    Messenger messenger = new Messenger(returnHandler);

    try {
      PassphraseDialogFragment passphraseDialog =
          PassphraseDialogFragment.newInstance(this, messenger, secretKeyId);

      passphraseDialog.show(getSupportFragmentManager(), "passphraseDialog");
    } catch (PgpGeneralException e) {
      Log.d(Constants.TAG, "No passphrase for this secret key!");
      // send message to handler to start certification directly
      returnHandler.sendEmptyMessage(PassphraseDialogFragment.MESSAGE_OKAY);
    }
  }
 private void encrypt(Uri dataUri, boolean text) {
   // If there is no encryption key, don't bother.
   if (!mHasEncrypt) {
     Notify.showNotify(getActivity(), R.string.error_no_encrypt_subkey, Notify.Style.ERROR);
     return;
   }
   try {
     long keyId =
         new ProviderHelper(getActivity())
             .getCachedPublicKeyRing(dataUri)
             .extractOrGetMasterKeyId();
     long[] encryptionKeyIds = new long[] {keyId};
     Intent intent;
     if (text) {
       intent = new Intent(getActivity(), EncryptTextActivity.class);
       intent.setAction(EncryptTextActivity.ACTION_ENCRYPT_TEXT);
       intent.putExtra(EncryptTextActivity.EXTRA_ENCRYPTION_KEY_IDS, encryptionKeyIds);
     } else {
       intent = new Intent(getActivity(), EncryptFileActivity.class);
       intent.setAction(EncryptFileActivity.ACTION_ENCRYPT_DATA);
       intent.putExtra(EncryptFileActivity.EXTRA_ENCRYPTION_KEY_IDS, encryptionKeyIds);
     }
     // used instead of startActivity set actionbar based on callingPackage
     startActivityForResult(intent, 0);
   } catch (PgpGeneralException e) {
     Log.e(Constants.TAG, "key not found!", e);
   }
 }
  /**
   * Reads all PGPKeyRing objects from input
   *
   * @param inputData
   * @return
   */
  private void generateListOfKeyrings(InputData inputData) {
    PositionAwareInputStream progressIn = new PositionAwareInputStream(inputData.getInputStream());

    // need to have access to the bufferedInput, so we can reuse it for the possible
    // PGPObject chunks after the first one, e.g. files with several consecutive ASCII
    // armor blocks
    BufferedInputStream bufferedInput = new BufferedInputStream(progressIn);
    try {
      // parse all keyrings
      Iterator<UncachedKeyRing> it = UncachedKeyRing.fromStream(bufferedInput);
      while (it.hasNext()) {
        UncachedKeyRing ring = it.next();
        ImportKeysListEntry item = new ImportKeysListEntry(getContext(), ring);
        mData.add(item);
        mParcelableRings.put(item.hashCode(), new ParcelableKeyRing(ring.getEncoded()));
      }
    } catch (IOException e) {
      Log.e(Constants.TAG, "IOException on parsing key file! Return NoValidKeysException!", e);
      OperationResult.OperationLog log = new OperationResult.OperationLog();
      log.add(OperationResult.LogType.MSG_GET_NO_VALID_KEYS, 0);
      GetKeyResult getKeyResult = new GetKeyResult(GetKeyResult.RESULT_ERROR_NO_VALID_KEYS, log);
      mEntryListWrapper =
          new AsyncTaskResultWrapper<ArrayList<ImportKeysListEntry>>(mData, getKeyResult);
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.view_cert_activity);

    mSigneeKey = (TextView) findViewById(R.id.signee_key);
    mSigneeUid = (TextView) findViewById(R.id.signee_uid);
    mAlgorithm = (TextView) findViewById(R.id.algorithm);
    mType = (TextView) findViewById(R.id.signature_type);
    mReason = (TextView) findViewById(R.id.reason);
    mCreation = (TextView) findViewById(R.id.creation);

    mCertifierKey = (TextView) findViewById(R.id.signer_key_id);
    mCertifierUid = (TextView) findViewById(R.id.signer_uid);

    mRowReason = findViewById(R.id.row_reason);

    mViewCertifierButton = findViewById(R.id.view_cert_view_cert_key);

    mDataUri = getIntent().getData();
    if (mDataUri == null) {
      Log.e(Constants.TAG, "Intent data missing. Should be Uri of key!");
      finish();
      return;
    }

    getSupportLoaderManager().initLoader(0, null, this);
  }
  public void drawPublicKey() {
    PGPPublicKeyRing pubring = ProviderHelper.getPGPPublicKeyRingByMasterKeyId(this, mPubKeyId);

    if (pubring != null) {
      PGPPublicKey key = PgpKeyHelper.getMasterKey(pubring);
      String masterKeyIdHex = PgpKeyHelper.convertKeyIdToHex(mPubKeyId);

      // get relevant UI elements
      TextView keyIdHex = (TextView) findViewById(R.id.public_key_master_key_hex);
      TextView keyUserId = (TextView) findViewById(R.id.public_key_user_id);
      TextView keyUserIdRest = (TextView) findViewById(R.id.public_key_user_id_rest);

      if (key != null) {
        String userId = PgpKeyHelper.getMainUserIdSafe(this, key);

        String[] userIdSplit = PgpKeyHelper.splitUserId(userId);
        String userName, userEmail;

        if (userIdSplit[0] != null) {
          userName = userIdSplit[0];
        } else {
          userName = getResources().getString(R.string.user_id_no_name);
        }

        if (userIdSplit[1] != null) {
          userEmail = userIdSplit[1];
        } else {
          userEmail = getResources().getString(R.string.error_user_id_no_email);
        }

        keyIdHex.setText(masterKeyIdHex);

        keyUserId.setText(userName);
        keyUserIdRest.setText(userEmail);
        keyUserId.setVisibility(View.VISIBLE);
        keyUserIdRest.setVisibility(View.VISIBLE);
      } else {
        Log.e(Constants.TAG, "this shouldn't happen. key == 0!");
        finish();
        return;
      }
    } else {
      Log.e(Constants.TAG, "this shouldn't happen. pubring == 0!");
      finish();
      return;
    }
  }
  @Override
  public void onCreate() {
    super.onCreate();
    mContext = this;
    Log.d(Constants.TAG, "PassphraseCacheService, onCreate()");

    registerReceiver();
  }
  public static void clearCachedPassphrases(Context context) {
    Log.d(Constants.TAG, "PassphraseCacheService.clearCachedPassphrase()");

    Intent intent = new Intent(context, PassphraseCacheService.class);
    intent.setAction(ACTION_PASSPHRASE_CACHE_CLEAR);

    context.startService(intent);
  }
  /**
   * If an Intent gives a signatureMasterKeyId and/or encryptionMasterKeyIds, preselect those!
   *
   * @param preselectedSignatureKeyId
   * @param preselectedEncryptionKeyIds
   */
  private void preselectKeys(
      long preselectedSignatureKeyId,
      long[] preselectedEncryptionKeyIds,
      ProviderHelper providerHelper) {
    if (preselectedSignatureKeyId != 0) {
      // TODO: don't use bouncy castle objects!
      try {
        PGPSecretKeyRing keyRing =
            providerHelper.getPGPSecretKeyRingWithKeyId(preselectedSignatureKeyId);

        PGPSecretKey masterKey = keyRing.getSecretKey();
        if (masterKey != null) {
          PGPSecretKey signKey = PgpKeyHelper.getFirstSigningSubkey(keyRing);
          if (signKey != null) {
            setSignatureKeyId(masterKey.getKeyID());
          }
        }
      } catch (ProviderHelper.NotFoundException e) {
        Log.e(Constants.TAG, "key not found!", e);
      }
    }

    if (preselectedEncryptionKeyIds != null) {
      Vector<Long> goodIds = new Vector<Long>();
      for (int i = 0; i < preselectedEncryptionKeyIds.length; ++i) {
        // TODO One query per selected key?! wtf
        try {
          long id =
              providerHelper.getMasterKeyId(
                  KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(
                      Long.toString(preselectedEncryptionKeyIds[i])));
          goodIds.add(id);
        } catch (ProviderHelper.NotFoundException e) {
          Log.e(Constants.TAG, "key not found!", e);
        }
      }
      if (goodIds.size() > 0) {
        long[] keyIds = new long[goodIds.size()];
        for (int i = 0; i < goodIds.size(); ++i) {
          keyIds[i] = goodIds.get(i);
        }
        setEncryptionKeyIds(keyIds);
      }
    }
  }
  private static CryptoInputParcel getCryptoInputParcel(Context context, UUID uuid)
      throws InputParcelNotFound {
    Intent intent = new Intent(context, CryptoInputParcelCacheService.class);
    intent.setAction(ACTION_GET);

    final Object mutex = new Object();
    final Message returnMessage = Message.obtain();

    HandlerThread handlerThread = new HandlerThread("getParcelableThread");
    handlerThread.start();
    Handler returnHandler =
        new Handler(handlerThread.getLooper()) {
          @Override
          public void handleMessage(Message message) {
            // copy over result to handle after mutex.wait
            returnMessage.what = message.what;
            returnMessage.copyFrom(message);
            synchronized (mutex) {
              mutex.notify();
            }
            // quit handlerThread
            getLooper().quit();
          }
        };

    // Create a new Messenger for the communication back
    Messenger messenger = new Messenger(returnHandler);
    intent.putExtra(EXTRA_UUID1, uuid.getMostSignificantBits());
    intent.putExtra(EXTRA_UUID2, uuid.getLeastSignificantBits());
    intent.putExtra(EXTRA_MESSENGER, messenger);
    // send intent to this service
    context.startService(intent);

    // Wait on mutex until parcelable is returned to handlerThread. Note that this local
    // variable is used in the handler closure above, so it does make sense here!
    // noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (mutex) {
      try {
        mutex.wait(3000);
      } catch (InterruptedException e) {
        // don't care
      }
    }

    switch (returnMessage.what) {
      case MSG_GET_OKAY:
        Bundle returnData = returnMessage.getData();
        returnData.setClassLoader(context.getClassLoader());
        return returnData.getParcelable(EXTRA_CRYPTO_INPUT_PARCEL);
      case MSG_GET_NOT_FOUND:
        throw new InputParcelNotFound();
      default:
        Log.e(Constants.TAG, "timeout!");
        throw new InputParcelNotFound("should not happen!");
    }
  }
 private void updateService() {
   if (mPassphraseCache.size() > 0) {
     startForeground(Constants.Notification.PASSPHRASE_CACHE, getNotification());
   } else {
     // stop whole service if no cached passphrases remaining
     Log.d(
         Constants.TAG,
         "PassphraseCacheService: No passphrases remaining in memory, stopping service!");
     stopForeground(true);
   }
 }
 @Override
 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   Log.d(Constants.TAG, "clicked id: " + id);
   long masterKeyId = getMasterKeyId(position);
   if (mSelectedItems.contains(masterKeyId)) {
     mSelectedItems.remove(masterKeyId);
   } else {
     mSelectedItems.add(masterKeyId);
   }
   notifyDataSetChanged();
 }
  public static void clearCachedPassphrase(Context context, long masterKeyId, long subKeyId) {
    Log.d(Constants.TAG, "PassphraseCacheService.clearCachedPassphrase() for " + masterKeyId);

    Intent intent = new Intent(context, PassphraseCacheService.class);
    intent.setAction(ACTION_PASSPHRASE_CACHE_CLEAR);

    intent.putExtra(EXTRA_KEY_ID, masterKeyId);
    intent.putExtra(EXTRA_SUBKEY_ID, subKeyId);

    context.startService(intent);
  }
    public static <T extends AbstractCursor> T wrap(Cursor cursor, Class<T> type) {
      if (cursor != null) {
        try {
          Constructor<T> constructor = type.getConstructor(Cursor.class);
          return constructor.newInstance(cursor);
        } catch (Exception e) {
          Log.e(Constants.TAG, "Could not create instance of cursor wrapper!", e);
        }
      }

      return null;
    }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAccountsLabel = (TextView) findViewById(R.id.api_accounts_label);
    mAppNameView = (TextView) findViewById(R.id.api_app_settings_app_name);
    mAppIconView = (ImageView) findViewById(R.id.api_app_settings_app_icon);
    mPackageName = (TextView) findViewById(R.id.api_app_settings_package_name);
    mPackageSignature = (TextView) findViewById(R.id.api_app_settings_package_certificate);
    mStartFab = (FloatingActionButton) findViewById(R.id.fab);

    mStartFab.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            startApp();
          }
        });

    setFullScreenDialogClose(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            cancel();
          }
        });
    setTitle(null);

    Intent intent = getIntent();
    mAppUri = intent.getData();
    if (mAppUri == null) {
      Log.e(Constants.TAG, "Intent data missing. Should be Uri of app!");
      finish();
      return;
    } else {
      Log.d(Constants.TAG, "uri: " + mAppUri);
      loadData(savedInstanceState, mAppUri);
    }
  }
  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    Uri dataUri = getArguments().getParcelable(ARG_DATA_URI);
    if (dataUri == null) {
      Log.e(Constants.TAG, "Data missing. Should be Uri of key!");
      getActivity().finish();
      return;
    }

    loadData(dataUri);
  }
 private void startApp() {
   Intent i;
   PackageManager manager = getPackageManager();
   try {
     i = manager.getLaunchIntentForPackage(mAppSettings.getPackageName());
     if (i == null) throw new PackageManager.NameNotFoundException();
     // start like the Android launcher would do
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
     i.addCategory(Intent.CATEGORY_LAUNCHER);
     startActivity(i);
   } catch (PackageManager.NameNotFoundException e) {
     Log.e(Constants.TAG, "startApp", e);
   }
 }
  public void deleteKey(Uri dataUri, Handler deleteHandler) {
    try {
      long masterKeyId =
          new ProviderHelper(mActivity).getCachedPublicKeyRing(dataUri).extractOrGetMasterKeyId();

      // Create a new Messenger for the communication back
      Messenger messenger = new Messenger(deleteHandler);
      DeleteKeyDialogFragment deleteKeyDialog =
          DeleteKeyDialogFragment.newInstance(messenger, new long[] {masterKeyId});
      deleteKeyDialog.show(mActivity.getSupportFragmentManager(), "deleteKeyDialog");
    } catch (PgpGeneralException e) {
      Log.e(Constants.TAG, "key not found!", e);
    }
  }
  private void loadData(Uri dataUri) {
    mDataUri = dataUri;

    Log.i(Constants.TAG, "mDataUri: " + mDataUri.toString());

    mActionEncryptFiles.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            encrypt(mDataUri, false);
          }
        });
    mActionEncryptText.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            encrypt(mDataUri, true);
          }
        });
    mActionCertify.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View view) {
            certify(mDataUri);
          }
        });
    mActionEdit.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View view) {
            editKey(mDataUri);
          }
        });
    mActionUpdate.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View view) {
            try {
              updateFromKeyserver(mDataUri, new ProviderHelper(getActivity()));
            } catch (NotFoundException e) {
              Notify.showNotify(getActivity(), R.string.error_key_not_found, Notify.Style.ERROR);
            }
          }
        });

    mUserIdsAdapter = new UserIdsAdapter(getActivity(), null, 0);
    mUserIds.setAdapter(mUserIdsAdapter);

    // Prepare the loaders. Either re-connect with an existing ones,
    // or start new ones.
    getLoaderManager().initLoader(LOADER_ID_UNIFIED, null, this);
    getLoaderManager().initLoader(LOADER_ID_USER_IDS, null, this);
  }
 private void startSafeSlinger(Uri dataUri) {
   long keyId = 0;
   try {
     keyId =
         new ProviderHelper(getActivity())
             .getCachedPublicKeyRing(dataUri)
             .extractOrGetMasterKeyId();
   } catch (PgpKeyNotFoundException e) {
     Log.e(Constants.TAG, "key not found!", e);
   }
   Intent safeSlingerIntent = new Intent(getActivity(), SafeSlingerActivity.class);
   safeSlingerIntent.putExtra(SafeSlingerActivity.EXTRA_MASTER_KEY_ID, keyId);
   startActivityForResult(safeSlingerIntent, 0);
 }
  public static String getFingerPrint(Context context, long keyId) {
    PGPPublicKey key = ProviderHelper.getPGPPublicKeyByKeyId(context, keyId);
    // if it is no public key get it from your own keys...
    if (key == null) {
      PGPSecretKey secretKey = ProviderHelper.getPGPSecretKeyByKeyId(context, keyId);
      if (secretKey == null) {
        Log.e(Constants.TAG, "Key could not be found!");
        return null;
      }
      key = secretKey.getPublicKey();
    }

    return convertFingerprintToHex(key.getFingerprint(), true);
  }