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:com.owncloud.android.utils.EncryptionUtils.java

public static String decodeBase64BytesToString(byte[] bytes) {
    try {/* ww w.j av  a 2  s .co m*/
        return new String(Base64.decode(bytes, Base64.NO_WRAP));
    } catch (Exception e) {
        return "";
    }
}

From source file:com.nuvolect.securesuite.data.ExportVcf.java

/**
 * Create a single vcard from a contact record
 * @param contact_id/*  w  w  w  .j  a v a 2 s. c o  m*/
 * @return appended vcard
 */
public static VCard makeVcard(long contact_id) {

    VCard vcard = new VCard();
    try {
        vcard.setKind(Kind.individual());
        vcard.addLanguage("en-US");

        String full_name = NameUtil.getFullName(contact_id);
        vcard.setFormattedName(full_name);
        {
            StructuredName n = new StructuredName();
            String prefix = SqlCipher.getKv(contact_id, KvTab.name_prefix);
            n.addPrefix(prefix);
            String first = SqlCipher.getKv(contact_id, KvTab.name_first);
            n.setGiven(first);
            String last = SqlCipher.getKv(contact_id, KvTab.name_last);
            n.setFamily(last);
            String suffix = SqlCipher.getKv(contact_id, KvTab.name_suffix);
            n.addSuffix(suffix);
            vcard.setStructuredName(n);

            //                if( prefix.isEmpty() && first.isEmpty() && last.isEmpty() && suffix.isEmpty())//TODO remove
            //                    n.setFamily(full_name);
        }
        {
            JSONArray itemArray = new JSONArray(SqlCipher.get(contact_id, DTab.address));
            for (int i = 0; i < itemArray.length(); i++) {

                JSONObject item = itemArray.getJSONObject(i);
                Iterator<?> item_keys = item.keys();
                String item_label = (String) item_keys.next();
                final String item_value = item.getString(item_label);

                Address adr = new Address();
                adr.setStreetAddress(item_value);
                if (item_label.contentEquals("HOME"))
                    adr.addType(AddressType.HOME);
                else if (item_label.contentEquals("WORK"))
                    adr.addType(AddressType.WORK);

                vcard.addAddress(adr);
            }
        }
        {
            JSONArray itemArray = new JSONArray(SqlCipher.get(contact_id, DTab.phone));
            for (int i = 0; i < itemArray.length(); i++) {

                JSONObject item = itemArray.getJSONObject(i);
                Iterator<?> item_keys = item.keys();
                String item_label = (String) item_keys.next();
                final String item_value = item.getString(item_label);

                TelephoneType type = null;
                if (item_label.contentEquals("HOME"))
                    type = TelephoneType.HOME;
                else if (item_label.contentEquals("WORK"))
                    type = TelephoneType.WORK;

                if (type == null)
                    vcard.addTelephoneNumber(item_value);
                else
                    vcard.addTelephoneNumber(item_value, type);
            }
        }
        {
            JSONArray itemArray = new JSONArray(SqlCipher.get(contact_id, DTab.email));
            for (int i = 0; i < itemArray.length(); i++) {

                JSONObject item = itemArray.getJSONObject(i);
                Iterator<?> item_keys = item.keys();
                String item_label = (String) item_keys.next();
                final String item_value = item.getString(item_label);

                EmailType type = null;
                if (item_label.contentEquals("HOME"))
                    type = EmailType.HOME;
                else if (item_label.contentEquals("WORK"))
                    type = EmailType.WORK;

                if (type == null)
                    vcard.addEmail(item_value);
                else
                    vcard.addEmail(item_value, type);
            }
        }
        {
            JSONArray itemArray = new JSONArray(SqlCipher.get(contact_id, DTab.website));
            for (int i = 0; i < itemArray.length(); i++) {

                JSONObject item = itemArray.getJSONObject(i);
                Iterator<?> item_keys = item.keys();
                String item_label = (String) item_keys.next();
                final String item_value = item.getString(item_label);

                vcard.addUrl(item_value);
            }
        }
        {
            String photoStr = SqlCipher.get(contact_id, DTab.photo);
            byte[] b = null;
            b = Base64.decode(photoStr.getBytes(), Base64.DEFAULT);
            Photo photo = new Photo(b, ImageType.PNG);
            vcard.addPhoto(photo);
        }
        {
            String noteStr = SqlCipher.getKv(contact_id, KvTab.note);
            Note note = vcard.addNote(noteStr); // can contain newlines
            note.setLanguage("en-us");
        }
        {
            String organization = SqlCipher.getKv(contact_id, KvTab.organization);
            vcard.setOrganization(organization, "");// second parameter is department
        }
        {
            String title = SqlCipher.getKv(contact_id, KvTab.title);
            vcard.addTitle(title);
        }
        //FUTURE export im
        //FUTURE export dates
        //FUTURE export relation

    } catch (JSONException e) {
        LogUtil.logException(m_act, LogType.EXPORT_VCF, e);
    }
    return vcard;
}

