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.orange.ocara.model.loader.RuleSetJsonParser.java

private void storeResource(String resourceId, String resourceData, File resourcesPath) throws IOException {
    String base64Pattern = "base64,";
    int indexOfBase64Data = resourceData.lastIndexOf(base64Pattern);
    if (indexOfBase64Data < 0) {
        throw new JsonBadStructureException(resourceId);
    }//from   w  ww .  j  a  v  a  2 s  .com
    String base64String = resourceData.substring(indexOfBase64Data + base64Pattern.length());
    byte[] decodedData = Base64.decode(base64String, Base64.DEFAULT);

    File file = new File(resourcesPath, resourceId);

    FileOutputStream ouputStream = new FileOutputStream(file);
    ouputStream.write(decodedData);
    ouputStream.close();
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.AuthorizationProcessManager.java

/**
 * Extract token from response and save it locally
 * @param response response that contain the token
 *//*w  w w.j av a 2s . c  o m*/
private void saveTokenFromResponse(Response response) {
    try {
        JSONObject responseJSON = ((ResponseImpl) response).getResponseJSON();

        String accessToken = responseJSON.getString("access_token");
        String idToken = responseJSON.getString("id_token");

        //save the tokens
        preferences.accessToken.set(accessToken);
        preferences.idToken.set(idToken);

        //save the user identity separately
        String[] idTokenData = idToken.split("\\.");
        byte[] decodedIdTokenData = Base64.decode(idTokenData[1], Base64.DEFAULT);
        String decodedIdTokenString = new String(decodedIdTokenData);
        JSONObject idTokenJSON = new JSONObject(decodedIdTokenString);

        if (idTokenJSON.has("imf.user")) {
            preferences.userIdentity.set(idTokenJSON.getJSONObject("imf.user"));
        }

        logger.debug("token successfully saved");
    } catch (Exception e) {
        throw new RuntimeException("Failed to save token from response", e);
    }
}

From source file:com.marlonjones.voidlauncher.InstallShortcutReceiver.java

private static PendingInstallShortcutInfo decode(String encoded, Context context) {
    try {//from  w ww  .j  a  v a2 s  .c  o m
        JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue();
        Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);

        if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) {
            // The is an internal launcher target shortcut.
            UserHandleCompat user = UserManagerCompat.getInstance(context)
                    .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY));
            if (user == null) {
                return null;
            }

            LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context)
                    .resolveActivity(launcherIntent, user);
            return info == null ? null : new PendingInstallShortcutInfo(info, context);
        }

        Intent data = new Intent();
        data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
        data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY));

        String iconBase64 = object.optString(ICON_KEY);
        String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
        String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
        if (iconBase64 != null && !iconBase64.isEmpty()) {
            byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
            Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
        } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
            Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
            iconResource.resourceName = iconResourceName;
            iconResource.packageName = iconResourcePackageName;
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
        }

        return new PendingInstallShortcutInfo(data, context);
    } catch (JSONException | URISyntaxException e) {
        Log.d(TAG, "Exception reading shortcut to add: " + e);
    }
    return null;
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * {@code getDataValidity} is used to verify the digital signature of the
 * received data. If the verification is true then {@code true} is returned
 * otherwise {@code false}./*from  ww  w  .  j a  v  a  2  s .  c  o  m*/
 * 
 * @param key
 *            the PublicKey received from server.
 * @param data
 *            the data received from server.
 * @param serverDataSig
 *            the Signature corresponding to the received data.
 * @return Boolean value.
 * @throws NoSuchAlgorithmException
 *             if the specified algorithm is not available.
 * @throws InvalidKeyException
 *             if publicKey is not valid.
 * @throws SignatureException
 *             if this Signature instance is not initialized properly.
 */
private Boolean getDataValidity(PublicKey key, String data, String serverDataSig)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature s = Signature.getInstance("SHA256withRSA");
    s.initVerify(key);
    byte[] byte_dataFromServer = data.getBytes();
    s.update(byte_dataFromServer);
    byte[] byte_serverDataSig = Base64.decode(serverDataSig, Base64.DEFAULT);
    Boolean valid = s.verify(byte_serverDataSig);
    return valid;
}

From source file:mobisocial.musubi.identity.AphidIdentityProvider.java

