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:com.jrummyapps.android.safetynet.SafetyNetHelper.java

@Nullable
private String getApkDigestSha256() {
    try {/*from w w w .j  a  v a  2  s .co m*/
        FileInputStream fis = new FileInputStream(context.getPackageCodePath());
        MessageDigest md = MessageDigest.getInstance(SHA_256);
        try {
            DigestInputStream dis = new DigestInputStream(fis, md);
            byte[] buffer = new byte[2048];
            while (dis.read(buffer) != -1) {
                //
            }
            dis.close();
        } finally {
            fis.close();
        }
        return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
    } catch (IOException | NoSuchAlgorithmException e) {
        return null;
    }
}

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void iterateAsBase64(final CallbackContext callbackContext, JSONArray args) {
    try {/*from  w w  w.j a v a2 s.  c  o  m*/
        String namespace = args.getString(0);
        Enumerator it1 = new Enumerator() {
            public int next() {
                JSONObject obj = new JSONObject();
                try {
                    obj.put(KEY, key);
                    String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
                    obj.put(DATA, base64);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                PluginResult r = new PluginResult(PluginResult.Status.OK, obj);
                r.setKeepCallback(true);
                callbackContext.sendPluginResult(r);
                return Enumerator.Code.NONE;
            }
        };
        mWinch.getNamespace(namespace).enumerate(it1);
    } catch (JSONException e1) {
        e1.printStackTrace();
    } catch (WinchError e) {
        e.log();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        callbackContext.sendPluginResult(r);
    }

    PluginResult r = new PluginResult(PluginResult.Status.OK, false);
    r.setKeepCallback(false);
    callbackContext.sendPluginResult(r);
}

From source file:org.thoughtland.xlocation.Util.java

private static PublicKey getPublicKey(Context context) throws Throwable {
    // Read public key
    String sPublicKey = "";
    InputStreamReader isr = new InputStreamReader(context.getAssets().open("XLocation_public_key.txt"),
            "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();/*from w  w  w.ja  v a  2 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:com.ledger.android.u2f.bridge.MainActivity.java

private String createU2FResponseRegister(U2FContext context, byte[] registerResponse) {
    try {//from   www  .  jav a  2  s .  com
        JSONObject response = new JSONObject();
        response.put(TAG_JSON_TYPE, REGISTER_RESPONSE_TYPE);
        response.put(TAG_JSON_REQUESTID, context.getRequestId());
        JSONObject responseData = new JSONObject();
        responseData.put(TAG_JSON_REGISTRATIONDATA, Base64.encodeToString(registerResponse, 0,
                registerResponse.length - 2, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING));
        responseData.put(TAG_JSON_VERSION, VERSION_U2F_V2);
        String clientData = createClientData(context);
        responseData.put(TAG_JSON_CLIENTDATA, Base64.encodeToString(clientData.getBytes("UTF-8"),
                Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING));
        response.put(TAG_JSON_RESPONSEDATA, responseData);
        return response.toString();
    } catch (Exception e) {
        Log.e(TAG, "Error encoding request");
        return null;
    }
}

From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java

@SuppressLint("PackageManagerGetSignatures")
private List<String> getApkCertificateDigests() {
    List<String> apkCertificateDigests = new ArrayList<>();
    PackageManager pm = context.getPackageManager();
    PackageInfo packageInfo;//from  ww  w .  j a v  a2  s.  c o  m
    try {
        packageInfo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException wtf) {
        return apkCertificateDigests;
    }
    Signature[] signatures = packageInfo.signatures;
    for (Signature signature : signatures) {
        try {
            MessageDigest md = MessageDigest.getInstance(SHA_256);
            md.update(signature.toByteArray());
            byte[] digest = md.digest();
            apkCertificateDigests.add(Base64.encodeToString(digest, Base64.NO_WRAP));
        } catch (NoSuchAlgorithmException ignored) {
        }
    }
    return apkCertificateDigests;
}

From source file:com.badlogic.gdx.pay.android.ouya.PurchaseManagerAndroidOUYA.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   ww w  .  ja  v  a2s.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, ouyaPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

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

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

From source file:com.google.ipc.invalidation.ticl.android.AndroidChannel.java

/** Returns the web encoded version of the channel network endpoint ID for HTTP requests. */
@Override//  w  ww  . jav a 2  s .c o  m
protected String getWebEncodedEndpointId() {
    NetworkEndpointId networkEndpointId = getNetworkId();
    return Base64.encodeToString(networkEndpointId.toByteArray(),
            Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
}

From source file:com.dh.perfectoffer.event.framework.net.network.NetworkConnectionImpl.java

private static String createAuthenticationHeader(UsernamePasswordCredentials credentials) {
    StringBuilder sb = new StringBuilder();
    sb.append(credentials.getUserName()).append(":").append(credentials.getPassword());
    return "Basic " + Base64.encodeToString(sb.toString().getBytes(), Base64.NO_WRAP);
}

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

private void runDefault() throws IOException {
    Log.v("TwAjax", "runDefault URL=" + myUrl);

    // Create a new HttpClient and Get/Post Header
    DefaultHttpClient httpclient = getNewHttpClient();
    setHttpClientProxy(httpclient);//ww  w .j  a v a2  s  .c o m
    httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    //final HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(httpclient.getParams(), false);

    HttpRequestBase m;
    if (myMethod == "POST") {
        m = new HttpPost(myUrl);
        ((HttpPost) m).setEntity(new UrlEncodedFormEntity(myPostData, "utf-8"));
    } else {
        m = new HttpGet(myUrl);
    }
    m.addHeader("Host", m.getURI().getHost());
    if (twSession != null)
        m.addHeader("Cookie", "twnetSID=" + twSession);
    httpclient.setCookieStore(cookieStoreManager);

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        m.addHeader("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    // Execute HTTP Get/Post Request
    HttpResponse response = httpclient.execute(m);
    //InputStream is = response.getEntity().getContent();
    myHttpStatus = response.getStatusLine().getStatusCode();
    if (this.fetchHeader != null) {
        this.fetchHeaderResult = response.getHeaders(this.fetchHeader);
        Header[] h = response.getAllHeaders();
        for (Header hh : h)
            Log.d(TAG, "Header " + hh.getName() + "=" + hh.getValue());

    } else if (this.downloadToFile != null) {
        Log.v("TwAjax", "runDefault downloadToFile=" + downloadToFile);
        // download the file
        InputStream input = new BufferedInputStream(response.getEntity().getContent());
        OutputStream output = new FileOutputStream(downloadToFile);

        byte data[] = new byte[1024];

        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            //publishProgress((int)(total*100/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } else if (this.convertToBitmap) {
        myBmpResult = BitmapFactory.decodeStream(response.getEntity().getContent());
    } else if (this.convertToXml) {
        try {
            myXmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(response.getEntity().getContent());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }

    } else {
        myResult = EntityUtils.toString(response.getEntity(), "UTF-8");
    }
    //BufferedInputStream bis = new BufferedInputStream(is);
    //ByteArrayBuffer baf = new ByteArrayBuffer(50);

    //int current = 0;
    //while((current = bis.read()) != -1){
    //    baf.append((byte)current);
    //}

    //myResult = new String(baf.toByteArray(), "utf-8");
    success = true;
}

From source file:com.charabia.SmsViewActivity.java

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
    case SMS_KEY_CONTACT:
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();//from w  ww  .ja  v  a  2s. com

            ContentResolver cr = getContentResolver();

            Cursor cursor = cr.query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null);

            String lookup = null;

            if (cursor.moveToFirst()) {
                lookup = cursor.getString(0);
            }

            cursor.close();

            if (lookup == null) {
                Toast.makeText(this, R.string.unexpected_error, Toast.LENGTH_LONG).show();
                return;
            }

            cursor = cr.query(Data.CONTENT_URI, new String[] { Phone.NUMBER },
                    Data.MIMETYPE + "=? AND " + Data.LOOKUP_KEY + "=?",
                    new String[] { Phone.CONTENT_ITEM_TYPE, lookup }, null);

            ArrayList<String> options = new ArrayList<String>();

            while (cursor.moveToNext()) {
                options.add(cursor.getString(0));
            }

            cursor.close();

            final String[] phoneList = options.toArray(new String[0]);

            Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.send_invit_on_phone);
            builder.setItems(phoneList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {

                    keypair = tools.loadKeyPair();
                    RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic();

                    byte[] encoded = pubKey.getModulus().toByteArray();

                    byte[] data = new byte[3 + encoded.length];

                    data[0] = Tools.MAGIC[0];
                    data[1] = Tools.MAGIC[1];
                    data[2] = Tools.PUBLIC_KEY_TYPE;

                    System.arraycopy(encoded, 0, data, 3, encoded.length);

                    tools.sendData(phoneList[i], Tools.INVITATION, "", data);

                }
            });

            builder.create().show();
        } else {
            Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
        }
        break;
    case IntentIntegrator.REQUEST_CODE:
        if (resultCode == RESULT_OK) {
            try {
                String contents = data.getStringExtra("SCAN_RESULT");
                @SuppressWarnings("unused")
                String format = data.getStringExtra("SCAN_RESULT_FORMAT");
                // Handle successful scan

                // TODO: add more tests control

                String[] infos = contents.split("\n");

                Cipher rsaCipher = Cipher.getInstance(Tools.RSA_CIPHER_ALGO);

                if (mode == MODE_ESCLAVE) {
                    // Save key and show crypted key on QRCode
                    key = tools.generateKeyAES().getEncoded();

                    KeyFactory keyFact = KeyFactory.getInstance("RSA");

                    PublicKey pubkey = keyFact.generatePublic(
                            new RSAPublicKeySpec(new BigInteger(infos[1]), new BigInteger(infos[2])));

                    rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey);

                    int blockSize = rsaCipher.getBlockSize();

                    int nbBlock = key.length / blockSize;
                    int reste = key.length % blockSize;

                    byte[] cryptedKey = new byte[(nbBlock + 1) * rsaCipher.getOutputSize(blockSize)];

                    int offset = 0;

                    for (int i = 0; i < nbBlock; i++) {
                        offset += rsaCipher.doFinal(key, i * blockSize, blockSize, cryptedKey, offset);
                    }

                    rsaCipher.doFinal(key, nbBlock * blockSize, reste, cryptedKey, offset);

                    IntentIntegrator.shareText(SmsViewActivity.this,
                            prefPhoneNumber + "\n" + Base64.encodeToString(cryptedKey, Base64.NO_WRAP));

                } else {

                    // We have read crypted key, so decode it
                    rsaCipher.init(Cipher.DECRYPT_MODE, keypair.getPrivate());

                    byte[] cryptedData = Base64.decode(infos[1], Base64.NO_WRAP);

                    int blockSize = rsaCipher.getBlockSize();
                    int nbBlock = cryptedData.length / blockSize;

                    int offset = 0;

                    byte[] tempKey = new byte[(nbBlock + 1) * blockSize];

                    for (int i = 0; i < nbBlock; i++) {
                        offset += rsaCipher.doFinal(cryptedData, i * blockSize, blockSize, tempKey, offset);
                    }

                    key = new byte[offset];
                    System.arraycopy(tempKey, 0, key, 0, offset);
                }

                phoneNumber = infos[0];

                // store the key
                // TODO dialog to confirm add contact in mode SLAVE
                try {
                    new Tools(this).updateOrCreateContactKey(phoneNumber, key);
                } catch (NoContactException e) {
                    e.printStackTrace();
                    // propose to add contact
                    Intent newIntent = new Intent(Intents.SHOW_OR_CREATE_CONTACT);
                    newIntent.setData(Uri.fromParts("tel", phoneNumber, null));
                    startActivityForResult(newIntent, ADD_CONTACT);
                    return;
                }

                Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG)
                        .show();

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
            }

        } else {
            // TODO: string
            Toast.makeText(this, R.string.fail_reading_tag, Toast.LENGTH_LONG).show();
        }
        break;
    case ADD_CONTACT:
        try {
            tools.updateOrCreateContactKey(phoneNumber, key);
            Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG)
                    .show();
        } catch (NoContactException e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
        }
        break;
    }

}