From source file:net.named_data.accessmanager.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == AUTHORIZE_REQUEST) {
        // Make sure the request was successful
        if (resultCode == Activity.RESULT_OK) {
            String signerID = data.getStringExtra("prefix");
            Name appID = new Name(signerID).append(APP_NAME);
            mAppId = appID.toUri();//from  w  w  w . j  a  va2  s  .c o  m
            try {
                String encodedString = generateKey(appID.toString());
                requestSignature(encodedString, signerID);
            } catch (Exception e) {
                Log.e(TAG, "Exception in identity generation/request");
                Log.e(TAG, e.getMessage());
            }
        }
    } else if (requestCode == SIGN_CERT_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            String signedCert = data.getStringExtra("signed_cert");
            byte[] decoded = Base64.decode(signedCert, Base64.DEFAULT);
            Blob blob = new Blob(decoded);
            Data certData = new Data();
            try {
                if (!mAppId.isEmpty()) {
                    certData.wireDecode(blob);
                    IdentityCertificate certificate = new IdentityCertificate(certData);
                    String signerKey = ((Sha256WithRsaSignature) certificate.getSignature()).getKeyLocator()
                            .getKeyName().toUri();
                    Log.d(TAG, "Signer key name " + signerKey);
                    Log.d(TAG, "App certificate name: " + certificate.getName().toUri());
                    DataBase.getInstance(getApplicationContext()).insertID(mAppId,
                            certificate.getName().toUri(), signerKey);
                    mAppCertificateName = new Name(certificate.getName());
                    Common.setUserPrefix(new Name(mAppId).getPrefix(-1));
                    Common.setAppID(mAppId, certificate);
                    Log.d(TAG, "try to start service");
                    startService(new Intent(this, AccessManagerService.class));
                } else {
                    Log.e(TAG, "mAppId empty for result of SIGN_CERT_REQUEST");
                }
            } catch (Exception e) {
                Log.e(getResources().getString(R.string.app_name), e.getMessage());
            }
        }
    }
}

From source file:org.openmidaas.library.test.MIDaaSTest.java