private byte[] getAphidResultForIdentity(IBIdentity ident, String property) throws IdentityProviderException {
    Log.d(TAG, "Getting key for " + ident.principal_);

    // Populate tokens from identity providers (only Google and Facebook for now)
    try {//w w  w.  ja  v  a 2  s. co m
        cacheGoogleTokens();
    } catch (IdentityProviderException.Auth e) {
        // No need to continue if this is our identity and token fetch failed
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.Auth(ident);
        }
    } catch (IdentityProviderException.NeedsRetry e) {
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.NeedsRetry(ident);
        }
    }
    try {
        cacheCurrentFacebookToken();
    } catch (IdentityProviderException e) {
        // No need to continue if this is our identity and token fetch failed
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.Auth(ident);
        }
    }

    String aphidType = null;
    String aphidToken = null;
    // Get a service-specific token if it exists
    Pair<Authority, String> userProperties = new Pair<Authority, String>(ident.authority_, ident.principal_);
    if (mKnownTokens.containsKey(userProperties)) {
        aphidToken = mKnownTokens.get(userProperties);
    }

    // The IBE server has its own identifiers for providers
    switch (ident.authority_) {
    case Facebook:
        aphidType = "facebook";
        break;
    case Email:
        if (mKnownTokens.containsKey(userProperties)) {
            aphidType = "google";
        }
        break;
    case PhoneNumber:
        // Aphid doesn't return keys for a phone number without verification
        throw new IdentityProviderException.TwoPhase(ident);
    }

    // Do not ask the server for identities we don't know how to handle
    if (aphidType == null || aphidToken == null) {
        throw new IdentityProviderException(ident);
    }

    // Bundle arguments as JSON
    JSONObject jsonObj = new JSONObject();
    try {
        jsonObj.put("type", aphidType);
        jsonObj.put("token", aphidToken);
        jsonObj.put("starttime", ident.temporalFrame_);
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
    JSONArray userinfo = new JSONArray();
    userinfo.put(jsonObj);

    // Contact the server
    try {
        JSONObject resultObj = getAphidResult(userinfo);
        if (resultObj == null) {
            throw new IdentityProviderException.NeedsRetry(ident);
        }
        String encodedKey = resultObj.getString(property);
        boolean hasError = resultObj.has("error");
        if (!hasError) {
            long temporalFrame = resultObj.getLong("time");
            if (encodedKey != null && temporalFrame == ident.temporalFrame_) {
                // Success!
                return Base64.decode(encodedKey, Base64.DEFAULT);
            } else {
                // Might have jumped the gun a little bit, so try again later
                throw new IdentityProviderException.NeedsRetry(ident);
            }
        } else {
            // Aphid authentication error means Musubi has a bad token
            String error = resultObj.getString("error");
            if (error.contains("401")) {
                // Authentication errors require user action
                String accountType = Character.toString(Character.toUpperCase(aphidType.charAt(0)))
                        + aphidType.substring(1);
                sendNotification(accountType);
                throw new IdentityProviderException.Auth(ident);
            } else {
                // Other failures should be retried silently
                throw new IdentityProviderException.NeedsRetry(ident);
            }
        }
    } catch (IOException e) {
        Log.e(TAG, e.toString());
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
    throw new IdentityProviderException.NeedsRetry(ident);
}

From source file:com.android.launcher3.InstallShortcutReceiver.java

private static PendingInstallShortcutInfo decode(String encoded, Context context) {
    try {//from w w  w  .  j  av  a  2s . c o m
        JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue();
        Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);

        if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) {
            // The is an internal launcher target shortcut.
            UserHandleCompat user = UserManagerCompat.getInstance(context)
                    .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY));
            if (user == null) {
                return null;
            }

            LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context)
                    .resolveActivity(launcherIntent, user);
            return info == null ? null : new PendingInstallShortcutInfo(info, context);
        }

        Intent data = new Intent();
        data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
        data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY));

        String iconBase64 = object.optString(ICON_KEY);
        String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
        String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
        if (iconBase64 != null && !iconBase64.isEmpty()) {
            byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
            Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
        } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
            Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
            iconResource.resourceName = iconResourceName;
            iconResource.packageName = iconResourcePackageName;
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
        }

        return new PendingInstallShortcutInfo(data, context);
    } catch (JSONException e) {
        Log.d(TAG, "Exception reading shortcut to add: " + e);
    } catch (URISyntaxException e) {
        Log.d(TAG, "Exception reading shortcut to add: " + e);
    }
    return null;
}

From source file:org.kde.kdeconnect.Device.java

