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:autobahn.WebSocketWriter.java

/**
 * Create new key for WebSockets handshake.
 *
 * @return WebSockets handshake key (Base64 encoded).
 *///  w  w w .ja v  a  2s.  c o  m
private String newHandshakeKey() {
    final byte[] ba = new byte[16];
    mRng.nextBytes(ba);
    return Base64.encodeToString(ba, Base64.NO_WRAP);
}

From source file:eu.codeplumbers.cosi.services.CosiContactService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiContactService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    allContacts = new ArrayList<>();

    Device device = Device.registeredDevice();

    // cozy register device url
    designUrl = device.getUrl() + "/ds-api/request/contact/all/";
    syncUrl = 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);

    showNotification();//w  w w.j  av a2s  .c  o m

    if (isNetworkAvailable()) {
        try {
            // read local sms log first
            readContactDatabase();
            EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Getting remote contacts from Cozy..."));
            getRemoteContacts();

            mBuilder.setContentText(getString(R.string.lbl_contacts_sync_done));
            mBuilder.setProgress(0, 0, false);
            mNotifyManager.notify(notification_id, mBuilder.build());

            mNotifyManager.cancel(notification_id);

            sendChangesToCozy();

            mNotifyManager.cancel(notification_id);

            EventBus.getDefault().post(new ContactSyncEvent(REFRESH, "Sync OK"));
        } catch (Exception e) {
            e.printStackTrace();
            mSyncRunning = false;
            EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:com.nextgis.maplib.map.NGWVectorLayer.java

public String download() {
    if (!mNet.isNetworkAvailable()) { //return tile from cache
        return mContext.getString(R.string.error_network_unavailable);
    }//from  ww w  . j av  a 2  s  .co  m

    try {

        final HttpGet get = new HttpGet(mURL);
        //basic auth
        if (null != mLogin && mLogin.length() > 0 && null != mPassword && mPassword.length() > 0) {
            get.setHeader("Accept", "*/*");
            final String basicAuth = "Basic "
                    + Base64.encodeToString((mLogin + ":" + mPassword).getBytes(), Base64.NO_WRAP);
            get.setHeader("Authorization", basicAuth);
        }

        final DefaultHttpClient HTTPClient = mNet.getHttpClient();
        final HttpResponse response = HTTPClient.execute(get);

        // Check to see if we got success
        final org.apache.http.StatusLine line = response.getStatusLine();
        if (line.getStatusCode() != 200) {
            Log.d(TAG, "Problem downloading GeoJSON: " + mURL + " HTTP response: " + line);
            return mContext.getString(R.string.error_download_data);
        }

        final HttpEntity entity = response.getEntity();
        if (entity == null) {
            Log.d(TAG, "No content downloading GeoJSON: " + mURL);
            return mContext.getString(R.string.error_download_data);
        }

        String data = EntityUtils.toString(entity);
        JSONObject geoJSONObject = new JSONObject(data);

        return createFromGeoJSON(geoJSONObject);

    } catch (IOException e) {
        Log.d(TAG, "Problem downloading GeoJSON: " + mURL + " Error: " + e.getLocalizedMessage());
        return mContext.getString(R.string.error_download_data);
    } catch (JSONException e) {
        e.printStackTrace();
        return mContext.getString(R.string.error_download_data);
    }
}

From source file:org.disrupted.rumble.network.protocols.firechat.FirechatMessageParser.java

public ChatMessage networkToChatMessage(JSONObject message) throws JSONException {
    ChatMessage retMessage = null;//from   ww w .ja v  a 2s.c om

    String post = "";
    long length = 0;

    String firechatid = message.getString(UUID);
    String author = message.getString(NAME);
    String firechat = message.getString(FIRECHAT);
    String author_id = message.getString(RUMBLEID);
    String timeScientificNotation = message.getString(TIMESTAMP);
    long timestamp = Double.valueOf(timeScientificNotation).longValue();

    try {
        post = message.getString(MESSAGE);
    } catch (JSONException ignore) {
        post = "";
    }
    try {
        length = message.getLong(LENGTH);
    } catch (JSONException ignore) {
        length = 0;
    }

    if (author_id.equals(""))
        author_id = HashUtil.computeContactUid(author + "FireChat", 0);

    Contact contact = new Contact(author, author_id, false);
    long receivedAt = System.currentTimeMillis();
    retMessage = new ChatMessage(contact, post, timestamp, receivedAt, FirechatProtocol.protocolID);

    // we store the message in Base64 because it is more readable
    if (HashUtil.isBase64Encoded(firechatid))
        retMessage.setUUID(firechatid);
    else
        retMessage.setUUID(Base64.encodeToString(firechatid.getBytes(), Base64.NO_WRAP));
    retMessage.setFileSize(length);

    return retMessage;
}

From source file:net.sourcewalker.garanbot.api.GaranboClient.java

private String getAuthHeader() {
    byte[] input = String.format("%s:%s", username, password).getBytes();
    return "Basic " + Base64.encodeToString(input, Base64.NO_WRAP);
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Encrypts a message.//from   www  . java 2  s  .  c om
 * @param args Arguments: data, publicKey[, privateKey]
 * @param callback Callback
 */
public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        PRNGProvider.init(); // Ensure OpenSSL fix

        // Get the arguments
        String data = args.getString(0);
        String pub = args.getString(1);
        String priv = null;
        if (args.length() == 3) {
            priv = args.getString(2);
        }
        String sig = null;

        // Convert everything into byte arrays
        byte[] dataRaw = data.getBytes("utf-8");
        byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);

        // Generate random AES key and IV
        byte[] aesKey = new byte[AES_BYTES];
        new SecureRandom().nextBytes(aesKey);
        byte[] aesIv = new byte[16]; // Block size
        new SecureRandom().nextBytes(aesIv);
        Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));

        // Encrypt data with AES
        byte[] encData = c.doFinal(dataRaw);

        // Encrypt aes data with RSA
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec));
        c.update(aesKey);
        c.update(aesIv);
        byte[] encKey = c.doFinal();

        // Concatenate and transform
        byte[] encRaw = new byte[encKey.length + encData.length];
        System.arraycopy(encKey, 0, encRaw, 0, encKey.length);
        System.arraycopy(encData, 0, encRaw, encKey.length, encData.length);
        encKey = null;
        encData = null;
        String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8");

        // Sign
        if (priv != null) {
            // Fail on error (no try-catch)
            byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT);
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw);
            Signature s = Signature.getInstance("SHA1withRSA", "BC");
            s.initSign(kf.generatePrivate(privateKeySpec));
            s.update(encRaw);
            sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8");
        }

        JSONArray res = new JSONArray();
        res.put(enc);
        res.put(sig);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:roommateapp.info.net.FileDownloader.java

