Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

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

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:com.android.exchange.EasSyncService.java

/**
 * Using mUserName and mPassword, create and cache mAuthString and mCacheString, which are used
 * in all HttpPost commands.  This should be called if these strings are null, or if mUserName
 * and/or mPassword are changed/*from w  ww.  j  a  v a  2 s.  co  m*/
 */
@SuppressWarnings("deprecation")
private void cacheAuthAndCmdString() {
    String safeUserName = URLEncoder.encode(mUserName);
    String cs = mUserName + ':' + mPassword;
    mAuthString = "Basic " + Base64.encodeToString(cs.getBytes(), Base64.NO_WRAP);
    mCmdString = "&User=" + safeUserName + "&DeviceId=" + mDeviceId + "&DeviceType=" + mDeviceType;
}

From source file:org.cryptsecure.Utility.java

/**
 * Convert string to BASE64//from  w w w  . ja  va 2s.  c  om
 * 
 * @param originalString
 *            the original string
 * @return the string
 */
public static String convertStringToBASE64(String originalString) {
    return Base64.encodeToString(originalString.getBytes(), Base64.DEFAULT);
}

From source file:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * If there is a saved cert, checks the one given against it. If a signature was passed in
 * and no saved cert, then check that signature. Otherwise, presents the
 * given cert's signature to the user for approval.
 * /*from  w  w w  .  j  a v  a2 s.  c  om*/
 * The saved data must always win over any passed-in URI data
 * 
 * @param cert the given cert.
 */
private void validateX509Cert(final X509Certificate cert) {

    boolean certMismatch = false;

    int hashAlg = connection.getIdHashAlgorithm();
    byte[] certData = null;
    boolean isSigEqual = false;
    try {
        certData = cert.getEncoded();
        isSigEqual = SecureTunnel.isSignatureEqual(hashAlg, connection.getIdHash(), certData);
    } catch (Exception ex) {
        ex.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
        return;
    }

    // If there is no saved cert, then if a signature was provided,
    // check the signature and save the cert if the signature matches.
    if (connection.getSshHostKey().equals("")) {
        if (!connection.getIdHash().equals("")) {
            if (isSigEqual) {
                Log.i(TAG, "Certificate validated from URI data.");
                saveAndAcceptCert(cert);
                return;
            } else {
                certMismatch = true;
            }
        }
        // If there is a saved cert, check against it.
    } else if (connection.getSshHostKey().equals(Base64.encodeToString(certData, Base64.DEFAULT))) {
        Log.i(TAG, "Certificate validated from saved key.");
        saveAndAcceptCert(cert);
        return;
    } else {
        certMismatch = true;
    }

    // Show a dialog with the key signature for approval.
    DialogInterface.OnClickListener signatureNo = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // We were told not to continue, so stop the activity
            Log.i(TAG, "Certificate rejected by user.");
            closeConnection();
            ((Activity) getContext()).finish();
        }
    };
    DialogInterface.OnClickListener signatureYes = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.i(TAG, "Certificate accepted by user.");
            saveAndAcceptCert(cert);
        }
    };

    // Display dialog to user with cert info and hash.
    try {
        // First build the message. If there was a mismatch, prepend a warning about it.
        String message = "";
        if (certMismatch) {
            message = getContext().getString(R.string.warning_cert_does_not_match) + "\n\n";
        }
        byte[] certBytes = cert.getEncoded();
        String certIdHash = SecureTunnel.computeSignatureByAlgorithm(hashAlg, certBytes);
        String certInfo = String.format(Locale.US, getContext().getString(R.string.info_cert_tunnel),
                certIdHash, cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName(),
                cert.getNotBefore(), cert.getNotAfter());
        certInfo = message + certInfo.replace(",", "\n");

        // Actually display the message
        Utils.showYesNoPrompt(getContext(),
                getContext().getString(R.string.info_continue_connecting) + connection.getAddress() + "?",
                certInfo, signatureYes, signatureNo);
    } catch (NoSuchAlgorithmException e2) {
        e2.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
}

From source file:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * Saves and accepts a x509 certificate.
 * @param cert/*from  w w  w  . ja  va  2s.c om*/
 */
private void saveAndAcceptCert(X509Certificate cert) {
    String certificate = null;
    try {
        certificate = Base64.encodeToString(cert.getEncoded(), Base64.DEFAULT);
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
    connection.setSshHostKey(certificate);
    connection.save(database.getWritableDatabase());
    database.close();
    // Indicate the certificate was accepted.
    certificateAccepted = true;
    synchronized (RemoteCanvas.this) {
        RemoteCanvas.this.notifyAll();
    }
}

From source file:com.annanovas.bestprice.DashBoardEditActivity.java

public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality) {
    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    image.compress(compressFormat, quality, byteArrayOS);
    return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}

From source file:org.cryptsecure.Utility.java

/**
 * Gets the resized image as BASE64 string.
 * /*from  ww  w. j  ava  2  s  . c  o  m*/
 * @param context
 *            the context
 * @param attachmentPath
 *            the attachment path
 * @param maxWidth
 *            the max width
 * @param maxHeight
 *            the max height
 * @param quality
 *            the quality
 * @return the resized image as bas e64 string
 */
