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:org.comixwall.pffw.GraphsBase.java

/**
 * Run the controller task./*from   w w  w  . j  ava 2 s  .  co m*/
 * We fetch the graphs using secure http, or fall back to plain http if secure connection fails.
 * <p>
 * Note that the PFFW uses a self-signed server certificate. So the code should trust that certificate
 * and not reject the hostname.
 *
 * @return True on success, false on failure.
 */
@Override
public boolean executeTask() {
    Boolean retval = true;
    try {
        String output = controller.execute("symon", "RenderLayout", mLayout, mGraphWidth, mGraphHeight);

        JSONArray jsonArray = new JSONArray(output);
        mGraphsJsonObject = new JSONObject(jsonArray.get(0).toString());

        Iterator<String> it = mGraphsJsonObject.keys();
        while (it.hasNext()) {
            String title = it.next();
            String file = mGraphsJsonObject.getString(title);

            try {
                InputStream stream = null;

                try {
                    String outputGraph = controller.execute("symon", "GetGraph", file);
                    String base64Graph = new JSONArray(outputGraph).get(0).toString();
                    stream = new ByteArrayInputStream(Base64.decode(base64Graph, Base64.DEFAULT));

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.warning("SSH graph connection exception: " + e.toString());
                }

                // Try secure http if ssh fails
                if (stream == null) {
                    // 1540861800_404e00f4044d07242a77f802e457f774
                    String hash = file.substring(file.indexOf('_') + 1);

                    try {
                        // Using https here gives: CertPathValidatorException: Trust anchor for certification path not found.
                        // So we should trust the PFFW server crt and hostname
                        URL secureUrl = new URL("https://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpsURLConnection secureUrlConn = (HttpsURLConnection) secureUrl.openConnection();

                        // Tell the URLConnection to use a SocketFactory from our SSLContext
                        secureUrlConn.setSSLSocketFactory(sslContext.getSocketFactory());

                        // Install the PFFW host verifier
                        secureUrlConn.setHostnameVerifier(hostnameVerifier);

                        logger.finest("Using secure http: " + secureUrl.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        secureUrlConn.setConnectTimeout(5000);
                        secureUrlConn.setReadTimeout(5000);
                        logger.finest("Secure URL connection timeout values: "
                                + secureUrlConn.getConnectTimeout() + ", " + secureUrlConn.getReadTimeout());

                        stream = secureUrlConn.getInputStream();

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.warning("Secure URL connection exception: " + e.toString());
                    }

                    // Try plain http if secure http fails
                    if (stream == null) {
                        // ATTENTION: Don't use try-catch here, catch in the outer exception handling
                        URL plainUrl = new URL("http://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpURLConnection plainUrlConn = (HttpURLConnection) plainUrl.openConnection();

                        logger.finest("Using plain http: " + plainUrlConn.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        plainUrlConn.setConnectTimeout(5000);
                        plainUrlConn.setReadTimeout(5000);
                        logger.finest("Plain URL connection timeout values: " + plainUrlConn.getConnectTimeout()
                                + ", " + plainUrlConn.getReadTimeout());

                        stream = plainUrlConn.getInputStream();
                    }
                }

                Bitmap bmp = BitmapFactory.decodeStream(stream);
                setBitmap(title, bmp);

            } catch (Exception e) {
                // We are especially interested in SocketTimeoutException, but catch all
                e.printStackTrace();
                logger.info("GraphsBase doInBackground exception: " + e.toString());
                // We should break out of while loop on exception, because all conn attempts have failed
                break;
            }
        }

        output = controller.execute("pf", "GetReloadRate");

        int timeout = Integer.parseInt(new JSONArray(output).get(0).toString());
        mRefreshTimeout = timeout < 10 ? 10 : timeout;

    } catch (Exception e) {
        e.printStackTrace();
        logger.warning("doInBackground exception: " + e.toString());
        retval = false;
    }
    return retval;
}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 */// w  w w.  j  ava 2  s.co  m
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException
                            | IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }
    }
}

From source file:net.bither.util.TransactionsUtil.java

public static List<In> getInSignatureFromBither(String str) {
    List<In> result = new ArrayList<In>();
    if (str.length() > 0) {
        String[] txs = str.split(";");
        for (String tx : txs) {
            String[] ins = tx.split(":");
            byte[] txHash = Utils.reverseBytes(Base64.decode(ins[0], Base64.URL_SAFE));
            for (int i = 1; i < ins.length; i++) {
                String[] array = ins[i].split(",");
                int inSn = Integer.decode(array[0]);
                byte[] inSignature = Base64.decode(array[1], Base64.URL_SAFE);
                In in = new In();
                in.setTxHash(txHash);/*from  w  w  w .j av  a  2s.co  m*/
                in.setInSn(inSn);
                in.setInSignature(inSignature);
                result.add(in);
            }
        }
    }
    return result;
}

From source file:de.tum.in.tumcampus.services.GcmIntentService.java

/**
 * Loads the private key from preferences
 *
 * @return The private key object/*  w w  w .  ja v a2  s  .  co m*/
 */
private PrivateKey getPrivateKeyFromSharedPrefs() {
    String privateKeyString = Utils.getInternalSettingString(this, Const.PRIVATE_KEY, "");
    byte[] privateKeyBytes = Base64.decode(privateKeyString, Base64.DEFAULT);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        return keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        Utils.log(e);
    }
    return null;
}