/**
 * Parallel execution//from  w  w w  .  j  a  va 2 s . c  o  m
 */
@SuppressLint("UseValueOf")
@Override
protected Object doInBackground(Object... params) {

    if (!this.isHolidayFile) {

        /* Progressbar einblenden */
        this.ac.runOnUiThread(new Runnable() {
            public void run() {
                toggleProgressbar();
            }
        });
    }

    boolean success = true;
    String eingabe = (String) params[0];

    if (eingabe != null) {

        try {
            URL url = new URL(eingabe);

            // Get filename
            String fileName = eingabe;
            StringTokenizer tokenizer = new StringTokenizer(fileName, "/", false);
            int tokens = tokenizer.countTokens();
            for (int i = 0; i < tokens; i++) {
                fileName = tokenizer.nextToken();
            }

            // Create file
            this.downloadedFile = new File(this.roommateDirectory, fileName);

            // Download and write file
            try {
                // Password and username if it's HTACCESS
                String authData = new String(Base64.encode((username + ":" + pw).getBytes(), Base64.NO_WRAP));

                URLConnection urlcon = url.openConnection();

                // Authorisation if it's a userfile
                if (eingabe.startsWith(RoommateConfig.URL)) {
                    urlcon.setRequestProperty("Authorization", "Basic " + authData);
                    urlcon.setDoInput(true);
                }
                InputStream inputstream = urlcon.getInputStream();
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                int current = 0;

                while ((current = inputstream.read()) != -1) {
                    baf.append((byte) current);
                }

                FileOutputStream fos = new FileOutputStream(this.downloadedFile);
                fos.write(baf.toByteArray());
                fos.close();

            } catch (IOException e) {
                success = false;
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            success = false;
            e.printStackTrace();
        }
    } else {
        success = false;
    }
    return new Boolean(success);
}

From source file:org.ttrssreader.net.JavaJSONConnector.java

@Override
public void init() {
    super.init();
    if (!httpAuth)
        return;/*  ww w  .  j  av a2 s. c  o  m*/

    try {
        base64NameAndPw = Base64.encodeToString((httpUsername + ":" + httpPassword).getBytes("UTF-8"),
                Base64.NO_WRAP);
    } catch (UnsupportedEncodingException e) {
        base64NameAndPw = null;
    }
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(httpUsername, httpPassword.toCharArray());
        }
    });
}

From source file:pro.jariz.reisplanner.api.NSTask.java

protected String doReq(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;// ww  w .  j av a  2  s .co m
    String responseString = null;
    try {
        HttpGet get = new HttpGet(uri[0]);
        get.setHeader("Authorization",
                "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
        response = httpclient.execute(get);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        NSTask.LastExceptionMessage = e.getMessage();
        NSAPI.Error(e);
        return null;
    } catch (IOException e) {
        NSTask.LastExceptionMessage = e.getMessage();
        NSAPI.Error(e);
        return null;
    }
    return responseString;
}

From source file:org.kde.kdeconnect.Helpers.SecurityHelpers.RsaHelper.java

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

    JSONArray chunks = np.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  www .j  ava2 s.c o m

    NetworkPackage decrypted = NetworkPackage.unserialize(decryptedJson);
    decrypted.setPayload(np.getPayload(), np.getPayloadSize());
    return decrypted;
}