public static String getResizedImageAsBASE64String(Context context, Bitmap bitmap, int maxWidth, int maxHeight,
        int quality, boolean clipped) {
    // byte[] bytes = Utility.getFile(attachmentPath);
    // Bitmap bitmap = Utility.getBitmapFromBytes(bytes);
    Bitmap resizedBitmap = Utility.getResizedImage(bitmap, maxWidth, maxHeight, false, clipped);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
    byte[] byteArray = stream.toByteArray();
    String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
    return encoded;
}

From source file:org.cryptsecure.Utility.java

/**
 * Reads a file and encodes the bytes with BASE64 for transmission.
 * //from   w  w w .  java  2 s.  c  o m
 * @param attachmentPath
 *            the attachment path
 * @return the encoded image
 */
public static String getEncodedFile(String attachmentPath) {
    try {
        byte[] bytes = getFile(attachmentPath);
        String encodedFile = Base64.encodeToString(bytes, Base64.DEFAULT);
        return encodedFile;
    } catch (Exception e) {
        // Ignore, return null
        e.printStackTrace();
    }
    return null;
}

From source file:com.colorchen.qbase.utils.FileUtil.java

public static String file2Base64(String filePath) {
    FileInputStream fis = null;/*from w  ww.  j  ava  2 s  . c om*/
    String base64String = "";
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        fis = new FileInputStream(filePath);
        byte[] buffer = new byte[1024 * 100];
        int count = 0;
        while ((count = fis.read(buffer)) != -1) {
            bos.write(buffer, 0, count);
        }
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    base64String = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
    return base64String;

}

From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java

/**
 * For pphone protocol ,callback the purchase result
 * be invoked by Billingpphone purchase result interface.
 * @param bSuccess//w w  w  .j a v a2  s.c  o m
 * @param rsReceipt
 * @param strPurchaseGameSessionId
 */
public void notifyPurchaseResultByPphone(boolean bSuccess, String rsReceipt, String strPurchaseGameSessionId) {
    DebugLog.d(TAG, "call notifyPurchaseResultBypphone() bSuccess = " + bSuccess);
    String strCbPurchaseResult = "";
    if (bSuccess && rsReceipt != null && !"".equals(rsReceipt)) {
        byte[] licenseBytes = rsReceipt.getBytes();
        String base64license = Base64.encodeToString(licenseBytes, Base64.DEFAULT);
        strCbPurchaseResult = "{\"id\": \"" + strPurchaseGameSessionId + "\",\"type\": \"result\",\"code\": \""
                + Constants.RESPONSE_200 + "\",\"message\": \"success\"}";
        mReceiptMap.put(strPurchaseGameSessionId, base64license);

    } else {
        strCbPurchaseResult = "{\"id\": \"" + strPurchaseGameSessionId + "\",\"type\": \"result\",\"code\": \""
                + Constants.RESPONSE_600 + "\",\"message\": \"failure\"}";

    }
    DebugLog.d(TAG, "call notifyPurchaseResultBypphone() ubiGCPlayerCallback result = " + strCbPurchaseResult);
    ubiGCPlayerCallback("purchaseInApp", strCbPurchaseResult);
}

From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java

/**
 * Client -> client - >WebServer/*w  w w.j a  va  2  s  . c o  m*/
 * BillingActivity
 * get the purchase result from billingActivity
 * will put the result to local receiptMap
 * @param bSuccess
 * @param license
 * @param strId ----session id (req -> res)
 */
public void notifyPurchaseResult(boolean bSuccess, String license, String strId) {
    DebugLog.d(TAG, "call notifyPurchaseResult() bSuccess = " + bSuccess);
    String request;
    /**
    {
        "id": "dsfdh34576dfgg76",
        "type": "result",
        "code": "200",
        "message": "success",
        "receipt": "xxxxx" //this xxxx stands for the base64 encoded license string
    }    
    */
    if (bSuccess && license != null) {

        byte[] licenseBytes = license.getBytes();
        String base64license = Base64.encodeToString(licenseBytes, Base64.DEFAULT);
        //request = "{\"id\": \""+ strId + "\",\"type\": \"result\",\"code\": \""+Constants.RESPONSE_200+"\",\"message\": \"success\",\"receipt\": \"" + base64license + "\"}";
        request = "{\"id\": \"" + strId + "\",\"type\": \"result\",\"code\": \"" + Constants.RESPONSE_200
                + "\",\"message\": \"success\"}";
        mReceiptMap.put(strId, base64license);
    } else {

        request = "{\"id\": \"" + strId + "\",\"type\": \"result\",\"code\": \"" + Constants.RESPONSE_500
                + "\",\"message\": \"failure\"}";
    }

    DebugLog.d(TAG, "javascript:playerNotification.notifyPurchaseResult. request = " + request);

    ubiGCPlayerCallback("purchaseInApp", request);

    mBillingStatus = Constants.BILLING_STATUS_END;
    sIsBillingTriggered = false;
}