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.primitive.applicationmanager.ApplicationManager.java

/**
 * ApplicationSummary??????/*from   www .  ja  v  a 2  s.com*/
 * @return ApplicationSummary
 * @throws ApplicationManagerException
 */
private ApplicationSummary requestApplicationSummary() throws ApplicationManagerException {
    Logger.start();
    final String url = this.config.buildServerURL(ApplicationManager.ApplicationURI);
    final Map<String, String> params = new HashMap<String, String>();
    params.put("id", this.applicationID);
    final JSONObject json = this.requestToResponse(url, params);
    try {
        final boolean success = json.getBoolean("sucess");
        if (!success) {
            return this.beforeSummary;
        }
        final String hash = json.getString("hash");
        final String result = json.getString("result");
        final String passphrase = HashMacHelper.getHMACBase64(HashMacHelper.Algorithm.HmacSHA256,
                hash.getBytes("UTF-8"), this.config.passPhrase.getBytes("UTF-8"));

        byte[] passPhraseBytes = new byte[256 / 8];
        System.arraycopy(passphrase.getBytes(), 0, passPhraseBytes, 0, 256 / 8);

        final byte[] decriptDataByte = CipherHelper.decrypt(CipherHelper.Algorithm.AES, Mode.CBC,
                Padding.PKCS7Padding, Base64.decode(result.getBytes("UTF-8"), Base64.DEFAULT),
                hash.getBytes("UTF-8"), passPhraseBytes);

        final String decriptData = new String(decriptDataByte, "UTF-8");

        final JSONObject decript = new JSONObject(decriptData);
        final ApplicationSummary summary = new ApplicationSummary(decript);
        if (this.isUpgrade(summary)) {
            this.beforeSummary = summary;
        }
        this.beforeSummary = summary;
    } catch (final JSONException ex) {
        Logger.err(ex);
    } catch (final UnsupportedEncodingException ex) {
        Logger.err(ex);
    } catch (CipherException ex) {
        Logger.err(ex);
    }
    return this.beforeSummary;
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public void resultAnalyst(String restr, int delaynum, int speednum, String targetoutputfolder)
        throws IOException {

    String[] tempgetudplist = restr.split("sickjohnsisick1122356l112355iaaaoss");

    //     System.out.println(tempgetudplist[1]);

    String[] tempstrs = tempgetudplist[0].split("\\r\\n");

    for (int i = 10; i < tempstrs.length; i++) {

        String[] tempstrsxxxx = tempstrs[i].split(",");
        //vpn539246233|182.216.181.220|508611|35|41230804|Korea Republic of|KR|13|
        //#HostName|IP|Score|Ping|Speed|CountryLong|CountryShort|NumVpnSessions|Uptime|TotalUsers|TotalTraffic|LogType|Operator|Message|OpenVPN_ConfigData_Base64|\

        if (tempstrsxxxx.length > 14) {
            //Base64 decoder = new Base64();

            byte[] decodedBytes = Base64.decode(tempstrsxxxx[14], Base64.DEFAULT);
            tempstrsxxxx[14] = new String(decodedBytes, "UTF-8");
            tempstrsxxxx[14] = tempstrsxxxx[14].replaceAll("#.+?\r\n", "");

            // System.out.println
            log.info(tempstrsxxxx[0] + "|" + tempstrsxxxx[1] + "|" + tempstrsxxxx[2] + "|" + tempstrsxxxx[3]
                    + "|" + tempstrsxxxx[4] + "|" + tempstrsxxxx[5] + "|" + tempstrsxxxx[6] + "|"
                    + tempstrsxxxx[7] + "|" + tempstrsxxxx[8] + "|" + tempstrsxxxx[9] + "|" + tempstrsxxxx[10]
                    + "|" + tempstrsxxxx[11] + "|" + tempstrsxxxx[12] + "|" + tempstrsxxxx[13] + "|"
            // +udplist.get(tempudpportnum+1)+"|" //+tempstrsxxxx[14]
            );/*ww w  .  ja v  a  2s.  c  o m*/

            if (isNumericInt(tempstrsxxxx[7]) && isNumericInt(tempstrsxxxx[3]) && isNumericInt(tempstrsxxxx[4])
                    &&
                    //tempstrsxxxx[14].indexOf("proto udp")!=-1 &&
                    // Integer.valueOf(tempstrsxxxx[7])>0        &&
                    Integer.valueOf(tempstrsxxxx[3]) < delaynum
                    && Integer.valueOf(tempstrsxxxx[4]) > speednum) {

                //  tempgetudplist[1].split(",");
                List<String> udplist = Arrays.asList(tempgetudplist[1].split(","));

                int tempudpportnum = udplist.indexOf(tempstrsxxxx[0]);

                if (tempudpportnum != -1) {

                    tempstrsxxxx[14] = tempstrsxxxx[14].replace("proto tcp", "proto udp");
                    tempstrsxxxx[14] = tempstrsxxxx[14].replaceFirst(
                            "remote [0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+ [0-9]+",
                            "remote " + tempstrsxxxx[1] + " " + udplist.get(tempudpportnum + 1));

                    int performrank = Integer.valueOf(tempstrsxxxx[2]) / 10000;

                    File tempfile = new File(targetoutputfolder + tempstrsxxxx[1] + "_" + tempstrsxxxx[6]
                            + "_udp_" + "Rank" + performrank + ".ovpn");
                    FileOutputStream osss = new FileOutputStream(tempfile);
                    osss.write(tempstrsxxxx[14].getBytes("UTF-8"));
                    osss.close();

                    //System.out.println
                    log.info(tempfile.getAbsoluteFile().toString());
                    tempfile = null;

                }
                //+tempstrsxxxx[14]+"|");
            }

        }

    }

}

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

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *//*from   w  w w . java2s  . c  o  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.emm.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 e) {
                        Log.e(TAG, e.getMessage());
                    } catch (KeyStoreException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, 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:com.luyaozhou.recognizethisforglass.ViewFinder.java

private void processPictureWhenReady(final String picturePath) {
    final File pictureFile = new File(picturePath);
    //Map<String, String > result = new HashMap<String,String>();

    if (pictureFile.exists()) {
        // The picture is ready; process it.
        Bitmap imageBitmap = null;/*from www. j  a  v  a 2 s.  c  o  m*/
        try {
            //               Bundle extras = data.getExtras();
            //               imageBitmap = (Bitmap) extras.get("data");
            FileInputStream fis = new FileInputStream(picturePath); //get the bitmap from file
            imageBitmap = (Bitmap) BitmapFactory.decodeStream(fis);

            if (imageBitmap != null) {
                Bitmap lScaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 1600, 1200, false);
                if (lScaledBitmap != null) {
                    imageBitmap.recycle();
                    imageBitmap = null;

                    ByteArrayOutputStream lImageBytes = new ByteArrayOutputStream();
                    lScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, lImageBytes);
                    lScaledBitmap.recycle();
                    lScaledBitmap = null;

                    byte[] lImageByteArray = lImageBytes.toByteArray();

                    HashMap<String, String> lValuePairs = new HashMap<String, String>();
                    lValuePairs.put("base64Image", Base64.encodeToString(lImageByteArray, Base64.DEFAULT));
                    lValuePairs.put("compressionLevel", "30");
                    lValuePairs.put("documentIdentifier", "DRIVER_LICENSE_CA");
                    lValuePairs.put("documentHints", "");
                    lValuePairs.put("dataReturnLevel", "15");
                    lValuePairs.put("returnImageType", "1");
                    lValuePairs.put("rotateImage", "0");
                    lValuePairs.put("data1", "");
                    lValuePairs.put("data2", "");
                    lValuePairs.put("data3", "");
                    lValuePairs.put("data4", "");
                    lValuePairs.put("data5", "");
                    lValuePairs.put("userName", "zbroyan@miteksystems.com");
                    lValuePairs.put("password", "google1");
                    lValuePairs.put("phoneKey", "1");
                    lValuePairs.put("orgName", "MobileImagingOrg");

                    String lSoapMsg = formatSOAPMessage("InsertPhoneTransaction", lValuePairs);

                    DefaultHttpClient mHttpClient = new DefaultHttpClient();
                    //                        mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.R)
                    HttpPost mHttpPost = new HttpPost();

                    mHttpPost.setHeader("User-Agent", "UCSD Team");
                    mHttpPost.setHeader("Content-typURIe", "text/xml;charset=UTF-8");
                    //mHttpPost.setURI(URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx?op=InsertPhoneTransaction"));
                    mHttpPost.setURI(
                            URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx"));

                    StringEntity se = new StringEntity(lSoapMsg, HTTP.UTF_8);
                    se.setContentType("text/xml; charset=UTF-8");
                    mHttpPost.setEntity(se);
                    HttpResponse mResponse = mHttpClient.execute(mHttpPost, new BasicHttpContext());

                    String responseString = new BasicResponseHandler().handleResponse(mResponse);
                    parseXML(responseString);

                    //Todo: this is test code. Need to be implemented
                    //result = parseXML(testStr);
                    Log.i("test", "test:" + " " + responseString);
                    Log.i("test", "test: " + " " + map.size());

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

        // this part will be relocated in order to let the the server process picture
        if (map.size() == 0) {
            Intent display = new Intent(getApplicationContext(), DisplayInfoFailed.class);
            display.putExtra("result", (java.io.Serializable) iQAMsg);
            startActivity(display);
        } else {
            Intent display = new Intent(getApplicationContext(), DisplayInfo.class);
            display.putExtra("result", (java.io.Serializable) map);
            startActivity(display);

        }
    } else {
        // The file does not exist yet. Before starting the file observer, you
        // can update your UI to let the user know that the application is
        // waiting for the picture (for example, by displaying the thumbnail
        // image and a progress indicator).

        final File parentDirectory = pictureFile.getParentFile();
        FileObserver observer = new FileObserver(parentDirectory.getPath(),
                FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
            // Protect against additional pending events after CLOSE_WRITE
            // or MOVED_TO is handled.
            private boolean isFileWritten;

            @Override
            public void onEvent(int event, final String path) {
                if (!isFileWritten) {
                    // For safety, make sure that the file that was created in
                    // the directory is actually the one that we're expecting.
                    File affectedFile = new File(parentDirectory, path);
                    isFileWritten = affectedFile.equals(pictureFile);

                    if (isFileWritten) {
                        stopWatching();
                        // Now that the file is ready, recursively call
                        // processPictureWhenReady again (on the UI thread).
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new LongOperation().execute(picturePath);
                            }
                        });
                    }
                }
            }
        };
        observer.startWatching();

    }

}

