Example usage for android.util Base64 NO_WRAP

List of usage examples for android.util Base64 NO_WRAP

Introduction

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

Prototype

int NO_WRAP

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

Click Source Link

Document

Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).

Usage

From source file:tv.ouya.sdk.TestOuyaFacade.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);//from   w w w  .  j  ava 2  s.  c  om
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(product.getIdentifier(),
            Base64.encodeToString(encryptedKey, Base64.NO_WRAP), Base64.encodeToString(ivBytes, Base64.NO_WRAP),
            Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }

    //custom-iap-code
    Log.i("TestOuyaFacade", "TestOuyaFacade.requestPurchase(" + product.getIdentifier() + ")");
    UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog",
            "TestOuyaFacade.requestPurchase(" + product.getIdentifier() + ")");

    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(product));
}

From source file:org.quantumbadger.redreader.reddit.api.RedditOAuth.java

public static FetchAccessTokenResult fetchAnonymousAccessTokenSynchronous(final Context context) {

    final String uri = ACCESS_TOKEN_URL;
    StatusLine responseStatus = null;/* w ww  .jav a 2 s.c om*/

    try {
        final HttpClient httpClient = CacheManager.createHttpClient(context);

        final HttpPost request = new HttpPost(uri);

        final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs
                .add(new BasicNameValuePair("grant_type", "https://oauth.reddit.com/grants/installed_client"));
        nameValuePairs.add(new BasicNameValuePair("device_id", "DO_NOT_TRACK_THIS_DEVICE"));
        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        request.addHeader("Authorization", "Basic "
                + Base64.encodeToString((CLIENT_ID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));

        final HttpResponse response = httpClient.execute(request);
        responseStatus = response.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            return new FetchAccessTokenResult(FetchAccessTokenResultStatus.UNKNOWN_ERROR,
                    new RRError(context.getString(R.string.error_unknown_title),
                            context.getString(R.string.message_cannotlogin), null, responseStatus,
                            request.getURI().toString()));
        }

        final JsonValue jsonValue = new JsonValue(response.getEntity().getContent());
        jsonValue.buildInThisThread();
        final JsonBufferedObject responseObject = jsonValue.asObject();

        final String accessTokenString = responseObject.getString("access_token");

        if (accessTokenString == null) {
            throw new RuntimeException("Null access token: " + responseObject.getString("error"));
        }

        final AccessToken accessToken = new AccessToken(accessTokenString);

        return new FetchAccessTokenResult(accessToken);

    } catch (IOException e) {
        return new FetchAccessTokenResult(FetchAccessTokenResultStatus.CONNECTION_ERROR,
                new RRError(context.getString(R.string.error_connection_title),
                        context.getString(R.string.error_connection_message), e, responseStatus, uri));

    } catch (Throwable t) {
        return new FetchAccessTokenResult(FetchAccessTokenResultStatus.UNKNOWN_ERROR,
                new RRError(context.getString(R.string.error_unknown_title),
                        context.getString(R.string.message_cannotlogin), t, responseStatus, uri));
    }
}

From source file:biz.bokhorst.xprivacy.Util.java

private static PublicKey getPublicKey(Context context) throws Throwable {
    // Read public key
    String sPublicKey = "";
    InputStreamReader isr = new InputStreamReader(context.getAssets().open("XPrivacy_public_key.txt"), "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();/*from  w  w  w .j a v  a2  s  .  c  o  m*/
    while (line != null) {
        if (!line.startsWith("-----"))
            sPublicKey += line;
        line = br.readLine();
    }
    br.close();
    isr.close();

    // Create public key
    byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey);
    return keyFactory.generatePublic(encodedPubKeySpec);
}

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

/**
 * compress the image to 64kb/*from ww w. ja va  2s. co m*/
 * 
 * @return return the imageString after compressed
 */
private String compressImage() {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    int quality = 100;
    while (stream.toByteArray().length > 65536 && quality != 0) {
        stream.reset();
        image.compress(Bitmap.CompressFormat.JPEG, quality, stream);
        quality -= 10;
    }
    if (quality == 0)
        return null;
    return Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
}

From source file:tv.ouya.sdk.UnityOuyaFacade.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);/*  w  w  w  . ja  va 2 s  .  c  o m*/
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(product.getIdentifier(),
            Base64.encodeToString(encryptedKey, Base64.NO_WRAP), Base64.encodeToString(ivBytes, Base64.NO_WRAP),
            Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }

    //custom-iap-code
    Log.i(LOG_TAG, "UnityOuyaFacade.requestPurchase(" + product.getIdentifier() + ")");
    UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog",
            "UnityOuyaFacade.requestPurchase(" + product.getIdentifier() + ")");

    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(product));
}