@SmallTest
public void testAttributeBundle() {
    Map<String, AbstractAttribute<?>> map = new HashMap<String, AbstractAttribute<?>>();
    map.put("mock1", new MockAttribute());
    String bundleAsString = MIDaaS.getAttributeBundle(VALID_CLIENT_ID, null, map);
    Assert.assertNotNull(bundleAsString);
    String[] segments = bundleAsString.split("\\.");
    String header = segments[0];/*  w ww . j  ava 2 s . co  m*/
    byte[] headerBytes = Base64.decode(header, Base64.NO_PADDING + Base64.NO_WRAP);
    byte[] bodyBytes = Base64.decode(segments[1], Base64.NO_PADDING + Base64.NO_WRAP);
    try {
        String headerAsString = new String(headerBytes, "UTF-8");
        JSONObject object = new JSONObject(headerAsString);
        if (!object.getString("alg").equals("none")) {
            Assert.fail();
        }
        String bodyAsString = new String(bodyBytes, "UTF-8");
        JSONObject bodyObject = new JSONObject(bodyAsString);
        if (!object.getString("alg").equals("none")) {
            Assert.fail();
        }
        if (!bodyObject.getString("iss").equals("org.openmidaas.library")) {
            Assert.fail();
        }
        if (!bodyObject.getString("aud").equals(VALID_CLIENT_ID)) {
            Assert.fail();
        }
        if (bodyObject.isNull("attrs")) {
            Assert.fail();
        }
        JSONObject attributes = bodyObject.getJSONObject("attrs");
        Iterator<?> keys = attributes.keys();
        // parsing through the "attrs" field now.
        while (keys.hasNext()) {
            String key = (String) keys.next();
            if (attributes.get(key) != null) {
                if (!attributes.get(key).equals("MockAttribute")) {
                    Assert.fail();
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        Assert.fail();
    } catch (JSONException e) {
        Assert.fail();
    }

}

From source file:libcore.tzdata.update_test_app.installupdatetestapp.MainActivity.java

private static PrivateKey createKey() throws Exception {
    byte[] derKey = Base64.decode(TEST_KEY.getBytes(), Base64.DEFAULT);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(derKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}

From source file:app.sunstreak.yourpisd.LoginActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_new);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);//  w  w w .j ava 2  s.co  m
    }
    final SharedPreferences sharedPrefs = getPreferences(Context.MODE_PRIVATE);
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    height = size.y;
    mLoginFormView = findViewById(R.id.login_form);
    mLoginStatusView = (LinearLayout) findViewById(R.id.login_status);
    mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

    if (DateHelper.isAprilFools()) {
        LinearLayout container = (LinearLayout) mLoginFormView.findViewById(R.id.container);
        ImageView logo = (ImageView) container.findViewById(R.id.logo);
        InputStream is;
        try {
            is = getAssets().open("doge.png");
            logo.setImageBitmap(BitmapFactory.decodeStream(is));
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    mAutoLogin = sharedPrefs.getBoolean("auto_login", false);
    System.out.println(mAutoLogin);

    session = ((YPApplication) getApplication()).session;

    try {
        boolean refresh = getIntent().getExtras().getBoolean("Refresh");

        if (refresh) {
            mEmail = session.getUsername();
            mPassword = session.getPassword();
            showProgress(true);
            mAuthTask = new UserLoginTask();
            mAuthTask.execute((Void) null);

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mPasswordView.getWindowToken(), 0);
        } else
            mLoginFormView.setVisibility(View.VISIBLE);
    } catch (NullPointerException e) {
        // Keep going.
    }

    if (sharedPrefs.getBoolean("patched", false)) {
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.remove("password");
        editor.putBoolean("patched", true);
        editor.commit();
    }

    if (!sharedPrefs.getBoolean("AcceptedUserAgreement", false)) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getResources().getString(R.string.user_agreement_title));
        builder.setMessage(getResources().getString(R.string.user_agreement));
        // Setting Positive "Yes" Button
        builder.setPositiveButton("Agree", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                sharedPrefs.edit().putBoolean("AcceptedUserAgreement", true).commit();
                dialog.cancel();
            }
        });

        // Setting Negative "NO" Button
        builder.setNegativeButton("Disagree", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                sharedPrefs.edit().putBoolean("AcceptedUserAgreement", false).commit();
                Toast.makeText(LoginActivity.this, "Quitting app", Toast.LENGTH_SHORT).show();
                finish();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    // Set up the remember_password CheckBox
    mRememberPasswordCheckBox = (CheckBox) findViewById(R.id.remember_password);
    mRememberPasswordCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mRememberPassword = isChecked;
        }
    });

    mRememberPassword = sharedPrefs.getBoolean("remember_password", false);
    mRememberPasswordCheckBox.setChecked(mRememberPassword);

    // Set up the auto_login CheckBox
    mAutoLoginCheckBox = (CheckBox) findViewById(R.id.auto_login);
    mAutoLoginCheckBox.setChecked(mAutoLogin);
    mAutoLoginCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton button, boolean isChecked) {
            mAutoLogin = isChecked;
            if (isChecked) {
                mRememberPasswordCheckBox.setChecked(true);
            }
        }

    });

    // Set up the login form.
    mEmailView = (EditText) findViewById(R.id.email);

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        }
    });

    //Load stored username/password
    mEmailView.setText(sharedPrefs.getString("email", mEmail));
    mPasswordView.setText(new String(Base64.decode(sharedPrefs.getString("e_password", ""), Base64.DEFAULT)));
    // If the password was not saved, give focus to the password.
    if (mPasswordView.getText().equals(""))
        mPasswordView.requestFocus();

    mLoginFormView = findViewById(R.id.login_form);
    mLoginStatusView = (LinearLayout) findViewById(R.id.login_status);
    mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

    findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            attemptLogin();
        }
    });
    findViewById(R.id.sign_in_button).setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mPasswordView.getWindowToken(), 0);
            return false;
        }
    });
    mLoginFormView.setVisibility(View.VISIBLE);
    // Login if auto-login is checked.
    if (mAutoLogin)
        attemptLogin();
}