From source file:com.moki.touch.util.management.ContentManager.java

/**
 * Get a list of urls that indicate what urls exist in the settings of the application
 * @return an arraylist of strings for content urls in the settings
 *//*w  w w.ja va 2 s.c  o m*/
public ArrayList<String> getAllSettingsUrls() {
    ArrayList<String> settingsUrls = new ArrayList<String>();
    JSONArray urls = SettingsUtil.getSettingsValues().optJSONArray(CONTENT_KEY);
    for (int i = 0; i < urls.length(); i++) {
        settingsUrls.add(Base64.encodeToString(
                urls.optJSONObject(i).optString(ContentObject.CONTENT_URL).getBytes(), Base64.DEFAULT));
    }
    return settingsUrls;
}

From source file:com.example.SmartBoard.MQTTHandler.java

public static String bitmapToString(Bitmap bitmapImage) {
    if (bitmapImage == null)
        return null;
    Bitmap bitmap = bitmapImage;//from w  ww  .j a  va2  s .co m
    ByteArrayOutputStream blob = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, blob);
    byte[] bitmapdata = blob.toByteArray();
    return Base64.encodeToString(bitmapdata, Base64.DEFAULT);
}

From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java

/**
 * Parse the JSON Web Signature (JWS) response from the {@link SafetyNet} response.
 *
 * @param jws/*  www.ja  v a  2  s  . co  m*/
 *     The output of {@link SafetyNetApi.AttestationResult#getJwsResult()}.
 * @return The {@link SafetyNetResponse}.
 * @throws SafetyNetError
 *     If an error occurs while parsing the JWS.
 */
public static SafetyNetResponse getSafetyNetResponseFromJws(@NonNull String jws) throws SafetyNetError {
    try {
        String[] parts = jws.split("\\.");

        HashMap<String, Object> header = new HashMap<>();

        try {
            JSONObject json = new JSONObject(new String(Base64.decode(parts[0], Base64.DEFAULT)));
            for (Iterator<String> iterator = json.keys(); iterator.hasNext();) {
                String key = iterator.next();
                header.put(key, json.get(key));
            }
        } catch (Exception ignored) {
        }

        JSONObject json = new JSONObject(new String(Base64.decode(parts[1], Base64.DEFAULT)));
        String nonce = json.optString("nonce");
        long timestampMs = json.optLong("timestampMs");
        String apkPackageName = json.optString("apkPackageName");

        JSONArray jsonArray = json.optJSONArray("apkCertificateDigestSha256");
        String[] apkCertificateDigestSha256 = null;
        if (jsonArray != null) {
            int length = jsonArray.length();
            apkCertificateDigestSha256 = new String[length];
            for (int i = 0; i < length; i++) {
                apkCertificateDigestSha256[i] = jsonArray.getString(i);
            }
        }

        String apkDigestSha256 = json.optString("apkDigestSha256");
        boolean ctsProfileMatch = json.optBoolean("ctsProfileMatch");
        String signature = parts[2];

        return new SafetyNetResponse(jws, header, nonce, timestampMs, apkPackageName,
                apkCertificateDigestSha256, apkDigestSha256, ctsProfileMatch, signature);

    } catch (Exception e) {
        throw new SafetyNetError(e);
    }
}

From source file:com.mi.xserv.Xserv.java

private void manageMessage(String event) {
    JSONObject json = null;//w ww. j a v a 2  s . c om
    try {
        json = new JSONObject(event);
    } catch (JSONException ignored) {
    }

    if (json != null) {
        int op = 0;
        try {
            op = json.getInt("op");
        } catch (JSONException ignored) {
        }

        if (op == 0) {
            // messages

            onReceiveMessages(json);
        } else if (op > 0) {
            // operations

            try {
                String data = json.getString("data");
                byte[] b = Base64.decode(data, Base64.DEFAULT);
                json.put("data", new String(b, "UTF-8")); // string
            } catch (JSONException | UnsupportedEncodingException ignored) {
            }

            JSONObject json_data = null;
            try {
                String data = json.getString("data");
                Object type = new JSONTokener(data).nextValue();
                if (type instanceof JSONObject) {
                    json_data = new JSONObject(data);

                    json.put("data", json_data);
                } else if (type instanceof JSONArray) {
                    json.put("data", new JSONArray(data));
                }
            } catch (JSONException ignored) {
            }

            try {
                json.put("name", stringifyOp(op));
            } catch (JSONException ignored) {
            }

            int rc = 0;
            String uuid = "";
            String topic = "";
            String descr = "";
            try {
                rc = json.getInt("rc");
                uuid = json.getString("uuid");
                topic = json.getString("topic");
                descr = json.getString("descr");
            } catch (JSONException ignored) {
            }

            if (op == OP_HANDSHAKE) {
                // handshake

                if (rc == RC_OK) {
                    if (json_data != null) {
                        setUserData(json_data);

                        isConnected = true;

                        onOpenConnection();
                    } else {
                        mCallbacks.clear();

                        onErrorConnection(new Exception(descr));
                    }
                } else {
                    mCallbacks.clear();

                    onErrorConnection(new Exception(descr));
                }
            } else {
                // classic operations

                if (op == OP_SUBSCRIBE && isPrivateTopic(topic) && rc == RC_OK) {
                    if (json_data != null) {
                        setUserData(json_data);
                    }
                }

                if (mCallbacks.get(uuid) != null) {
                    mCallbacks.get(uuid).onCompletion(json);
                    mCallbacks.remove(uuid);
                } else {
                    OnReceiveOperations(json);
                }
            }
        }
    }
}

From source file:com.lillicoder.newsblurry.net.PreferenceCookieStore.java

/**
 * Decodes the given base-64 cookie string and returns a
 * {@link Cookie} representing that data.
 * @param encodedCookie Base-64 encoded string of a stored {@link Cookie}.
 * @return {@link Cookie} decoded from the given base-64 encoded cookie string.
 *//*from   w w  w .j a v  a  2s .c om*/
private Cookie decodeCookie(String encodedCookie) {
    Assert.assertTrue(encodedCookie != null);

    byte[] rawData = Base64.decode(encodedCookie, Base64.DEFAULT);
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);

    Cookie cookie = null;
    try {
        ObjectInputStream inStream = new ObjectInputStream(in);
        SerializableCookie serializableCookie = (SerializableCookie) inStream.readObject();
        if (serializableCookie != null)
            cookie = serializableCookie.getCookie();
    } catch (ClassNotFoundException e) {
        Log.w(TAG, WARNING_FAILED_TO_FIND_SERIALIZABLE_COOKIE_CLASS);
    } catch (IOException e) {
        Log.w(TAG, WARNING_FAILED_TO_READ_COOKIE_FROM_STREAM);
    }

    return cookie;
}

From source file:com.pedox.plugin.HttpClient.HttpClient.java

public void getImage(final Activity context, String url, JSONObject options,
        final CallbackContext callbackContext) throws JSONException {
    final AsyncHttpClient client = new AsyncHttpClient();
    this.setArgument(client, options);
    client.get(url, new FileAsyncHttpResponseHandler(context) {
        @Override//from w w w . ja v a 2  s  .c o m
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
            HttpClient.handleResult(false, statusCode, headers, "kekacauan", callbackContext, throwable);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, File file) {

            InputStream inputStream = null;
            try {
                inputStream = new FileInputStream(file.getPath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            byte[] bytes;
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            bytes = output.toByteArray();
            String encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);

            HttpClient.handleResult(true, statusCode, headers, encodedImage, callbackContext, null);
        }
    });
}