From source file:com.danielme.muspyforandroid.services.MuspyClient.java

private void setAuthHeader(AbstractHttpMessage abstractHttpMessage, Context context)
        throws AuthorizationException {
    abstractHttpMessage.setHeader(AUTHORIZATION, "Basic " + Base64.encodeToString(
            (Utils.getEmail(context) + ":" + Utils.getPass(context)).getBytes(), Base64.NO_WRAP));
}

From source file:com.shopify.buy.dataprovider.BuyClient.java

/**
 * Post a credit card to Shopify's card server and associate it with a Checkout
 *
 * @param card     the {@link CreditCard} to associate
 * @param checkout the {@link Checkout} to associate the card with
 * @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
 *///w  w  w . j a v a  2  s.  c  o  m
public void storeCreditCard(final CreditCard card, final Checkout checkout, final Callback<Checkout> callback) {
    if (card == null) {
        throw new NullPointerException("card cannot be null");
    }

    if (checkout == null) {
        throw new NullPointerException("checkout cannot be null");
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            PaymentSessionCheckoutWrapper dataWrapper = new PaymentSessionCheckoutWrapper();
            PaymentSessionCheckout data = new PaymentSessionCheckout();
            data.setToken(checkout.getToken());
            data.setCreditCard(card);
            data.setBillingAddress(checkout.getBillingAddress());
            dataWrapper.setCheckout(data);

            RequestBody body = RequestBody.create(jsonMediateType, new Gson().toJson(dataWrapper));

            Request request = new Request.Builder().url(checkout.getPaymentUrl()).post(body)
                    .addHeader("Authorization",
                            "Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.NO_WRAP))
                    .addHeader("Content-Type", "application/json").addHeader("Accept", "application/json")
                    .build();
            try {
                com.squareup.okhttp.Response httpResponse = httpClient.newCall(request).execute();
                String paymentSessionId = parsePaymentSessionResponse(httpResponse);
                checkout.setPaymentSessionId(paymentSessionId);

                Response retrofitResponse = new Response(request.urlString(), httpResponse.code(),
                        httpResponse.message(), Collections.<Header>emptyList(), null);
                callback.success(checkout, retrofitResponse);
            } catch (IOException e) {
                e.printStackTrace();

                callback.failure(RetrofitError.unexpectedError(request.urlString(), e));
            }
        }
    }).start();
}

From source file:tv.ouya.sample.IapSampleActivity.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);// ww w. j  a  v a 2s .c o  m
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(product.getIdentifier(),
            Base64.encodeToString(encryptedKey, Base64.NO_WRAP), Base64.encodeToString(ivBytes, Base64.NO_WRAP),
            Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }
    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(product));
}

From source file:de.tavendo.autobahn.WebSocketConnection.java

/**
 * Create new key for WebSockets handshake.
 *
 * @return WebSockets handshake key (Base64 encoded).
 *//*from   w w  w  .  j  a  v  a2 s  .  c  o  m*/
private String newHandshakeKey() {
    final Random mRng = new Random();

    final byte[] ba = new byte[16];
    mRng.nextBytes(ba);
    return Base64.encodeToString(ba, Base64.NO_WRAP);
}

From source file:de.wikilab.android.friendica01.TwAjax.java

private void runFileUpload() throws IOException {

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "d1934afa-f2e4-449b-99be-8be6ebfec594";
    Log.i("Andfrnd/TwAjax", "URL=" + getURL());
    URL url = new URL(getURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);/*from   w  ww  .  j  av  a  2  s.c  o m*/
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        connection.setRequestProperty("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    //Log.i("Andfrnd","-->"+connection.getRequestProperty("Authorization")+"<--");

    connection.setRequestProperty("Host", url.getHost());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    for (NameValuePair nvp : myPostData) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd);
    }
    for (PostFile pf : myPostFiles) {
        pf.writeToStream(outputStream, boundary);
    }
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    myHttpStatus = connection.getResponseCode();

    outputStream.flush();
    outputStream.close();

    if (myHttpStatus < 400) {
        myResult = convertStreamToString(connection.getInputStream());
    } else {
        myResult = convertStreamToString(connection.getErrorStream());
    }

    success = true;
}