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:de.tum.frm2.nicos_android.nicos.NicosClient.java

public void connect(ConnectionData connData, Object[] eventmask) throws RuntimeException {
    if (connected) {
        throw new RuntimeException("client already connected");
    }//from www  .  j  ava  2  s .  co  m
    disconnecting = false;

    SocketAddress sockaddr;
    try {
        // If ANY code of this scope failes, communication is entirely impossible.
        // That means, no need to catch all exceptions one by one.
        InetAddress addr = InetAddress.getByName(connData.getHost());
        sockaddr = new InetSocketAddress(addr, connData.getPort());

        // Initialize empty socket.
        socket = new Socket();

        // Connects this socket to the server with a specified timeout value
        // If timeout occurs, SocketTimeoutException is thrown
        socket.connect(sockaddr, TIMEOUT);
        socketOut = socket.getOutputStream();
        socketIn = socket.getInputStream();

        // Write client identification: we are a new client
        socketOut.write(client_id);
    } catch (Exception e) {
        String msg;
        if (e instanceof IOException) {
            // "null reference" error messages won't help the user.
            msg = "Socket communication failed (server not responding).";
        } else {
            msg = "Server connection failed: " + e.getMessage() + ".";
        }
        signal("failed", msg);
        return;
    }

    // read banner
    try {
        TupleOfTwo<Byte, Object> response = _read();
        byte ret = response.getFirst();
        if (ret != daemon.STX) {
            throw new ProtocolError("invalid response format");
        }
        nicosBanner = (HashMap) response.getSecond();
        if (!nicosBanner.containsKey("daemon_version")) {
            throw new ProtocolError("daemon version missing from response");
        }
        int daemon_proto = (int) nicosBanner.get("protocol_version");
        if (!daemon.isProtoVersionCompatible(daemon_proto)) {
            throw new ProtocolError("daemon uses protocol " + String.valueOf(daemon_proto)
                    + ", but this client requires protocol " + String.valueOf(daemon.PROTO_VERSIONS[0]));
        }
    } catch (Exception e) {
        signal("failed", "Server(" + connData.getHost() + ":" + String.valueOf(connData.getPort())
                + ") handshake failed: " + e.getMessage());
        return;
    }

    // log-in sequence
    char[] password = connData.getPassword();
    Object unwrap = nicosBanner.get("pw_hashing");
    String pw_hashing = "sha1";
    if (unwrap != null) {
        pw_hashing = unwrap.toString();
    }

    String encryptedPassword = null;
    boolean supportsRSA = false;
    try {
        String rsaSupportString = pw_hashing.substring(0, 4);
        supportsRSA = rsaSupportString.equals("rsa,");
    } catch (StringIndexOutOfBoundsException e) {
        // Does not start with "rsa," -> does not support RSA encryption.
        // boolean supportsRSA stays at false.
    }
    if (supportsRSA) {
        byte[] keyBytes = Base64.decode(nicosBanner.get("rsakey").toString(), Base64.DEFAULT);
        String publicKeyString = new String(keyBytes, StandardCharsets.UTF_8);
        PublicKey publicKey = extractPublicKey(publicKeyString);

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
            // Cannot happen.
        }
        try {
            if (cipher != null) {
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            } else {
                throw new InvalidKeyException();
            }
        } catch (InvalidKeyException e) {
            throw new RuntimeException("The server's RSA key is invalid or incompatible.");
        }

        byte[] encrypted;
        try {
            encrypted = cipher.doFinal(String.valueOf(password).getBytes());
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
            encrypted = new byte[0];
        }
        encryptedPassword = "RSA:" + Base64.encodeToString(encrypted, Base64.DEFAULT);
    }

    if (pw_hashing.equals("sha1")) {
        encryptedPassword = new String(Hex.encodeHex(DigestUtils.sha1(String.valueOf(password))));
    }

    else if (pw_hashing.equals("md5")) {
        encryptedPassword = new String(Hex.encodeHex(DigestUtils.md5(String.valueOf(password))));
    }

    HashMap<String, String> credentials = new HashMap<>();
    credentials.put("login", connData.getUser());
    credentials.put("passwd", encryptedPassword);
    credentials.put("display", "");

    // Server requires credentials to be wrapped in a tuple with 1 item
    // e.g. python: payload = (credentials,)
    // Pyrolite library matches java.lang.Object arrays to tuples with the array's length.
    Object[] data = { credentials };
    Object untypedAuthResponse = ask("authenticate", data);
    if (untypedAuthResponse == null) {
        return;
    }

    // Login was successful.
    HashMap authResponse = (HashMap) untypedAuthResponse;
    user_level = (int) authResponse.get("user_level");

    if (eventmask != null) {
        tell("eventmask", eventmask);
    }

    // connect to event port
    eventSocket = new Socket();
    try {
        eventSocket.connect(sockaddr);
        OutputStream eventSocketOut = eventSocket.getOutputStream();
        eventSocketIn = eventSocket.getInputStream();
        eventSocketOut.write(client_id);
    } catch (IOException e) {
        signal("failed", "Event connection failed: " + e.getMessage() + ".", e);
        return;
    }

    // Start event handler
    final Thread event_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            // equals event_handler.
            event_handler();
        }
    });
    event_thread.start();

    connected = true;
    viewonly = connData.getViewonly();
    signal("connected");
}

