Example usage for android.util Base64 NO_WRAP

List of usage examples for android.util Base64 NO_WRAP

Introduction

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

Prototype

int NO_WRAP

To view the source code for android.util Base64 NO_WRAP.

Click Source Link

Document

Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).

Usage

From source file:in.neoandroid.neoupdate.neoUpdate.java

private boolean checkSignature(String jsonContent, String sign) {
    Log.d(TAG, "JSON: " + jsonContent);

    if (sign == null)
        return false;
    final String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+6EG/fAE+zIdh5Wzqnf"
            + "Fo4nCf7t7eJcKyvk1lqX1MdkIi/fUs8HQ4aQ4jWLCO4M1Gkz1FQiXOnheGLV5MXY"
            + "c9GyaglsofvpA/pU5d16FybX2pCevbTzcm39eU+XlwQWOr8gh23tYD8G6uMX6sIJ"
            + "W+1k1FWdud9errMVm0YUScI+J4AV5xzN0IQ29h9IeNp6oFqZ2ByWog6OBMTUDFIW"
            + "q8oRvH0OuPv3zFR5rKwsbTYb5Da8lhUht04dLBA860Y4zeUu98huvS9jQPu2N4ns"
            + "Hf425FfDJ/wae+7eLdQo7uFb+Wvc+PO9U39e6vXQfa8ZkUoXHD0XZN4jsFcKYuJw" + "OwIDAQAB";
    try {//w ww.  j av  a 2s.  c  o m
        byte keyBytes[] = Base64.decode(publicKeyStr.getBytes(), Base64.NO_WRAP);

        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey publicKey = kf.generatePublic(publicSpec);

        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(publicKey);
        signer.update(jsonContent.getBytes(), 0, jsonContent.length());

        return signer.verify(Base64.decode(sign, Base64.NO_WRAP));
    } catch (Exception e) {
    }
    return false;
}

From source file:org.gluu.com.ox_push2.u2f.v2.SoftwareDevice.java

public TokenResponse sign(String jsonRequest, String origin, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Starting to process sign request: " + jsonRequest);
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    JSONArray authenticateRequestArray = null;
    if (request.has("authenticateRequests")) {
        authenticateRequestArray = request.getJSONArray("authenticateRequests");
        if (authenticateRequestArray.length() == 0) {
            throw new U2FException("Failed to get authentication request!");
        }//from   w  w  w.  ja v  a  2 s  .co m
    } else {
        authenticateRequestArray = new JSONArray();
        authenticateRequestArray.put(request);
    }

    Log.i(TAG, "Found " + authenticateRequestArray.length() + " authentication requests");

    AuthenticateResponse authenticateResponse = null;
    String authenticatedChallenge = null;
    JSONObject authRequest = null;
    for (int i = 0; i < authenticateRequestArray.length(); i++) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Process authentication request: " + authRequest);
        authRequest = (JSONObject) authenticateRequestArray.get(i);

        if (!authRequest.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
            throw new U2FException("Unsupported U2F_V2 version!");
        }

        String version = authRequest.getString(JSON_PROPERTY_VERSION);
        String appParam = authRequest.getString(JSON_PROPERTY_APP_ID);
        String challenge = authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE);
        byte[] keyHandle = Base64.decode(authRequest.getString(JSON_PROPERTY_KEY_HANDLE),
                Base64.URL_SAFE | Base64.NO_WRAP);

        authenticateResponse = u2fKey.authenticate(new AuthenticateRequest(version,
                AuthenticateRequest.USER_PRESENCE_SIGN, challenge, appParam, keyHandle));
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Authentication response: " + authenticateResponse);
        if (authenticateResponse != null) {
            authenticatedChallenge = challenge;
            break;
        }
    }

    if (authenticateResponse == null) {
        return null;
    }

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, AUTHENTICATE_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_AUTHENTICATE);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE));
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String keyHandle = authRequest.getString(JSON_PROPERTY_KEY_HANDLE);
    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeAuthenticateResponse(authenticateResponse);

    JSONObject response = new JSONObject();
    response.put("signatureData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("keyHandle", keyHandle);

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(authenticatedChallenge);
    tokenResponse.setKeyHandle(keyHandle);

    return tokenResponse;
}

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

