Example usage for android.util Base64 DEFAULT

List of usage examples for android.util Base64 DEFAULT

Introduction

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

Prototype

int DEFAULT

To view the source code for android.util Base64 DEFAULT.

Click Source Link

Document

Default values for encoder/decoder flags.

Usage

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

public void initfragFileChooserQuizlet(final MainActivity main, final String username,
        final String searchPhrase) {
    this.username = username;
    this.searchPhrase = searchPhrase;
    this._main = main;
    //String passwd = lib.InputBox(_main,"password","password","",false).input;
    QUIZLET_CLIENT_ID = new String(Base64.decode(Data.QuizletClientID, Base64.DEFAULT));
    browseApiUrl = "https://api.quizlet.com/2.0/search/sets?client_id=" + QUIZLET_CLIENT_ID
            + "&time_format=fuzzy_date";
    getSetApiUrl = "https://api.quizlet.com/2.0/sets?client_id=" + QUIZLET_CLIENT_ID + "&set_ids=";
    blnAdapterInvalid = true;//from  w  ww .j  ava 2s.  co m
}

From source file:com.oakesville.mythling.util.HttpHelper.java

private byte[] retrieveWithBasicAuth() throws IOException {
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Accept", "application/json");
    String credentials = Base64.encodeToString((user + ":" + password).getBytes(), Base64.DEFAULT);
    headers.put("Authorization", "Basic " + credentials);
    return retrieve(headers);
}

From source file:com.amansoni.tripbook.activity.FacebookActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Add code to print out the key hash
    try {/*from   ww  w. j  a va 2 s  .c  o m*/
        PackageInfo info = getPackageManager().getPackageInfo("com.amansoni.tripbook",
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }

    setContentView(R.layout.facebook_activity);

    loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
        @Override
        public void onUserInfoFetched(GraphUser user) {
            FacebookActivity.this.user = user;
            updateUI();
            // It's possible that we were waiting for this.user to be populated in order to post a
            // status update.
            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) {
            onClickPostStatusUpdate();
        }
    });

    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();
        }
    });

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

    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.ericrgon.postmark.BaseFragmentActivity.java

private byte[] getSalt() {
    SharedPreferences preferences = getSharedPreferences(CREDENTIALS_PREF_FILE, MODE_PRIVATE);
    byte[] salt;/*  w w  w  .  j a  v  a2 s. c om*/
    if (preferences.contains(SALT_PREF)) {
        salt = Base64.decode(preferences.getString(SALT_PREF, ""), Base64.DEFAULT);
    } else {
        //Generate a new salt if one doesn't exist.
        salt = SecurityUtil.generateSalt().getEncoded();
        SharedPreferences.Editor editor = preferences.edit().putString(SALT_PREF,
                Base64.encodeToString(salt, Base64.DEFAULT));
        editor.apply();
    }

    return salt;
}

From source file:mobisocial.musubi.nearby.GpsBroadcastTask.java

