Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

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

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:eu.codeplumbers.cosi.api.tasks.UnregisterDeviceTask.java

public UnregisterDeviceTask(AboutFragment aboutFragment, String password) {
    this.aboutFragment = aboutFragment;
    resultDevice = null;//from  w  w  w  .j  a  v a2 s  . c  o m

    Device device = Device.registeredDevice();

    // cozy register device url
    this.url = device.getUrl() + "/device/";
    // concatenate username and password with colon for authentication
    final String credentials = "owner" + ":" + password;
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    dialog = new ProgressDialog(aboutFragment.getActivity());
    dialog.setCancelable(false);
    dialog.setMessage("Please wait");
    dialog.setIndeterminate(true);
    dialog.show();

}

From source file:eu.codeplumbers.cosi.api.tasks.DeleteFileTask.java

public DeleteFileTask(FileManagerFragment fileManagerFragment) {
    this.fileManagerFragment = fileManagerFragment;

    Device device = Device.registeredDevice();

    // delete all local notes
    new Delete().from(Note.class).execute();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    dialog = new ProgressDialog(fileManagerFragment.getActivity());
    dialog.setCancelable(false);/* w  w w.  j  a  v  a2s . co  m*/
    dialog.setProgress(0);
    dialog.setMax(100);
    dialog.setMessage("Please wait");
    dialog.setIndeterminate(false);
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    dialog.show();

}

From source file:eu.codeplumbers.cosi.api.tasks.SyncDocumentTask.java

public SyncDocumentTask(Activity activity) {
    this.activity = activity;
    result = "";/*  w w  w .j ava  2 s. c  om*/

    Device device = Device.registeredDevice();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    dialog = new ProgressDialog(activity);
    dialog.setCancelable(false);
    dialog.setProgress(0);
    dialog.setMax(100);
    dialog.setMessage("Please wait");
    dialog.setIndeterminate(false);
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    dialog.show();

}

From source file:eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java

public GetPlacesTask(PlacesFragment placesFragment) {
    this.placesFragment = placesFragment;
    allPlaces = new ArrayList<>();

    Device device = Device.registeredDevice();

    // delete all local places
    new Delete().from(Place.class).execute();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/request/place/all/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    dialog = new ProgressDialog(placesFragment.getActivity());
    dialog.setCancelable(false);//w  w w  .  j a  v a2 s .  c  o  m
    dialog.setMessage("Please wait");
    dialog.setIndeterminate(true);
    dialog.show();

}

From source file:com.auth0.util.Telemetry.java

public String asBase64() {
    Map<String, Object> info = new HashMap<>();
    info.put("name", getName("Lock.Android"));
    info.put("version", getVersion(BuildConfig.VERSION_NAME));
    if (isNonEmpty(this.libraryVersion)) {
        info.put("lib_version", this.libraryVersion);
    }//from   w w w .  j ava 2s .com
    if (this.extra != null) {
        info.putAll(this.extra);
    }
    String clientInfo = null;
    try {
        String json = new ObjectMapper().writeValueAsString(info);
        Log.v(TAG, "Telemetry JSON is " + json);
        clientInfo = Base64.encodeToString(json.getBytes(Charset.defaultCharset()),
                Base64.URL_SAFE | Base64.NO_WRAP);
    } catch (JsonProcessingException e) {
        Log.w(TAG, "Failed to build client info", e);
    }
    return clientInfo;
}

From source file:org.jboss.aerogear.unifiedpush.quickstart.util.WebClient.java

public User authenticate(String username, String password) {

    try {//from   w  w  w  .jav a  2 s  . c o  m

        String loginURL = Constants.BASE_URL + "/rest/security/user/info";
        String credentials = username + ":" + password;
        String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

        HttpGet get = new HttpGet(loginURL);

        get.setHeader("Authorization", "Basic " + base64EncodedCredentials);
        get.setHeader("Accept", "application/json");
        get.setHeader("Content-type", "application/json");

        HttpResponse response = httpClient.execute(get);

        if (isStatusCodeOk(response)) {
            String responseData = EntityUtils.toString(response.getEntity());

            Gson gson = new GsonBuilder().create();

            Map<String, Object> rootNode = gson.fromJson(responseData, Map.class);
            String innerJson = gson.toJson(rootNode.get("account"));
            return gson.fromJson(innerJson, User.class);
        } else {
            return null;
        }

    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        return null;
    }

}

From source file:com.remobile.cordova.PluginResult.java

public PluginResult(Status status, byte[] data, boolean binaryString) {
    this.status = status.ordinal();
    this.messageType = binaryString ? MESSAGE_TYPE_BINARYSTRING : MESSAGE_TYPE_ARRAYBUFFER;
    this.strMessage = Base64.encodeToString(data, Base64.NO_WRAP);
}

From source file:com.tapcentive.minimalist.JWTHelper.java

/***
 * Generates a JSON Web Token. This token uses the supplied application key to sign the token
 * content which should uniquely identify the client's customer (e.g. a loyalty number, email
 * etc.) and contain any Tapcentive audience IDs assigned to this customer. This example does
 * not require that either parameter be present.
 * @param originalBody/*from w  w  w. j  av  a 2  s  .com*/
 * @param audiences
 * @param customerId
 * @return
 */
