Example usage for android.util Base64 decode

List of usage examples for android.util Base64 decode

Introduction

In this page you can find the example usage for android.util Base64 decode.

Prototype

public static byte[] decode(byte[] input, int flags) 

Source Link

Document

Decode the Base64-encoded data in input and return the data in a new byte array.

Usage

From source file:at.diamonddogs.util.Utils.java

/**
 * Base64 byte array to string/*from   www . ja  v  a2 s .com*/
 *
 * @param encMsg the message to be converted from base64
 * @return the string
 */
public static String decrypt(byte[] encMsg) {
    return new String(Base64.decode(encMsg, Base64.DEFAULT));
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static List<ECKey> restoreWalletFromBackupFile(String fileName, String passOrNFC, Wallet wallet,
        boolean shouldAddKeys) {
    final List<ECKey> keys = new LinkedList<ECKey>();
    boolean nfcEncrypted;

    try {//from  w w  w .  j  ava2s .c o m

        if (Constants.WALLET_BACKUP_DIRECTORY.exists() && Constants.WALLET_BACKUP_DIRECTORY.isDirectory()) {

            File file = new File(Constants.WALLET_BACKUP_DIRECTORY, fileName);

            FileInputStream fileInputStream = new FileInputStream(file);
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(fileInputStream, Constants.UTF_8));

            String x1 = null;
            String x2Encrypted = null;
            String x2Decrypted = null;
            String secretString = null;

            while (true) {
                final String line = in.readLine();
                if (line == null)
                    break; // eof

                if (line.startsWith("# "))
                    continue;

                if (line.trim().isEmpty())
                    continue;

                if (line.startsWith("#1:")) {
                    String[] splitStr = line.split(":");
                    x1 = splitStr[1];
                    continue;
                }

                if (line.startsWith("#X2:")) {

                    String[] splitStr = line.split(":");
                    String x2Base64 = splitStr[1];

                    x2Encrypted = new String(Base64.decode(x2Base64.getBytes(), Base64.NO_WRAP));
                    x2Decrypted = WalletUtils.decryptString(x2Encrypted, passOrNFC);
                    x2Decrypted = x2Decrypted.split(":")[1];
                    BigInteger secret = WalletUtils.generateSecretFromStrings("1:" + x1, "2:" + x2Decrypted,
                            null);
                    secretString = WalletUtils.convertToSha256(secret.toString());

                    continue;
                }

                if (line.startsWith("#ENCTYPE:NFC")) {
                    x2Decrypted = passOrNFC;
                    BigInteger secret = WalletUtils.generateSecretFromStrings("1:" + x1, x2Decrypted, null);
                    secretString = WalletUtils.convertToSha256(secret.toString());
                    continue;
                }

                if (line.startsWith("#ENCTYPE:PASSWORD"))
                    continue;

                String encryptedKey = new String(Base64.decode(line.getBytes(), Base64.NO_WRAP));
                String plainKey = WalletUtils.decryptString(encryptedKey, secretString);
                ECKey key = new DumpedPrivateKey(Constants.NETWORK_PARAMETERS, plainKey).getKey();

                if (!wallet.hasKey(key))
                    keys.add(key);
            }

            //Only add keys if the parameter says so. This is because the wallet may be still encrypted.
            //We dont want to add keys to an encrypted wallet. That's bad.
            if (shouldAddKeys)
                wallet.addKeys(keys);

        }

    } catch (final AddressFormatException x) {
        Log.e(TAG, "exception caught: " + x.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "exception caught: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "exception caught: " + e.getMessage());
    }

    return keys;

}

From source file:mobisocial.musubi.objects.IntroductionObj.java

@Override
public boolean processObject(Context context, MFeed feed, MIdentity sender, MObject object) {
    boolean anyChanged = false;
    SQLiteOpenHelper databaseSource = App.getDatabaseSource(context);
    IdentitiesManager identitiesManager = new IdentitiesManager(databaseSource);

    if (object.json_ == null) {
        Log.w(TAG, "bad introduction format");
        return false;
    }// w  w w .j  a  v a  2  s. co m
    JSONObject json;
    try {
        json = new JSONObject(object.json_);
    } catch (JSONException e) {
        Log.e(TAG, "Bad json in database", e);
        return false;
    }
    JSONArray array;
    try {
        array = json.getJSONArray(IDENTITIES);
    } catch (JSONException e) {
        Log.e(TAG, "json identity array missing", e);
        return false;
    }
    // TODO: use getIdentitiesForObj
    for (int i = 0; i < array.length(); ++i) {
        JSONObject identity;
        try {
            identity = array.getJSONObject(i);
        } catch (JSONException e) {
            Log.e(TAG, "identity entry in introduction access error", e);
            continue;
        }
        int authority = -1;
        String principalHashString = null;
        try {
            authority = identity.getInt(ID_AUTHORITY);
            principalHashString = identity.getString(ID_PRINCIPAL_HASH);
        } catch (JSONException e) {
            Log.e(TAG, "identity entry in introduction missing key fields", e);
            continue;
        }
        String principal = null;
        try {
            principal = identity.getString(ID_PRINCIPAL);
        } catch (JSONException e) {
        }
        String name = null;
        try {
            name = identity.getString(ID_NAME);
        } catch (JSONException e) {
        }
        if (name == null && principal == null) {
            //not much of an introduction
            continue;
        }

        byte[] principalHash = Base64.decode(principalHashString, Base64.DEFAULT);
        IBHashedIdentity hid = new IBHashedIdentity(Authority.values()[authority], principalHash, 0);
        MIdentity ident = identitiesManager.getIdentityForIBHashedIdentity(hid);
        if (ident == null) {
            //this introduction has to be sent to both participants, so the low leve
            //will already have added the identity
            Log.e(TAG, "identity introduction for totally unseen identities");
            continue;
        }
        if (ident.owned_) {
            //we won't have a received profile version, so owned keeps us from self updating
            continue;
        }
        //TODO: rely on  deferred handling for gray list participants
        //TODO: check that the person is actually in the feed
        boolean changed = false;
        if (principal != null && ident.principal_ == null) {
            if (!Arrays.equals(Util.sha256(principal.getBytes()), principalHash)) {
                Log.e(TAG, "received mismatched principal and principal hash");
                continue;
            }
            changed = true;
            ident.principal_ = principal;
        }
        if (name != null && ident.receivedProfileVersion_ == 0) {
            changed = true;
            //each time someone introduces us, we'll just accept the new name
            //as long as we never got a real profile.
            ident.musubiName_ = name;
        }
        if (changed) {
            identitiesManager.updateIdentity(ident);
            anyChanged = true;
        }
    }
    if (anyChanged) {
        context.getContentResolver().notifyChange(MusubiService.PRIMARY_CONTENT_CHANGED, null);
    }
    return true;
}

From source file:com.github.pockethub.android.ui.commit.CommitFileViewActivity.java

private void loadMarkdown() {
    loadingBar.setVisibility(View.VISIBLE);
    codeView.setVisibility(View.GONE);

    String markdown = new String(Base64.decode(blob.content(), Base64.DEFAULT));
    Bundle args = new Bundle();
    args.putCharSequence(ARG_TEXT, markdown);
    args.putParcelable(ARG_REPO, repo);//from ww  w. j a v  a 2 s . co m
    getSupportLoaderManager().restartLoader(0, args, this);
}

From source file:org.gluu.com.ox_push2.u2f.v2.SoftwareDevice.java

public TokenResponse sign(String jsonRequest, String origin, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Starting to process sign request: " + jsonRequest);
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    JSONArray authenticateRequestArray = null;
    if (request.has("authenticateRequests")) {
        authenticateRequestArray = request.getJSONArray("authenticateRequests");
        if (authenticateRequestArray.length() == 0) {
            throw new U2FException("Failed to get authentication request!");
        }//w  w w.j a  va2  s . c  om
    } else {
        authenticateRequestArray = new JSONArray();
        authenticateRequestArray.put(request);
    }

    Log.i(TAG, "Found " + authenticateRequestArray.length() + " authentication requests");

    AuthenticateResponse authenticateResponse = null;
    String authenticatedChallenge = null;
    JSONObject authRequest = null;
    for (int i = 0; i < authenticateRequestArray.length(); i++) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Process authentication request: " + authRequest);
        authRequest = (JSONObject) authenticateRequestArray.get(i);

        if (!authRequest.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
            throw new U2FException("Unsupported U2F_V2 version!");
        }

        String version = authRequest.getString(JSON_PROPERTY_VERSION);
        String appParam = authRequest.getString(JSON_PROPERTY_APP_ID);
        String challenge = authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE);
        byte[] keyHandle = Base64.decode(authRequest.getString(JSON_PROPERTY_KEY_HANDLE),
                Base64.URL_SAFE | Base64.NO_WRAP);

        authenticateResponse = u2fKey.authenticate(new AuthenticateRequest(version,
                AuthenticateRequest.USER_PRESENCE_SIGN, challenge, appParam, keyHandle));
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Authentication response: " + authenticateResponse);
        if (authenticateResponse != null) {
            authenticatedChallenge = challenge;
            break;
        }
    }

    if (authenticateResponse == null) {
        return null;
    }

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, AUTHENTICATE_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_AUTHENTICATE);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE));
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String keyHandle = authRequest.getString(JSON_PROPERTY_KEY_HANDLE);
    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeAuthenticateResponse(authenticateResponse);

    JSONObject response = new JSONObject();
    response.put("signatureData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("keyHandle", keyHandle);

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(authenticatedChallenge);
    tokenResponse.setKeyHandle(keyHandle);

    return tokenResponse;
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private boolean checkSignature(String jsonContent, String sign) {
    Log.d(TAG, "JSON: " + jsonContent);

    if (sign == null)
        return false;
    final String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+6EG/fAE+zIdh5Wzqnf"
            + "Fo4nCf7t7eJcKyvk1lqX1MdkIi/fUs8HQ4aQ4jWLCO4M1Gkz1FQiXOnheGLV5MXY"
            + "c9GyaglsofvpA/pU5d16FybX2pCevbTzcm39eU+XlwQWOr8gh23tYD8G6uMX6sIJ"
            + "W+1k1FWdud9errMVm0YUScI+J4AV5xzN0IQ29h9IeNp6oFqZ2ByWog6OBMTUDFIW"
            + "q8oRvH0OuPv3zFR5rKwsbTYb5Da8lhUht04dLBA860Y4zeUu98huvS9jQPu2N4ns"
            + "Hf425FfDJ/wae+7eLdQo7uFb+Wvc+PO9U39e6vXQfa8ZkUoXHD0XZN4jsFcKYuJw" + "OwIDAQAB";
    try {//w  w  w. j a  v  a 2  s  .  c om
        byte keyBytes[] = Base64.decode(publicKeyStr.getBytes(), Base64.NO_WRAP);

        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey publicKey = kf.generatePublic(publicSpec);

        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(publicKey);
        signer.update(jsonContent.getBytes(), 0, jsonContent.length());

        return signer.verify(Base64.decode(sign, Base64.NO_WRAP));
    } catch (Exception e) {
    }
    return false;
}

From source file:com.rnd.snapsplit.view.SentRequestFragment.java

@Nullable
@Override/*from   www. j  a va  2s.  c  om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.activity_sent_request, container, false);
    activity = getActivity();
    profile = new Profile(getContext());
    ((Toolbar) getActivity().findViewById(R.id.tool_bar_hamburger)).setVisibility(View.VISIBLE);

    mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(getContext());
    //mLinearLayoutManager.setStackFromEnd(true);
    //Raymonds phone number here
    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("requests");
    mFirebaseAdapter = new FirebaseRecyclerAdapter<PaymentRequest, MessageViewHolder>(PaymentRequest.class,
            R.layout.list_sent_requests, MessageViewHolder.class,
            mFirebaseDatabaseReference.orderByChild("requestEpochDate")) {

        @Override
        protected PaymentRequest parseSnapshot(DataSnapshot snapshot) {
            PaymentRequest pr = super.parseSnapshot(snapshot);
            if (pr != null) {
                pr.setId(snapshot.getKey());
                return pr;
            }
            return null;
        }

        @Override
        protected void populateViewHolder(final MessageViewHolder viewHolder, PaymentRequest pr, int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            if (pr != null && pr.getRequestorPhoneNumber().equals(profile.getPhoneNumber())) {

                if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                    String encodedReceipt = pr.getStrReceiptPic();
                    byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    viewHolder.receiptIcon.setImageBitmap(bitmap);
                }
                viewHolder.pr = pr;
                viewHolder.id = pr.getId();
                viewHolder.description.setText(pr.getDescription());
                viewHolder.toPerson.setText("Request sent to: "
                        + Friend.getFriendByPhoneNumber(getContext(), pr.getReceipientPhoneNo()).getName());
                viewHolder.splitAmount.setText("HKD" + String.format("%.2f", pr.getShareAmount()));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
                String date = null;
                Date temp = new Date(Long.parseLong(pr.getRequestEpochDate()) * (-1));
                date = simpleDateFormat.format(temp);
                viewHolder.date.setText(date);
            } else {
                ViewGroup.LayoutParams params = viewHolder.item.getLayoutParams();
                params.height = 0;
                viewHolder.item.setLayoutParams(params);
            }

            // log a view action on it
            //FirebaseUserActions.getInstance().end(getMessageViewAction(fd));
        }

        @Override
        public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MessageViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
            viewHolder.setOnLongClickListener(new MessageViewHolder.LongClickListener() {
                @Override
                public void onLongClick(View view, int position, String id, PaymentRequest pr) {
                    AlertDialog.Builder ImageDialog = new AlertDialog.Builder(getActivity());
                    ImageDialog.setTitle("Receipt Preview - " + pr.getDescription());
                    ImageView showImage = new ImageView(getActivity());
                    Bitmap bitmap = null;
                    if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                        String encodedReceipt = pr.getStrReceiptPic();
                        byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                        bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    }
                    if (bitmap != null) {
                        showImage.setImageBitmap(bitmap);
                    }
                    ImageDialog.setView(showImage);

                    ImageDialog.setNegativeButton("Close Preview", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });
                    ImageDialog.show();
                }
            });
            viewHolder.setOnClickListener(new MessageViewHolder.ClickListener() {
                @Override
                public void onItemClick(View view, int position, String id, PaymentRequest pr) {
                    //Toast.makeText(getActivity(), "Item clicked at " + position, Toast.LENGTH_SHORT).show();

                }

            });
            return viewHolder;
        }

    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

    return view;

}

From source file:com.primitive.applicationmanager.ApplicationManager.java

/**
 * Package??????/*from  w w  w .j a v a 2 s .  c  o m*/
 * @return Package[]
 * @throws ApplicationManagerException
 */
private Package[] requestPackages() throws ApplicationManagerException {
    Logger.start();
    final ApplicationSummary summary = this.requestApplicationSummary();
    if (this.beforePackages != null) {
        if (summary == null) {
            return null;
        } else {
            if (!this.isUpgrade(summary)) {
                return this.beforePackages;
            }
        }
    }
    final String applicationID = summary.getID();
    final String applicationName = summary.getName();
    final String url = this.config.buildServerURL(ApplicationManager.PackagesURI);

    final Map<String, String> params = new HashMap<String, String>();
    params.put("name", applicationName);
    params.put("application", applicationID);
    params.put("region", Locale.getDefault().getCountry());
    final JSONObject json = super.requestToResponse(url, params);
    try {
        final boolean success = json.getBoolean("sucess");
        if (!success) {
            return this.beforePackages;
        }
        final String secret = summary.getSecret();
        final String hash = json.getString("hash");
        final String result = json.getString("result");
        final String passphrase = HashMacHelper.getHMACBase64(HashMacHelper.Algorithm.HmacSHA256,
                hash.getBytes("UTF-8"), secret.getBytes("UTF-8"));

        byte[] passPhraseBytes = new byte[256 / 8];
        System.arraycopy(passphrase.getBytes(), 0, passPhraseBytes, 0, 256 / 8);

        final byte[] decriptDataByte = CipherHelper.decrypt(CipherHelper.Algorithm.AES, Mode.CBC,
                Padding.PKCS7Padding, Base64.decode(result.getBytes("UTF-8"), Base64.DEFAULT),
                hash.getBytes("UTF-8"), passPhraseBytes);
        final String decriptData = new String(decriptDataByte, "UTF-8");

        final JSONObject decript = new JSONObject(decriptData);
        final JSONArray packagesJSON = decript.getJSONArray("packages");
        final ArrayList<Package> packages = new ArrayList<Package>();
        for (int i = 0; i < packagesJSON.length(); i++) {
            final JSONObject object = packagesJSON.getJSONObject(i);
            final Package packageObject = new Package(object);
            packages.add(packageObject);
            Logger.debug(packageObject);
        }
        this.beforePackages = packages.toArray(new Package[] {});
    } catch (final JSONException ex) {
        Logger.err(ex);
    } catch (final UnsupportedEncodingException ex) {
        Logger.err(ex);
    } catch (CipherException ex) {
        Logger.err(ex);
    }
    return this.beforePackages;
}

From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Get the cipher for the key protecting the saved password for a file
 *///w  w  w.  j  a  v a2 s  . c  o  m
@TargetApi(Build.VERSION_CODES.M)
private Cipher getKeyCipher(Uri fileUri, boolean encrypt) throws CertificateException, NoSuchAlgorithmException,
        KeyStoreException, IOException, UnrecoverableKeyException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    String keyName = getPrefsKey(fileUri);
    KeyStore keystore = getKeystore();
    Key key = keystore.getKey(keyName, null);
    if (key == null) {
        throw new IOException(itsContext.getString(R.string.key_not_found, fileUri));
    }

    Cipher ciph = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
            + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    if (encrypt) {
        ciph.init(Cipher.ENCRYPT_MODE, key);
    } else {
        SharedPreferences prefs = getPrefs();
        String ivStr = prefs.getString(getIvPrefsKey(keyName), null);
        if (TextUtils.isEmpty(ivStr)) {
            throw new IOException("Key IV not found for " + fileUri);
        }
        byte[] iv = Base64.decode(ivStr, Base64.NO_WRAP);
        ciph.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
    }
    return ciph;
}