From source file:com.letsgood.sampleapp.SignInActivity.java

private void printFacebookKeyHash() {
    // Add code to print out the key hash
    try {//from  ww w.j  av  a 2 s.c  o m
        PackageInfo info = getPackageManager().getPackageInfo("com.letsgood.sampleapp",
                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) {

    }
}

From source file:android.webkit.cts.TestWebServer.java

/**
 * Sets a base64 encoded response to be returned when a particular request path is passed
 * in (with the option to specify additional headers).
 *
 * @param requestPath The path to respond to.
 * @param base64EncodedResponse The response body that is base64 encoded. The actual server
 *                              response will the decoded binary form.
 * @param responseHeaders Any additional headers that should be returned along with the
 *                        response (null is acceptable).
 * @return The full URL including the path that should be requested to get the expected
 *         response.//w w  w. java 2 s  . co  m
 */
public String setResponseBase64(String requestPath, String base64EncodedResponse,
        List<Pair<String, String>> responseHeaders) {
    return setResponseInternal(requestPath, Base64.decode(base64EncodedResponse, Base64.DEFAULT),
            responseHeaders, null, RESPONSE_STATUS_NORMAL);
}

From source file:br.com.vpsa.oauth2android.token.MacTokenTypeDefinition.java

private String calculateBodyHash(String body, String algorithm) throws InvalidTokenTypeException {
    try {/*from ww w . j a va 2s.  c o  m*/
        MessageDigest md = MessageDigest.getInstance(algorithm);
        String bodyhash = Base64.encodeToString(md.digest(body.getBytes()), Base64.DEFAULT);
        return bodyhash;
    } catch (NoSuchAlgorithmException ex) {
        throw new InvalidTokenTypeException(
                "This token contains no or an invalid algorithm to calculate the bodyhash");
    }
}

From source file:com.ritul.truckshare.RegisterActivity.DriverLicenseActivity.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Utility.GALLERY_PICTURE && data != null) {
        isImage = true;/*from w w  w .j  av  a  2  s .  c om*/
        // data contains result
        // Do some task
        Image_Selecting_Task(data);
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = DriverLicenseActivity.this.getContentResolver().query(selectedImage, filePathColumn,
                null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        selectedpath = cursor.getString(columnIndex);
        cursor.close();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8;
        final Bitmap bitmap = BitmapFactory.decodeFile(selectedpath, options);
        convertimagetobyte();
        imagedata = Base64.encodeToString(imageByte, Base64.DEFAULT);
    } else if (requestCode == Utility.CAMERA_PICTURE && data != null) {
        isImage = true;
        // Do some task
        //Image_Selecting_Task(data);
        if (requestCode == Utility.CAMERA_PICTURE && resultCode == RESULT_OK && data != null) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            preview.setImageBitmap(photo);

            Bitmap bitmap = ((BitmapDrawable) preview.getDrawable()).getBitmap();
            imagedata = Base64.encodeToString(getBytesFromBitmap(bitmap), Base64.DEFAULT);

        }
    }
}

From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java

/**
 * Compute a truncated digest on the salt
 * We only take the three first letters (not chars!) of the Base64 encoded digest, because
 * this truncated digest must be transmitted with the group password (only letters)
 * @param salt the salt from on we want to compute the digest 
 * @return the three first letters of the Base64 encoded digest
 *///  ww w.j  a  va  2s  .c om
public String getSaltShortDigest(byte[] salt) {
    if (salt == null)
        return "";

    //Compute the digest
    MessageDigest md;
    String saltHash;
    Log.d(TAG, "Computing salt digest");
    try {
        md = MessageDigest.getInstance("SHA-1");
        md.update(salt, 0, salt.length);
        saltHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Digest of salt could not be computed");
        e.printStackTrace();
        return null;
    }

    //Truncate the digest
    String shortDigest = "";
    int i = 0;
    while (shortDigest.length() < 3) {
        char c = saltHash.charAt(i);
        if (Character.isLetter(c)) {
            shortDigest = shortDigest.concat(String.valueOf(Character.toLowerCase(c)));
        }
        i++;
        if (i >= saltHash.length()) {
            break;
        }
    }
    Log.d(TAG, "Short digest is " + shortDigest);

    return shortDigest;
}