public void addLink(NetworkPackage identityPackage, BaseLink link) {
    //FilesHelper.LogOpenFileCount();

    this.protocolVersion = identityPackage.getInt("protocolVersion");

    if (identityPackage.has("deviceName")) {
        this.name = identityPackage.getString("deviceName", this.name);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("deviceName", this.name);
        editor.apply();//from ww  w.  j  a  v  a2s. c  o  m
    }

    if (identityPackage.has("deviceType")) {
        this.deviceType = DeviceType.FromString(identityPackage.getString("deviceType", "desktop"));
    }

    if (identityPackage.has("certificate")) {
        String certificateString = identityPackage.getString("certificate");

        try {
            byte[] certificateBytes = Base64.decode(certificateString, 0);
            certificate = SslHelper.parseCertificate(certificateBytes);
            Log.i("KDE/Device", "Got certificate ");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("KDE/Device", "Error getting certificate");

        }
    }

    links.add(link);

    try {
        SharedPreferences globalSettings = PreferenceManager.getDefaultSharedPreferences(context);
        byte[] privateKeyBytes = Base64.decode(globalSettings.getString("privateKey", ""), 0);
        PrivateKey privateKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        link.setPrivateKey(privateKey);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/Device", "Exception reading our own private key"); //Should not happen
    }

    Log.i("KDE/Device", "addLink " + link.getLinkProvider().getName() + " -> " + getName() + " active links: "
            + links.size());

    if (!pairingHandlers.containsKey(link.getName())) {
        BasePairingHandler.PairingHandlerCallback callback = new BasePairingHandler.PairingHandlerCallback() {
            @Override
            public void incomingRequest() {
                for (PairingCallback cb : pairingCallback) {
                    cb.incomingRequest();
                }
            }

            @Override
            public void pairingDone() {
                Device.this.pairingDone();
            }

            @Override
            public void pairingFailed(String error) {
                for (PairingCallback cb : pairingCallback) {
                    cb.pairingFailed(error);
                }
            }

            @Override
            public void unpaired() {
                unpairInternal();
            }
        };
        pairingHandlers.put(link.getName(), link.getPairingHandler(this, callback));
    }

    Set<String> outgoingCapabilities = identityPackage.getStringSet("outgoingCapabilities", null);
    Set<String> incomingCapabilities = identityPackage.getStringSet("incomingCapabilities", null);
    if (incomingCapabilities != null && outgoingCapabilities != null) {
        m_supportedPlugins = new Vector<>(
                PluginFactory.pluginsForCapabilities(context, incomingCapabilities, outgoingCapabilities));
    } else {
        m_supportedPlugins = new Vector<>(PluginFactory.getAvailablePlugins());
    }

    link.addPackageReceiver(this);

    reloadPluginsFromSettings();

}

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  .j  a  va  2 s  .  c  om*/
    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.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java

private String decryptRSAToString(String encryptedBase64, String privateKey) {
    String decryptedString = "";
    try {//  ww w  . j a  va  2s.  c o  m
        String rStart = privateKey.replace("-----BEGIN PUBLIC KEY-----", "");
        String rEnd = rStart.replace("-----END PUBLIC KEY-----", "");
        rEnd = rEnd.replaceAll("\r", "");
        rEnd = rEnd.replaceAll("\n", "");
        rEnd = rEnd.replaceAll("\t", "");
        rEnd = rEnd.replaceAll(" ", "");
        KeyFactory keyFac = KeyFactory.getInstance("RSA");

        PublicKey publicKey = keyFac
                .generatePublic(new X509EncodedKeySpec(Base64.decode(rEnd.toString(), Base64.DEFAULT)));

        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        // encrypt the plain text using the public key
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        byte[] encryptedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        decryptedString = new String(decryptedBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return decryptedString;
}

From source file:com.openerp.base.ir.Attachment.java

private String createFile(String name, String base64, String file_type) {
    byte[] fileAsBytes = Base64.decode(base64, 0);

    InputStream is = new ByteArrayInputStream(fileAsBytes);
    String filename = name.replaceAll("[-+^:=, ]", "_");
    String file_path = getDirectoryPath(file_type) + "/" + filename;
    try {/*ww  w  . j  a  v a 2s. c o  m*/
        FileOutputStream fos = new FileOutputStream(file_path);
        byte data[] = new byte[1024];
        int count = 0;
        while ((count = is.read(data)) != -1) {
            fos.write(data, 0, count);
        }
        is.close();
        fos.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return file_path;
}