Example usage for android.util Base64 decode

List of usage examples for android.util Base64 decode

Introduction

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

Prototype

public static byte[] decode(byte[] input, int flags) 

Source Link

Document

Decode the Base64-encoded data in input and return the data in a new byte array.

Usage

From source file:com.owncloud.android.utils.EncryptionUtils.java

public static byte[] decodeStringToBase64Bytes(String string) {
    return Base64.decode(string, Base64.NO_WRAP);
}

From source file:pl.selvin.android.syncframework.content.TableInfo.java

@SuppressLint("NewApi")
final public void SyncJSON(final HashMap<String, Object> hval, final Metadata meta, final SQLiteDatabase db) {
    int i = 0;/* w w w.  ja  v a 2 s . c  o m*/
    vals.clear();
    for (; i < columns.length; i++) {
        String column = columns[i].name;
        switch (columns[i].type) {
        case ColumnType.BLOB:
            final String str = (String) hval.get(column);
            if (str != null)
                vals.put(column, Base64.decode(str, Base64.DEFAULT));
            break;
        case ColumnType.BOOLEAN:
        case ColumnType.INTEGER:
            vals.put(column, (Long) hval.get(column));
            break;
        case ColumnType.DATETIME:
            String date = (String) hval.get(column);
            if (date != null) {
                date = sdf.format(new Date(Long.parseLong(date.substring(6, date.length() - 2))));
            }
            vals.put(column, date);
            break;
        case ColumnType.NUMERIC:
            Object obj = hval.get(column);
            if (obj instanceof Double)
                vals.put(column, (Double) obj);
            else
                vals.put(column, (Long) obj);
            break;
        default:
            vals.put(column, (String) hval.get(column));
            break;
        }
    }
    vals.put(_.uri, meta.uri);
    vals.put(_.tempId, (String) null);
    vals.put(_.isDirty, 0);
    if (meta.tempId != null) {
        db.update(name, vals, _.tempIdP, new String[] { meta.tempId });
    } else {
        db.replace(name, null, vals);
    }
}

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

/**
 * Set the salt/*from   ww w.j a v a 2s. c  o  m*/
 * @param salt the Base64 encoded salt
 */
public void setSalt(String salt) {

    byte[] tempSalt = Base64.decode(salt, Base64.DEFAULT);

    if (this.saltShortDigest.equals(getSaltShortDigest(tempSalt))) {
        Log.d(TAG, "received salt digest is " + saltShortDigest + " and computed digest from received salt is "
                + getSaltShortDigest(tempSalt));
        this.salt = tempSalt;
        Log.d(TAG, "Saving salt " + salt);
        this.derivateKey(password.toCharArray());
    } else {
        Intent intent = new Intent("probablyWrongDecryptionKeyUsed");
        intent.putExtra("type", "salt");
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        Log.e(TAG, "Salt is false!");
    }

}

From source file:org.cprados.wificellmanager.billing.Security.java

/**
 * Verifies that the signature from the server matches the computed
 * signature on the data.  Returns true if the data is correctly signed.
 *
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature/*from   w  w w .j  a va  2s  .  c o  m*/
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
    if (Consts.DEBUG) {
        Log.i(TAG, "signature: " + signature);
    }
    Signature sig;
    try {
        sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(signedData.getBytes());
        //if (!sig.verify(Base64.decode(signature))) {
        if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
            Log.e(TAG, "Signature verification failed.");
            return false;
        }
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException.");
    } catch (InvalidKeyException e) {
        Log.e(TAG, "Invalid key specification.");
    } catch (SignatureException e) {
        Log.e(TAG, "Signature exception.");
    } // catch (Base64DecoderException e) {
      //    Log.e(TAG, "Base64 decoding failed.");
      //}
    return false;
}

From source file:com.chaosinmotion.securechat.messages.SCMessageQueue.java

/**
 * Internal routine for polling for messages, used if we cannot open
 * a socket for notifications./*from w  ww .j a  v  a  2s  .c o  m*/
 */
private void pollForMessages() {
    if (receiving)
        return;
    receiving = true;

    /*
     *  Poll messages
     */

    JSONObject obj = new JSONObject();
    try {
        obj.put("deviceid", SCRSAManager.shared().getDeviceUUID());
    } catch (JSONException e) {
        // Should never happen
    }
    SCNetwork.get().request("messages/getmessages", obj, false, this, new SCNetwork.ResponseInterface() {
        @Override
        public void responseResult(SCNetwork.Response response) {
            if (response.isSuccess()) {
                JSONArray a = response.getData().optJSONArray("messages");
                int i, len = a.length();
                for (i = 0; i < len; ++i) {
                    JSONObject d = a.optJSONObject(i);

                    int messageID = d.optInt("messageID");
                    int senderID = d.optInt("senderID");
                    String senderName = d.optString("senderName");
                    String received = d.optString("received");
                    Date timestamp = DateUtils.parseServerDate(received);
                    boolean toFlag = d.optBoolean("toflag");
                    byte[] data = Base64.decode(d.optString("message"), Base64.DEFAULT);

                    insertMessage(senderID, senderName, toFlag, messageID, timestamp, data);
                }
            }
            receiving = false;
        }
    });
}

From source file:com.partypoker.poker.engagement.reach.EngagementReachInteractiveContent.java

/**
 * Get notification image for in app notifications. For system notification this field corresponds
 * to the large icon (displayed only on Android 3+).
 * @return notification image.//from   w w w . ja  va2s. c o  m
 */