public String createJWT(JSONObject originalBody, List<String> audiences, String customerId) {

    try {
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject(originalBody.toString());
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        body.put("iss", _keyid);

        if ((audiences != null) && (audiences.size() > 0)) {
            JSONArray attrArray = new JSONArray(audiences);
            body.put("audiences", attrArray);
        }

        if (customerId != null) {
            body.put("customer_xid", customerId);
        }

        String signedContent = Base64.encodeToString(header.toString().getBytes("UTF-8"), Base64.NO_WRAP) + "."
                + Base64.encodeToString(body.toString().getBytes("UTF-8"), Base64.NO_WRAP);
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(_key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        String signature = Base64.encodeToString(sha256_HMAC.doFinal(signedContent.getBytes("UTF-8")),
                Base64.NO_WRAP);
        return signedContent + "." + signature;
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.liato.bankdroid.banking.banks.avanza.Avanza.java

public Urllib login() throws LoginException, BankException {
    urlopen = new Urllib(context, CertificateReader.getCertificates(context, R.raw.cert_avanza));
    urlopen.addHeader("ctag", "1122334455");
    urlopen.addHeader("Authorization",
            "Basic " + Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.NO_WRAP));

    try {//from   www. j  av  a  2s.co  m
        HttpResponse httpResponse = urlopen.openAsHttpResponse(API_URL + "account/overview/all",
                new ArrayList<NameValuePair>(), false);
        if (httpResponse.getStatusLine().getStatusCode() == 401) {
            throw new LoginException(context.getText(R.string.invalid_username_password).toString());
        }
        ObjectMapper vObjectMapper = new ObjectMapper();
        AccountOverview r = vObjectMapper.readValue(httpResponse.getEntity().getContent(),
                AccountOverview.class);
        for (com.liato.bankdroid.banking.banks.avanza.model.Account account : r.getAccounts()) {
            Account a = new Account(account.getAccountName(), new BigDecimal(account.getOwnCapital()),
                    account.getAccountId());
            if (!account.getCurrencyAccounts().isEmpty()) {
                a.setCurrency(account.getCurrencyAccounts().get(0).getCurrency());
            }
            if (!account.getPositionAggregations().isEmpty()) {
                Date now = new Date();
                ArrayList<Transaction> transactions = new ArrayList<Transaction>();
                for (PositionAggregation positionAgList : account.getPositionAggregations()) {
                    if (positionAgList.getPositions().isEmpty()) {
                        continue;
                    }
                    List<Position> positions = positionAgList.getPositions();
                    transactions.add(new Transaction(Helpers.formatDate(now),
                            "\u2014  " + positionAgList.getInstrumentTypeName() + "  "
                                    + positionAgList.getTotalProfitPercent() + "%  \u2014",
                            BigDecimal.valueOf(positionAgList.getTotalValue()), a.getCurrency()));
                    for (Position p : positions) {
                        Transaction t = new Transaction(Helpers.formatDate(now), p.getInstrumentName(),
                                BigDecimal.valueOf(p.getProfit()), a.getCurrency());
                        transactions.add(t);
                    }
                }
                a.setTransactions(transactions);
            }
            accounts.add(a);
        }
    } catch (JsonParseException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    }
    return urlopen;
}

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

public static void writeEncryptedKeys(@Nonnull final Writer out, @Nonnull final List<ECKey> keys,
        SharedPreferences prefs, String passOrNFC) throws IOException {

    boolean nfcEnabled = prefs.contains(Constants.SHAMIR_ENCRYPTED_KEY) ? false : true;

    String x1 = prefs.getString(Constants.SHAMIR_LOCAL_KEY, null);
    String x2 = null;// w ww. j a v  a 2s  . c o  m
    String encodedEncryptedX2 = null;

    if (!nfcEnabled) {
        x2 = prefs.getString(Constants.SHAMIR_ENCRYPTED_KEY, null);
        String encryptedX2 = encryptString(x2, passOrNFC);
        encodedEncryptedX2 = Base64.encodeToString(encryptedX2.getBytes("UTF-8"), Base64.NO_WRAP);
    }

    out.write("# PRIVATE KEYS ARE ENCRYPTED WITH SHAMIR SECRET SHARING\n");
    out.write("# TO DECRYPT - Import this backup and provide your password or NFC token\n");
    out.write("# If password/NFC token are lost, contact Bitcoin Security Project. We may be able to help.\n");
    out.write("#" + x1);
    out.write("\n");

    if (!nfcEnabled && encodedEncryptedX2 != null) {
        out.write("#X2:" + encodedEncryptedX2);
        out.write("\n");
        out.write("#ENCTYPE:PASSWORD");
    }
    //Means NFC is enabled and we're using that for encryption
    else if (nfcEnabled) {
        out.write("#ENCTYPE:NFC");
    }

    out.write("\n");

    BigInteger mainKey = null;
    if (nfcEnabled) {
        mainKey = generateSecretFromStrings(x1, passOrNFC, null);
    } else if (x2 != null) {
        mainKey = generateSecretFromStrings(x1, x2, null);
    }

    String mainKeyHash = convertToSha256(mainKey.toString());

    for (final ECKey key : keys) {
        String encodedKey = key.getPrivateKeyEncoded(Constants.NETWORK_PARAMETERS).toString();
        String encryptedKey = encryptString(encodedKey, mainKeyHash);

        out.write(Base64.encodeToString(encryptedKey.getBytes(), Base64.NO_WRAP));
        out.write('\n');
    }
}