public NetworkPackage encrypt(PublicKey publicKey) throws GeneralSecurityException {

    String serialized = serialize();

    int chunkSize = 128;

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    JSONArray chunks = new JSONArray();
    while (serialized.length() > 0) {
        if (serialized.length() < chunkSize) {
            chunkSize = serialized.length();
        }/*from   w w  w . j  a  v a2s  . c o  m*/
        String chunk = serialized.substring(0, chunkSize);
        serialized = serialized.substring(chunkSize);
        byte[] chunkBytes = chunk.getBytes(Charset.defaultCharset());
        byte[] encryptedChunk;
        encryptedChunk = cipher.doFinal(chunkBytes);
        chunks.put(Base64.encodeToString(encryptedChunk, Base64.NO_WRAP));
    }

    //Log.i("NetworkPackage", "Encrypted " + chunks.length()+" chunks");

    NetworkPackage encrypted = new NetworkPackage(NetworkPackage.PACKAGE_TYPE_ENCRYPTED);
    encrypted.set("data", chunks);
    encrypted.setPayload(mPayload, mPayloadSize);
    return encrypted;

}

From source file:com.adeven.adjustio.PackageBuilder.java

private void addMap(Map<String, String> parameters, String key, Map<String, String> map) {
    if (null == map) {
        return;//from   ww  w.  java  2 s  .  c o m
    }

    JSONObject jsonObject = new JSONObject(map);
    byte[] jsonBytes = jsonObject.toString().getBytes();
    String encodedMap = Base64.encodeToString(jsonBytes, Base64.NO_WRAP);

    addString(parameters, key, encodedMap);
}

From source file:com.mimo.service.api.MimoOauth2Client.java

/**
 * This function calls the Mimo Server along with the client info and server
 * authenticates the client and returns a valid access_token
 * //from  www . j  a v  a 2 s  .  c o  m
 * @param p_code
 *            : code received from the Mimo Server
 * 
 * @return <b>m_token</b> : is the access token returned from the server
 **/
private String requesttoken(String p_code) {
    String m_loadUrl = m_api.requesttoken(p_code);

    DefaultHttpClient m_httpClient = new DefaultHttpClient();
    HttpPost m_post = new HttpPost(m_loadUrl);

    // String m_authString = "mimo:mimo";
    String m_authString = MimoAPIConstants.USERNAME + ":" + MimoAPIConstants.PASSWORD;

    String m_authStringEnc = Base64.encodeToString(m_authString.getBytes(), Base64.NO_WRAP);
    m_post.addHeader(MimoAPIConstants.HEADER_TEXT_AUTHORIZATION,
            MimoAPIConstants.HEADER_TEXT_BASIC + m_authStringEnc);

    HttpResponse m_response = null;

    String m_token = null;

    try {
        m_response = m_httpClient.execute(m_post);

        JSONObject m_jsonResp;
        try {
            m_jsonResp = new JSONObject(convertStreamToString(m_response.getEntity().getContent()));
            // m_token = m_jsonResp.getString("access_token");
            m_token = m_jsonResp.getString(MimoAPIConstants.GET_ACCESS_TOKEN);
            if (MimoAPIConstants.DEBUG) {
                Log.d(TAG + "Access Token", m_token);
            }
            return m_token;
        } catch (IllegalStateException p_e) {
            if (MimoAPIConstants.DEBUG) {
                Log.e(TAG, p_e.getMessage());
            }
        } catch (JSONException p_e) {
            if (MimoAPIConstants.DEBUG) {
                Log.e(TAG, p_e.getMessage());
            }
        }

    } catch (ClientProtocolException p_e) {
        if (MimoAPIConstants.DEBUG) {
            Log.e(TAG, p_e.getMessage());
        }
    } catch (IOException p_e) {
        if (MimoAPIConstants.DEBUG) {
            Log.e(TAG, p_e.getMessage());
        }
    }

    return "";
}