@Override
protected Void doInBackground(Void... params) {
    if (DBG)/*w w  w .jav  a2s  . com*/
        Log.d(TAG, "Uploading group for nearby gps...");
    while (!mmLocationScanComplete) {
        synchronized (mmLocationResult) {
            if (!mmLocationScanComplete) {
                try {
                    if (DBG)
                        Log.d(TAG, "Waiting for location results...");
                    mmLocationResult.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }
    if (DBG)
        Log.d(TAG, "Got location " + mmLocation);
    if (isCancelled()) {
        return null;
    }

    try {
        SQLiteOpenHelper db = App.getDatabaseSource(mContext);
        FeedManager fm = new FeedManager(db);
        IdentitiesManager im = new IdentitiesManager(db);
        String group_name = UiUtil.getFeedNameFromMembersList(fm, mFeed);
        byte[] group_capability = mFeed.capability_;
        List<MIdentity> owned = im.getOwnedIdentities();
        MIdentity sharer = null;
        for (MIdentity i : owned) {
            if (i.type_ != Authority.Local) {
                sharer = i;
                break;
            }
        }
        String sharer_name = UiUtil.safeNameForIdentity(sharer);
        byte[] sharer_hash = sharer.principalHash_;

        byte[] thumbnail = fm.getFeedThumbnailForId(mFeed.id_);
        if (thumbnail == null)
            thumbnail = im.getMusubiThumbnail(sharer) != null ? sharer.musubiThumbnail_
                    : im.getThumbnail(sharer);
        int member_count = fm.getFeedMemberCount(mFeed.id_);

        JSONObject group = new JSONObject();
        group.put("group_name", group_name);
        group.put("group_capability", Base64.encodeToString(group_capability, Base64.DEFAULT));
        group.put("sharer_name", sharer_name);
        group.put("sharer_type", sharer.type_.ordinal());
        group.put("sharer_hash", Base64.encodeToString(sharer_hash, Base64.DEFAULT));
        if (thumbnail != null)
            group.put("thumbnail", Base64.encodeToString(thumbnail, Base64.DEFAULT));
        group.put("member_count", member_count);

        byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes());
        byte[] data = group.toString().getBytes();
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);

        byte[] partial_enc_data;
        Cipher cipher;
        AlgorithmParameterSpec iv_spec;
        SecretKeySpec sks;
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        } catch (Exception e) {
            throw new RuntimeException("AES not supported on this platform", e);
        }
        try {
            iv_spec = new IvParameterSpec(iv);
            sks = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, sks, iv_spec);
        } catch (Exception e) {
            throw new RuntimeException("bad iv or key", e);
        }
        try {
            partial_enc_data = cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException("body encryption failed", e);
        }

        TByteArrayList bal = new TByteArrayList(iv.length + partial_enc_data.length);
        bal.add(iv);
        bal.add(partial_enc_data);
        byte[] enc_data = bal.toArray();

        if (DBG)
            Log.d(TAG, "Posting to gps server...");

        Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/sharegroup");

        StringBuffer sb = new StringBuffer();
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri.toString());
        httpPost.addHeader("Content-Type", "application/json");
        JSONArray buckets = new JSONArray();
        JSONObject descriptor = new JSONObject();

        double lat = mmLocation.getLatitude();
        double lng = mmLocation.getLongitude();
        long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2);
        for (long c : coords) {
            MessageDigest md;
            try {
                byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes();
                md = MessageDigest.getInstance("SHA-256");
                ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length);
                b.putLong(c);
                b.put(obfuscate);
                String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT);
                buckets.put(buckets.length(), secret_bucket);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("your platform does not support sha256", e);
            }
        }
        descriptor.put("buckets", buckets);
        descriptor.put("data", Base64.encodeToString(enc_data, Base64.DEFAULT));
        descriptor.put("expiration", new Date().getTime() + 1000 * 60 * 60);

        httpPost.setEntity(new StringEntity(descriptor.toString()));
        try {
            HttpResponse execute = client.execute(httpPost);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                if (isCancelled()) {
                    return null;
                }
                sb.append(s);
            }
            if (sb.toString().equals("ok"))
                mSucceeded = true;
            else {
                System.err.println(sb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //TODO: report failures etc
    } catch (Exception e) {
        Log.e(TAG, "Failed to broadcast group", e);
    }
    return null;
}

From source file:ca.rmen.android.networkmonitor.app.email.Emailer.java

/**
 * Append the given attachments to the message which is being written by the given writer.
 *
 * @param boundary separates each file attachment
 *///w w  w .ja  v a  2s .  c o  m
private static void appendAttachments(Writer writer, String boundary, Collection<File> attachments)
        throws IOException {
    for (File attachment : attachments) {
        ByteArrayOutputStream fileOs = new ByteArrayOutputStream((int) attachment.length());
        FileInputStream fileIs = new FileInputStream(attachment);
        try {
            IoUtil.copy(fileIs, fileOs);
        } finally {
            IoUtil.closeSilently(fileIs, fileOs);
        }
        final String mimeType = attachment.getName().substring(attachment.getName().indexOf(".") + 1);
        writer.write("--" + boundary + "\n");
        writer.write("Content-Type: application/" + mimeType + "; name=\"" + attachment.getName() + "\"\n");
        writer.write("Content-Disposition: attachment; filename=\"" + attachment.getName() + "\"\n");
        writer.write("Content-Transfer-Encoding: base64\n\n");
        String encodedFile = Base64.encodeToString(fileOs.toByteArray(), Base64.DEFAULT);
        writer.write(encodedFile);
        writer.write("\n");
    }
}