public Bitmap getNotificationImage() {
    /* Decode as bitmap now if not already done */
    if (mNotificationImageString != null && mNotificationImage == null) {
        /* Decode base 64 then decode as a bitmap */
        byte[] data = Base64.decode(mNotificationImageString, Base64.DEFAULT);
        if (data != null)
            try {
                mNotificationImage = BitmapFactory.decodeByteArray(data, 0, data.length);
            } catch (OutOfMemoryError e) {
                /* Abort */
            }

        /* On any error, don't retry next time */
        if (mNotificationImage == null)
            mNotificationImageString = null;
    }
    return mNotificationImage;
}

From source file:com.ruesga.rview.fragments.SnippetFragment.java

private void readFileContent() {
    if (mDirty) {
        mBinding.editor.readContent(new AceEditorView.OnReadContentReadyListener() {
            @Override//w  w  w. j  a v  a2s.  c om
            public void onReadContentReady(byte[] content, String mimeType) {
                if (content.length > 0) {
                    content = Base64.decode(content, Base64.NO_WRAP);
                }
                saveContent(content);
                if (mimeType != null) {
                    mMimeType = mimeType;
                }
            }

            @Override
            public void onContentUnchanged() {
            }
        }, !mReadOnly);
        mDirty = false;
    }
}

From source file:com.supremainc.biostar2.user.UserInquriyFragment.java

private void setView() {
    if (mLayout == null) {
        return;//from w ww  .  j  a v  a2  s.c  o  m
    }
    mLayout.setUserID(mUserInfo.user_id);
    mLayout.setUserName(mUserInfo.name);
    mLayout.showPin(mUserInfo.pin_exist);

    if (mUserInfo.email == null || mUserInfo.email.equals("")) {
        mLayout.showEmailLink(false, "");
    } else {
        mLayout.showEmailLink(true, mUserInfo.email);
    }

    if (mUserInfo.phone_number == null || mUserInfo.phone_number.equals("")) {
        mLayout.showTelephoneLink(false, "");
    } else {
        mLayout.showTelephoneLink(true, mUserInfo.phone_number);
    }
    setPermission();
    if (mUserInfo.user_group != null) {
        mLayout.setUserGroup(mUserInfo.user_group.name);
        mLayout.setUserGroupID(mUserInfo.user_group.id);
    } else {
        mLayout.setUserGroup(getString(R.string.all_users));
        mLayout.setUserGroupID(String.valueOf(1));
    }
    if (mUserInfo.isActive()) {
        mLayout.setStatus(getString(R.string.active));
    } else {
        mLayout.setStatus(getString(R.string.inactive));
    }
    String sd = mUserInfo.getTimeFormmat(mTimeConvertProvider, User.UserTimeType.start_datetime,
            TimeConvertProvider.DATE_TYPE.FORMAT_DATE);
    String ed = mUserInfo.getTimeFormmat(mTimeConvertProvider, User.UserTimeType.expiry_datetime,
            TimeConvertProvider.DATE_TYPE.FORMAT_DATE);
    String pd = " ~ ";
    if (sd != null) {
        pd = sd + pd;
    }
    if (ed != null) {
        pd = pd + ed;
    }
    mLayout.setPeroid(pd);

    int count = 0;
    if (mUserInfo.access_groups != null) {
        count = mUserInfo.access_groups.size();
    }
    mLayout.setAccessGroup(String.valueOf(count));

    count = 0;
    if (mUserInfo.fingerprint_templates != null) {
        count = mUserInfo.fingerprint_templates.size();
    }
    mLayout.setFingerCount(String.valueOf(count));

    count = 0;
    if (mUserInfo.cards != null) {
        count = mUserInfo.cards.size();
    }
    mLayout.setCardCount(String.valueOf(count));

    if (mUserInfo.photo != null && !mUserInfo.photo.isEmpty()) {
        byte[] photoByte = Base64.decode(mUserInfo.photo, 0);
        final Bitmap bmp = ImageUtil.byteArrayToBitmap(photoByte);

        if (bmp != null) {
            mLayout.setBlurBackGroud(ImageUtil.fastBlur(bmp, 32));
            Bitmap rBmp = ImageUtil.getRoundedBitmap(bmp, true);
            mLayout.setUserPhoto(rBmp);
        }
    } else {
        mLayout.setUserPhotoDefault();
        mLayout.setBlurBackGroudDefault();
    }
}

From source file:de.appplant.cordova.plugin.emailcomposer.EmailComposer.java

/**
 * The URI for a base64 encoded content.
 *
 * @param {String} content/*from ww w .  j a  v a 2  s. c  o m*/
 *      The given base64 encoded content
 *
 * @return The URI including the given content
 */
private Uri getUriForBase64Content(String content) {
    String resName = content.substring(content.indexOf(":") + 1, content.indexOf("//"));
    String resData = content.substring(content.indexOf("//") + 2);
    byte[] bytes = Base64.decode(resData, 0);
    String storage = this.cordova.getActivity().getCacheDir() + STORAGE_FOLDER;
    File file = new File(storage, resName);

    new File(storage).mkdir();

    try {
        FileOutputStream outStream = new FileOutputStream(file);

        outStream.write(bytes);
        outStream.flush();
        outStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    String pkgName = getPackageName();
    String uriPath = pkgName + AttachmentProvider.AUTHORITY + "/" + resName;

    return Uri.parse("content://" + uriPath);
}

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");
    }//  w ww  .  jav a  2 s .c  om
    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");
}