From source file:com.rnd.snapsplit.view.OwedFragment.java

@Nullable
@Override/*  w  w  w.  j  a  v a 2  s.  c  om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.activity_owed, container, false);
    activity = getActivity();
    profile = new Profile(getContext());
    ((Toolbar) getActivity().findViewById(R.id.tool_bar_hamburger)).setVisibility(View.VISIBLE);

    mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(getContext());
    //mLinearLayoutManager.setStackFromEnd(true);
    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("requests");
    mFirebaseAdapter = new FirebaseRecyclerAdapter<PaymentRequest, MessageViewHolder>(PaymentRequest.class,
            R.layout.list_owed, MessageViewHolder.class,
            mFirebaseDatabaseReference.orderByChild("requestEpochDate")) {

        @Override
        protected PaymentRequest parseSnapshot(DataSnapshot snapshot) {
            PaymentRequest pr = super.parseSnapshot(snapshot);
            if (pr != null) {
                pr.setId(snapshot.getKey());
                return pr;
            }
            return null;
        }

        @Override
        protected void populateViewHolder(final MessageViewHolder viewHolder, PaymentRequest pr, int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            if (pr != null && pr.getReceipientPhoneNo().equals(profile.getPhoneNumber())) {

                if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                    String encodedReceipt = pr.getStrReceiptPic();
                    byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    viewHolder.receiptIcon.setImageBitmap(bitmap);
                }
                viewHolder.pr = pr;
                viewHolder.id = pr.getId();
                viewHolder.description.setText(pr.getDescription());
                viewHolder.from.setText(
                        "Request sent by: " + pr.getRequestorName() + " - " + pr.getRequestorPhoneNumber());
                viewHolder.share.setText("Your Share: HKD" + String.format("%.2f", pr.getShareAmount()));
                viewHolder.splitAmount
                        .setText("Total Amount: HKD" + String.format("%.2f", pr.getTotalAmount()));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
                String date = null;
                Date temp = new Date(Long.parseLong(pr.getRequestEpochDate()) * (-1));
                date = simpleDateFormat.format(temp);
                viewHolder.date.setText(date);
            } else {
                ViewGroup.LayoutParams params = viewHolder.item.getLayoutParams();
                params.height = 0;
                viewHolder.item.setLayoutParams(params);
            }

            // log a view action on it
            //FirebaseUserActions.getInstance().end(getMessageViewAction(fd));
        }

        @Override
        public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MessageViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
            viewHolder.setOnLongClickListener(new MessageViewHolder.LongClickListener() {
                @Override
                public void onLongClick(View view, int position, String id, PaymentRequest pr) {
                    AlertDialog.Builder ImageDialog = new AlertDialog.Builder(getActivity());
                    ImageDialog.setTitle("Receipt Preview - " + pr.getDescription());
                    ImageView showImage = new ImageView(getActivity());
                    Bitmap bitmap = null;
                    if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                        String encodedReceipt = pr.getStrReceiptPic();
                        byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                        bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    }
                    if (bitmap != null) {
                        showImage.setImageBitmap(bitmap);
                    }
                    ImageDialog.setView(showImage);

                    ImageDialog.setNegativeButton("Close Preview", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });
                    ImageDialog.show();
                }
            });
            viewHolder.setOnClickListener(new MessageViewHolder.ClickListener() {
                @Override
                public void onItemClick(View view, int position, String id, PaymentRequest pr) {
                    //Toast.makeText(getActivity(), "Item clicked at " + position, Toast.LENGTH_SHORT).show();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("pr", pr);

                    if (initCipher(mCipher, DEFAULT_KEY_NAME)) {
                        // Show the fingerprint dialog. The user has the option to use the fingerprint with
                        // crypto, or you can fall back to using a server-side verified password.
                        DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication();
                        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                        boolean useFingerprintPreference = mSharedPreferences
                                .getBoolean(getString(R.string.use_fingerprint_to_authenticate_key), true);
                        if (useFingerprintPreference) {
                            fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.FINGERPRINT);
                        } else {
                            fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.PASSWORD);
                        }
                        fragment.setArguments(bundle);
                        fragment.setTargetFragment(mFragment, 0);
                        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
                    } else {
                        // This happens if the lock screen has been disabled or or a fingerprint got
                        // enrolled. Thus show the dialog to authenticate with their password first
                        // and ask the user if they want to authenticate with fingerprints in the
                        // future
                        DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication();
                        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                        fragment.setStage(
                                DialogFragmentFingerprintAuthentication.Stage.NEW_FINGERPRINT_ENROLLED);
                        fragment.setArguments(bundle);
                        fragment.setTargetFragment(mFragment, 0);
                        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
                    }
                }

            });
            return viewHolder;
        }

    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
    } catch (KeyStoreException e) {
        throw new RuntimeException("Failed to get an instance of KeyStore", e);
    }
    try {
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    }
    //Cipher defaultCipher;
    Cipher cipherNotInvalidated;
    try {
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        cipherNotInvalidated = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    }
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

    KeyguardManager keyguardManager = getActivity().getSystemService(KeyguardManager.class);
    FingerprintManager fingerprintManager = getActivity().getSystemService(FingerprintManager.class);

    if (!keyguardManager.isKeyguardSecure()) {
        // Show a message that the user hasn't set up a fingerprint or lock screen.
        Toast.makeText(getActivity(),
                "Secure lock screen hasn't set up.\n"
                        + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint",
                Toast.LENGTH_LONG).show();
        //return;
    }

    // Now the protection level of USE_FINGERPRINT permission is normal instead of dangerous.
    // See http://developer.android.com/reference/android/Manifest.permission.html#USE_FINGERPRINT
    // The line below prevents the false positive inspection from Android Studio
    // noinspection ResourceType
    if (!fingerprintManager.hasEnrolledFingerprints()) {
        // This happens when no fingerprints are registered.
        Toast.makeText(getActivity(),
                "Go to 'Settings -> Security -> Fingerprint' and register at least one fingerprint",
                Toast.LENGTH_LONG).show();
        //return;
    }

    createKey(DEFAULT_KEY_NAME, true);
    createKey(KEY_NAME_NOT_INVALIDATED, false);

    return view;

}