From source file:com.tapcentive.sdk.touchpoint.nfc.SEManager.java

/**
 * Do tapcentive interaction.//from  ww w.  j a v a2s. co  m
 *
 * @param storage the storage
 * @return the interaction response
 * @throws TapcentiveException the tapcentive exception
 */
public InteractionResponse doTapcentiveInteraction(ProfileStorage storage) throws TapcentiveException {
    long time1 = SystemClock.uptimeMillis();

    @SuppressWarnings("unused")
    String prof = storage.getProfile();

    byte[] profile = Base64.decode(storage.getProfile(), Base64.DEFAULT);
    byte[] informationCommand = new byte[5 + profile.length];

    System.arraycopy(informationHeader, 0, informationCommand, 0, 5);
    System.arraycopy(profile, 0, informationCommand, 5, profile.length);

    informationCommand[4] = (byte) (profile.length);

    byte[] responseBuffer = sendAndReceive(informationCommand);

    long time2 = SystemClock.uptimeMillis();
    Log.d(TAG, "TIME: doTapcentiveIngeraction:sendAndReceive: " + (time2 - time1));

    InteractionResponse iResponse = new InteractionResponse(responseBuffer);
    long time3 = SystemClock.uptimeMillis();
    Log.d(TAG, "TIME: do TapcentiveInteraction:new InteractionResponse: " + (time3 - time2));

    return iResponse;
}

From source file:com.mhise.util.MHISEUtil.java

