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:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code PublicKey}. Convert the string formatted
 * public key into {@code PublicKey} type.
 * //from   w ww  . j  av a2 s . c om
 * @param key
 *            the string formated public key.
 * @return the new {@code PublicKey} instance.
 * @throws NoSuchAlgorithmException
 *             if no provider provides the requested algorithm.
 * @throws InvalidKeyException
 *             if the specified keySpec is invalid.
 * 
 */
// Converting the Server Public key format to Java compatible from
private PublicKey getServerPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {

    // Converting the Server Public key format to Java compatible from
    key = key.replace("-----BEGIN PUBLIC KEY-----\n", "");
    key = key.replace("\n-----END PUBLIC KEY-----", "");

    // Creating the public key from the string format received from server
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey serverPublicKeySig = keyFactory
            .generatePublic(new X509EncodedKeySpec(Base64.decode(key.toString(), Base64.DEFAULT)));
    return serverPublicKeySig;
}

From source file:com.facebook.unity.FB.java

/**
 * Provides the key hash to solve the openSSL issue with Amazon
 * @return key hash/*from   ww w  . j  ava 2  s .  c o m*/
 */
@TargetApi(Build.VERSION_CODES.FROYO)
public static String getKeyHash() {
    try {
        // In some cases the unity activity may not exist. This can happen when we are
        // completing a login and unity activity was killed in the background. In this
        // situation it's not necessary to send back the keyhash since the app will overwrite
        // the value with the value they get during the init call and the unity activity
        // wil be created by the time init is called.
        Activity activity = getUnityActivity();
        if (activity == null) {
            return "";
        }

        PackageInfo info = activity.getPackageManager().getPackageInfo(activity.getPackageName(),
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            String keyHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
            Log.d(TAG, "KeyHash: " + keyHash);
            return keyHash;
        }
    } catch (NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }
    return "";
}

From source file:android.framework.util.jar.JarVerifier.java

private boolean verify(Attributes attributes, String entry, byte[] data, int start, int end,
        boolean ignoreSecondEndline, boolean ignorable) {
    String algorithms = attributes.getValue("Digest-Algorithms");
    if (algorithms == null) {
        algorithms = "SHA SHA1";
    }//  www  .ja  va  2 s .  co  m
    StringTokenizer tokens = new StringTokenizer(algorithms);
    while (tokens.hasMoreTokens()) {
        String algorithm = tokens.nextToken();
        String hash = attributes.getValue(algorithm + entry);
        if (hash == null) {
            continue;
        }

        MessageDigest md;
        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            continue;
        }
        if (ignoreSecondEndline && data[end - 1] == '\n' && data[end - 2] == '\n') {
            md.update(data, start, end - 1 - start);
        } else {
            md.update(data, start, end - start);
        }
        byte[] b = md.digest();
        byte[] hashBytes = hash.getBytes(Charsets.ISO_8859_1);
        return MessageDigest.isEqual(b, Base64.decode(hashBytes, Base64.DEFAULT));
    }
    return ignorable;
}

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 av a 2s  .  c  o m
    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
 *//*from   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  ww  w.j a v a  2  s . co 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  w w  w .j a  v a 2s  .  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:org.mobisocial.corral.CorralDownloadClient.java

private static String hashToString(long hash) {
    try {//w  ww . j av a 2s . c o  m
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        dos.writeLong(hash);
        dos.writeInt(-4);
        byte[] data = bos.toByteArray();
        return Base64.encodeToString(data, Base64.DEFAULT).substring(0, 11);
    } catch (IOException e) {
        return null;
    }
}

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 {/*from   w w  w .  j a va2  s.c  om*/
        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 {/*  w  w  w .j a  va2s  .c  om*/
        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;
}