From source file:de.gebatzens.sia.SiaAPI.java

public StaticData downloadStaticFile(String name, boolean snack) {
    StaticData data = new StaticData();
    data.name = name;/*w  ww.  ja v a 2 s  .  c om*/

    try {
        APIResponse re = doRequest("/static?token=" + getToken() + "&file=" + URLEncoder.encode(name, "UTF-8"),
                null);

        if (re.state == APIState.SUCCEEDED) {
            data.data = Base64.decode((String) re.data, Base64.DEFAULT);
        } else {
            throw new APIException(re.reason);
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (snack)
            showReloadSnackbar(
                    e instanceof IOException ? SIAApp.SIA_APP.getString(R.string.no_internet_connection)
                            : e.getMessage());
        if (!data.load()) {
            data.throwable = e;
        }

    }

    return data;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public Pair<JSONObject, byte[]> handleOutgoing(JSONObject json) {
    byte[] bytes = Base64.decode(json.optString(DATA), Base64.DEFAULT);
    json.remove(DATA);/*from w w w  .  j  a  va  2 s . c o  m*/
    return new Pair<JSONObject, byte[]>(json, bytes);
}

From source file:org.kde.kdeconnect.NetworkPackage.java

public NetworkPackage decrypt(PrivateKey privateKey) throws GeneralSecurityException, JSONException {

    JSONArray chunks = mBody.getJSONArray("data");

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    String decryptedJson = "";
    for (int i = 0; i < chunks.length(); i++) {
        byte[] encryptedChunk = Base64.decode(chunks.getString(i), Base64.NO_WRAP);
        String decryptedChunk = new String(cipher.doFinal(encryptedChunk));
        decryptedJson += decryptedChunk;
    }/*from w  w  w .ja  v  a2  s.c  o m*/

    NetworkPackage decrypted = unserialize(decryptedJson);
    decrypted.setPayload(mPayload, mPayloadSize);
    return decrypted;
}

From source file:ca.ualberta.app.activity.CreateAnswerActivity.java

@Override
public void onStart() {
    super.onStart();
    Intent intent = getIntent();//from  w ww .j a  v  a  2 s.com
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            if (extras.getBoolean(EDIT_MODE)) {
                String answerContent = extras.getString(ANSWER_CONTENT);
                contentText.setText(answerContent);
                try {
                    byte[] imageByteArray = Base64.decode(extras.getByteArray(IMAGE), Base64.NO_WRAP);
                    image = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
                    scaleImage(THUMBIMAGESIZE, THUMBIMAGESIZE, true);
                    imageView.setVisibility(View.VISIBLE);
                    imageView.setImageBitmap(imageThumb);
                } catch (Exception e) {
                }

            }
        }
    }
}