From source file:com.jbirdvegas.mgerrit.dialogs.DiffDialog.java

private Request getDebugRequest(String url, String arg) {
    // seems a bug prevents the args from being respected???
    // See here://w ww.j a  v  a2 s .  c om
    // https://groups.google.com/forum/?fromgroups#!topic/repo-discuss/xmFCHbD4Z0Q
    String limiter = "&o=context:2";

    final String args = arg + limiter;
    final String weburl = url + args;
    Request debugRequest = new StringRequest(weburl, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            Log.d(TAG,
                    "[DEBUG-MODE]\n" + "Decoded Response for args {" + args + '}' + "\n" + "url: " + weburl
                            + "\n==================================="
                            + new String(Base64.decode(s, Base64.URL_SAFE | Base64.NO_PADDING))
                            + "====================================");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Log.e(TAG, "Debuging Volley Failed!!!", volleyError);
        }
    });
    return debugRequest;
}

From source file:com.example.android.apis.graphics.FingerPaint.java

private Bitmap loadBitmap() {
    SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
    String previouslyEncodedImage = shre.getString("paint_image_data", "");

    if (!previouslyEncodedImage.equalsIgnoreCase("")) {
        byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
        Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        return mutableBitmap;
    }//from w ww  .j a  v a2 s.com

    Display display = getWindowManager().getDefaultDisplay();
    @SuppressWarnings("deprecation")
    int width = display.getWidth();

    @SuppressWarnings("deprecation")
    int height = display.getHeight();

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    return bitmap;
}

From source file:me.piebridge.android.preference.PreferenceFragment.java

/**
 * return XmlPullParser// w  w w  .  j  av a2  s .co m
 * @param xml compiled XML encoded in base64
 * @return XmlPullParser
 */
public static XmlPullParser getParser(String xml) {
    try {
        byte[] data = Base64.decode(xml, Base64.DEFAULT);

        // XmlBlock block = new XmlBlock(LAYOUT.getBytes("UTF-8"));
        Class<?> clazz = Class.forName("android.content.res.XmlBlock");
        Constructor<?> constructor = clazz.getDeclaredConstructor(byte[].class);
        constructor.setAccessible(true);
        Object block = constructor.newInstance(data);

        // XmlPullParser parser = block.newParser();
        Method method = clazz.getDeclaredMethod("newParser");
        method.setAccessible(true);
        return (XmlPullParser) method.invoke(block);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (java.lang.InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.securekey.sdk.sample.VerifyQuickCodeActivity.java

/**
 * Implements AssertUserListener.assertUserComplete
 * <p>//www  .j a  va2 s  . c  om
 * If successful, will forward received JWT data for a final usage for a third party
 * 
 */
@Override
public void assertUserComplete(int status, Vector<SKAudienceJwt> audiences) {
    if (status == Briidge.STATUS_OK) {

        // The JWT should be provide to a third party to be verify
        // It could be parse to see what's inside 

        dismissProgressDialog();
        for (SKAudienceJwt skAudienceJwt : audiences) {
            String[] jwtSegment = getJWSSegments(skAudienceJwt.getJwt());
            try {
                final StringBuilder message = new StringBuilder();
                message.append(new String(Base64.decode(jwtSegment[0], Base64.NO_WRAP), "UTF-8") + "\n");
                message.append(new String(Base64.decode(jwtSegment[1], Base64.NO_WRAP), "UTF-8") + "\n\n\n");
                showDialog(message.toString());

                verifyJWT(skAudienceJwt.getJwt());
            } catch (UnsupportedEncodingException e) {
                Log.e(VerifyQuickCodeActivity.class.toString(), e.getMessage());
            }
        }

    } else if (status == Briidge.STATUS_TRY_LATER_TOO_MANY_INVALID_ATTEMPTS) {
        showDialog("User suspended!");
    } else if (status == Briidge.STATUS_WRONG_CODE) {
        showDialog("Invalid code!");
    } else {
        dismissProgressDialog();
        showDialog("Failed during verification process.");
    }
}

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

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key./*from   ww w .  ja  va2  s .  com*/
 *
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey) {
    try {
        //byte[] decodedKey = Base64.decode(encodedPublicKey);
        byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
        return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        Log.e(TAG, "Invalid key specification.");
        throw new IllegalArgumentException(e);
    } // catch (Base64DecoderException e) {
      //    Log.e(TAG, "Base64 decoding failed.");
      //    throw new IllegalArgumentException(e);
      //}
}

From source file:com.github.pockethub.ui.commit.CommitFileViewActivity.java

private void loadMarkdown() {
    ViewUtils.setGone(loadingBar, false);
    ViewUtils.setGone(codeView, true);/*from w w  w . ja  v  a  2  s .c  o  m*/

    String markdown = new String(Base64.decode(blob.content, Base64.DEFAULT));
    Bundle args = new Bundle();
    args.putCharSequence(ARG_TEXT, markdown);
    args.putParcelable(ARG_REPO, repo);
    getSupportLoaderManager().restartLoader(0, args, this);
}