From source file:com.etalio.android.EtalioExtendedAPI.java

private boolean privateSignIn(byte[] body) throws IOException, EtalioHttpException, EtalioTokenException {
    Log.v(SDK_TAG, "privateSignIn");
    Map<String, String> headers = new HashMap<String, String>();
    addEtalioUserAgent(headers);//w  ww.  j  av  a 2 s.  co  m
    String authenticationString = mClientId + ":" + mClientSecret;
    String authenticationString64 = Base64.encodeToString(authenticationString.getBytes(), Base64.NO_WRAP);
    headers.put("Authorization", "Basic " + authenticationString64);
    Log.v(TAG, "privateSignIn:: POST " + authenticationString + " " + getUrl("token", null) + " "
            + new String(body, "UTF-8"));
    HttpRequest request = new HttpRequest(HttpRequest.HttpMethod.POST, getUrl("token", null), headers, body,
            CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED, body.length);
    HttpResponse<TokenResponse> response = null;
    response = getHttpClient().executeRequest(request, new GsonHttpBodyConverter<TokenResponse>(),
            TokenResponse.class);
    Log.v(TAG, "privateSignIn::" + response.getStatus() + " : "
            + new String(getHttpBodyConverter().toBody(response.getBody(), "UTF-8"), "UTF-8"));
    updateEtalioToken(response);
    return true;
}

From source file:com.evothings.BLE.java

public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
    if (mScanCallbackContext == null) {
        return;//from  ww  w .ja v a 2s. c  om
    }
    try {
        //System.out.println("onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
        JSONObject o = new JSONObject();
        o.put("address", device.getAddress());
        o.put("rssi", rssi);
        o.put("name", device.getName());
        o.put("scanRecord", Base64.encodeToString(scanRecord, Base64.NO_WRAP));
        keepCallback(mScanCallbackContext, o);
    } catch (JSONException e) {
        mScanCallbackContext.error(e.toString());
    }
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

public static byte[] encodeStringToBase64Bytes(String string) {
    try {//from  w w w.  ja  va2 s.co m
        return Base64.encode(string.getBytes(), Base64.NO_WRAP);
    } catch (Exception e) {
        return new byte[0];
    }
}

From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Get the cipher for the key protecting the saved password for a file
 *//*w ww  . j a va  2s  .  com*/
@TargetApi(Build.VERSION_CODES.M)
private Cipher getKeyCipher(Uri fileUri, boolean encrypt) throws CertificateException, NoSuchAlgorithmException,
        KeyStoreException, IOException, UnrecoverableKeyException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    String keyName = getPrefsKey(fileUri);
    KeyStore keystore = getKeystore();
    Key key = keystore.getKey(keyName, null);
    if (key == null) {
        throw new IOException(itsContext.getString(R.string.key_not_found, fileUri));
    }

    Cipher ciph = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
            + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    if (encrypt) {
        ciph.init(Cipher.ENCRYPT_MODE, key);
    } else {
        SharedPreferences prefs = getPrefs();
        String ivStr = prefs.getString(getIvPrefsKey(keyName), null);
        if (TextUtils.isEmpty(ivStr)) {
            throw new IOException("Key IV not found for " + fileUri);
        }
        byte[] iv = Base64.decode(ivStr, Base64.NO_WRAP);
        ciph.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
    }
    return ciph;
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

public static String decodeBase64BytesToString(byte[] bytes) {
    try {/*from   ww w .  j  ava  2  s . c  o m*/
        return new String(Base64.decode(bytes, Base64.NO_WRAP));
    } catch (Exception e) {
        return "";
    }
}