public static boolean saveImportedCertificateToDevice(String certificate, String password, Context ctx,
        String certName) {//from  w  w  w  . java 2  s.com
    boolean isPasswordCorrect = false;

    byte[] certificatebytes = null;

    try {
        certificatebytes = Base64.decode(certificate, Base64.DEFAULT);
    } catch (IllegalArgumentException e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->saveImportedCertificateToDevice", "" + e);
    }
    KeyStore localTrustStore = null;
    try {
        localTrustStore = KeyStore.getInstance("PKCS12");
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream is = new ByteArrayInputStream(certificatebytes);
    try {
        localTrustStore.load(is, password.toCharArray());
        isPasswordCorrect = true;

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

    OutputStream fos = null;
    try {
        //<<<<<<< .mine
        //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE);
        //String  storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null);

        File _mobiusDirectory = new File(Constants.defaultP12StorePath);

        if (!_mobiusDirectory.exists()) {
            _mobiusDirectory.mkdir();
        }

        File file = new File(Constants.defaultP12StorePath + certName);
        fos = new FileOutputStream(file);
        //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
        localTrustStore.store(fos, MHISEUtil.getStrongPassword(certName).toCharArray());
        /*//=======
                    //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE);
                    //String  storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null);
                            
                            
                    File file = new File(Constants.defaultP12StorePath+certName);
                     fos = new FileOutputStream(file);
                    //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
                    localTrustStore.store(fos,MHISEUtil.getStrongPassword(certName).toCharArray());
        >>>>>>> .r4477*/
        fos.close();

        Enumeration<String> aliases = null;
        try {
            aliases = localTrustStore.aliases();
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //boolean isInstalledCertificateValid = false;

        while (aliases.hasMoreElements()) {

            String alias = aliases.nextElement();
            java.security.cert.X509Certificate cert = null;
            try {
                cert = (X509Certificate) localTrustStore.getCertificate(alias);
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            SharedPreferences sharedPreferences1 = ctx.getSharedPreferences(Constants.PREFS_NAME,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences1.edit();

            Log.i("Imported certificate serial number", "" + cert.getSerialNumber().toString(16));
            editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16));
            editor.commit();

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return isPasswordCorrect;
}

From source file:com.wordsbaking.cordova.wechat.WeChat.java

private void share(JSONArray args, CallbackContext callbackContext) throws JSONException, NullPointerException {
    // check if installed
    if (!api.isWXAppInstalled()) {
        callbackContext.error(ERR_WECHAT_NOT_INSTALLED);
        return;/*from   w ww  .j  a v  a2 s  .  co  m*/
    }

    JSONObject params = args.getJSONObject(0);

    if (params == null) {
        callbackContext.error(ERR_INVALID_OPTIONS);
        return;
    }

    SendMessageToWX.Req request = new SendMessageToWX.Req();

    request.transaction = String.valueOf(System.currentTimeMillis());

    int paramScene = params.getInt("scene");

    switch (paramScene) {
    case SCENE_SESSION:
        request.scene = SendMessageToWX.Req.WXSceneSession;
        break;
    // wechat android sdk does not support chosen by user
    case SCENE_CHOSEN_BY_USER:
    case SCENE_TIMELINE:
    default:
        request.scene = SendMessageToWX.Req.WXSceneTimeline;
        break;
    }

    WXMediaMessage message = null;

    String text = null;
    JSONObject messageOptions = null;

    if (!params.isNull("text")) {
        text = params.getString("text");
    }

    if (!params.isNull("message")) {
        messageOptions = params.getJSONObject("message");
    }

    if (messageOptions != null) {
        String url = null;
        String data = null;

        if (!messageOptions.isNull("url")) {
            url = messageOptions.getString("url");
        }

        if (!messageOptions.isNull("data")) {
            data = messageOptions.getString("data");
        }

        int type = SHARE_TYPE_WEBPAGE;

        if (!messageOptions.isNull("type")) {
            type = messageOptions.getInt("type");
        }

        switch (type) {
        case SHARE_TYPE_APP:
            break;
        case SHARE_TYPE_EMOTION:
            break;
        case SHARE_TYPE_FILE:
            break;
        case SHARE_TYPE_IMAGE:
            WXImageObject imageObject = new WXImageObject();
            if (url != null) {
                imageObject.imageUrl = url;
            } else if (data != null) {
                imageObject.imageData = Base64.decode(data, Base64.DEFAULT);
            } else {
                callbackContext.error(ERR_INVALID_OPTIONS);
                return;
            }
            message = new WXMediaMessage(imageObject);
            break;
        case SHARE_TYPE_MUSIC:
            break;
        case SHARE_TYPE_VIDEO:
            break;
        case SHARE_TYPE_WEBPAGE:
        default:
            WXWebpageObject webpageObject = new WXWebpageObject();
            webpageObject.webpageUrl = url;
            message = new WXMediaMessage(webpageObject);
            break;
        }

        if (message == null) {
            callbackContext.error(ERR_UNSUPPORTED_MEDIA_TYPE);
            return;
        }

        if (!messageOptions.isNull("title")) {
            message.title = messageOptions.getString("title");
        }

        if (!messageOptions.isNull("description")) {
            message.description = messageOptions.getString("description");
        }

        if (!messageOptions.isNull("thumbData")) {
            String thumbData = messageOptions.getString("thumbData");
            message.thumbData = Base64.decode(thumbData, Base64.DEFAULT);
        }
    } else if (text != null) {
        WXTextObject textObject = new WXTextObject();
        textObject.text = text;

        message = new WXMediaMessage(textObject);
        message.description = text;
    } else {
        callbackContext.error(ERR_INVALID_OPTIONS);
        return;
    }

    request.message = message;

    try {
        boolean success = api.sendReq(request);
        if (!success) {
            callbackContext.error(ERR_UNKNOWN);
            return;
        }
    } catch (Exception e) {
        callbackContext.error(e.getMessage());
        return;
    }

    currentCallbackContext = callbackContext;
}

From source file:jp.alessandro.android.iab.Security.java

/**
 * Verifies that the signature from the server matches the computed
 * signature on the data.  Returns true if the data is correctly signed.
 *
 * @param logger     the logger to use for printing events
 * @param publicKey  rsa public key generated by Google Play Developer Console
 * @param signedData signed data from server
 * @param signature  server signature//from www. ja v  a  2 s  .  c  o m
 * @return true if the data and signature match
 */
protected boolean verify(Logger logger, PublicKey publicKey, String signedData, String signature)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException,
        InvalidKeyException, SignatureException, IllegalArgumentException {

    byte[] signatureBytes = Base64.decode(signature, Base64.DEFAULT);
    Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);

    sig.initVerify(publicKey);
    sig.update(signedData.getBytes("UTF-8"));
    if (!sig.verify(signatureBytes)) {
        logger.e(Logger.TAG, "Signature verification failed.");
        return false;
    }
    return true;
}