From source file:com.mobiperf.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */
@Override/*from  w w w  .  j  a  v  a 2  s .  co  m*/
public MeasurementResult call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    boolean success = false;
    String errorMsg = "";
    InputStream inputStream = null;

    // This is not the ideal way of doing things, as we can pick up data
    // from other processes and be overly cautious in running measurements.
    // However, taking the packet sizes is completely inaccurate, and it's hard to
    // come up with a consistent expected value, unlike with DNS
    RRCTask.PacketMonitor packetmonitor = new RRCTask.PacketMonitor();
    packetmonitor.setBySize();
    packetmonitor.readCurrentPacketValues();

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
        }

        /* For HttpClient to work properly, we still want to consume the entire response even if
         * the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
                this.progress = (int) (100 * totalBodyLen / expectedResponseLen);
                this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
                broadcastProgressForUser(this.progress);
            }
            duration = System.currentTimeMillis() - startTime;
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success,
                this.measurementDesc);

        result.addResult("code", statusCode);

        dataConsumed = packetmonitor.getPacketsSentDiff();

        if (success) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        return result;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:app.sunstreak.yourpisd.LoginActivity.java

/**
 * Attempts to sign in or register the account specified by the login form.
 * If there are form errors (invalid email, missing fields, etc.), the
 * errors are presented and no actual login attempt is made.
 *///w w  w  .  j  av a  2  s.c  o  m
public void attemptLogin() {
    if (mAuthTask != null) {
        return;
    }

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    mEmail = mEmailView.getText().toString();
    encryptedPass = Base64.encodeToString(mPasswordView.getText().toString().getBytes(), Base64.DEFAULT);
    mPassword = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password.
    if (TextUtils.isEmpty(mPassword)) {
        mPasswordView.setError(getString(R.string.error_field_required));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid username.
    if (TextUtils.isEmpty(mEmail)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt login and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        SharedPreferences sharedPrefs = this.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.putString("email", mEmail);
        editor.putString("e_password", mRememberPassword ? encryptedPass : "");
        editor.putBoolean("remember_password", mRememberPassword);
        editor.putBoolean("auto_login", mAutoLogin);
        editor.commit();

        // Modified from default.

        showProgress(true);
        mAuthTask = new UserLoginTask();
        mAuthTask.execute((Void) null);
    }
}

From source file:jog.my.memory.gcm.ServerUtilities.java

/**
 * Convert images to the string representation
 * @param pics - pictures to send/*  w w  w.j a v a2 s . c o m*/
 * @return arraylist of string representation of pictures
 */
public static byte[] convertPhotosToByteRepresentation(ArrayList<Picture> pics) {
    ArrayList<byte[]> listPhotos = new ArrayList<>();
    for (int i = 0; i < pics.size(); i++) {
        String stringEncodedImage = Base64.encodeToString(pics.get(i).getmImageAsByteArray(), Base64.DEFAULT);
        listPhotos.add(pics.get(i).getmImageAsByteArray());
    }
    return listPhotos.get(0);
}

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Convert results cursor to JSON string.
 *
 * @param cur/*w w  w . j  ava2s.  c  om*/
 *            Cursor into query results
 *
 * @return results in string form
 *
 */
@SuppressLint("NewApi")
private String results2string(Cursor cur) {
    String result = "[]";

    // If query result has rows
    if (cur.moveToFirst()) {
        JSONArray fullresult = new JSONArray();
        String key = "";
        int colCount = cur.getColumnCount();

        // Build up JSON result object for each row
        do {
            JSONObject row = new JSONObject();
            try {
                for (int i = 0; i < colCount; ++i) {
                    key = cur.getColumnName(i);

                    // for old Android SDK remove lines from HERE:
                    if (android.os.Build.VERSION.SDK_INT >= 11) {
                        switch (cur.getType(i)) {
                        case Cursor.FIELD_TYPE_NULL:
                            row.put(key, null);
                            break;
                        case Cursor.FIELD_TYPE_INTEGER:
                            row.put(key, cur.getInt(i));
                            break;
                        case Cursor.FIELD_TYPE_FLOAT:
                            row.put(key, cur.getFloat(i));
                            break;
                        case Cursor.FIELD_TYPE_STRING:
                            row.put(key, cur.getString(i));
                            break;
                        case Cursor.FIELD_TYPE_BLOB:
                            row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT)));
                            break;
                        }
                    } else // to HERE.
                    {
                        row.put(key, cur.getString(i));
                    }
                }

                fullresult.put(row);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } while (cur.moveToNext());

        result = fullresult.toString();
    }

    return result;
}