예제 #1
1
  public static void logTokens(Activity context) {

    // Add code to print out the key hash
    try {
      PackageInfo info =
          context
              .getPackageManager()
              .getPackageInfo(
                  context.getApplicationContext().getPackageName(), PackageManager.GET_SIGNATURES);
      for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(signature.toByteArray());
        Log.d("SHA-KeyHash:::", Base64.encodeToString(md.digest(), Base64.DEFAULT));

        md = MessageDigest.getInstance("MD5");
        md.update(signature.toByteArray());
        Log.d("MD5-KeyHash:::", Base64.encodeToString(md.digest(), Base64.DEFAULT));

        md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("SHA-Hex-From-KeyHash:::", bytesToHex(md.digest()));
      }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }
  }
예제 #2
0
 public void testMakeUriString() throws IOException {
   // Simple user name and command
   EasSyncService svc = setupService(USER);
   String uriString = svc.makeUriString("Sync", null);
   // These next two should now be cached
   assertNotNull(svc.mAuthString);
   assertNotNull(svc.mUserString);
   assertEquals(
       "Basic " + Base64.encodeToString((USER + ":" + PASSWORD).getBytes(), Base64.NO_WRAP),
       svc.mAuthString);
   assertEquals(
       "&User="******"&DeviceId=" + ID + "&DeviceType=" + EasSyncService.DEVICE_TYPE,
       svc.mUserString);
   assertEquals(
       "https://" + HOST + "/Microsoft-Server-ActiveSync?Cmd=Sync" + svc.mUserString, uriString);
   // User name that requires encoding
   String user = "******";
   svc = setupService(user);
   uriString = svc.makeUriString("Sync", null);
   assertEquals(
       "Basic " + Base64.encodeToString((user + ":" + PASSWORD).getBytes(), Base64.NO_WRAP),
       svc.mAuthString);
   String safeUserName = "******";
   assertEquals(
       "&User="******"&DeviceId=" + ID + "&DeviceType=" + EasSyncService.DEVICE_TYPE,
       svc.mUserString);
   assertEquals(
       "https://" + HOST + "/Microsoft-Server-ActiveSync?Cmd=Sync" + svc.mUserString, uriString);
 }
예제 #3
0
  public void selectProfilePicture(Intent data) {

    Uri selectedImage = data.getData();

    try {

      Bitmap finalImage = ImageHandler.getPortraitImage(selectedImage, getActivity(), 300, 200);
      profilePicture.setImageBitmap(finalImage);

      Bitmap thumbNail = ImageHandler.getPortraitImage(selectedImage, getActivity(), 35, 23);

      // http://stackoverflow.com/questions/26292969/can-i-store-image-files-in-firebase-using-java-api
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      finalImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
      String imageString = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);

      stream.reset();
      thumbNail.compress(Bitmap.CompressFormat.PNG, 100, stream);
      String thumbNString = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);

      MainActivity.getUser().setProfilePicture(imageString, stream.toByteArray());
      stream.close();

      new FbDataChange("/users/" + MainActivity.getUser().getUid() + "/profilePicture", imageString)
          .execute();

      new FbDataChange("/users/" + MainActivity.getUser().getUid() + "/profileThumb", thumbNString)
          .execute();
    } catch (IOException e) {
    }
  }
예제 #4
0
 /**
  * Encodes this ciphertext, IV, mac as a string.
  *
  * @return base64(iv) : base64(mac) : base64(ciphertext). The iv and mac go first because
  *     they're fixed length.
  */
 @Override
 public String toString() {
   String ivString = Base64.encodeToString(iv, BASE64_FLAGS);
   String cipherTextString = Base64.encodeToString(cipherText, BASE64_FLAGS);
   String macString = Base64.encodeToString(mac, BASE64_FLAGS);
   return String.format(ivString + ":" + macString + ":" + cipherTextString);
 }
예제 #5
0
    @Override
    public void run() {
      int ret = 1;
      ret = OpenModule();
      if (ret != 0) {
        if (callback != null) {
          callback.onFail(-884, "指纹模块打开失败");
        }
        api.IDCard_Close();
        m_bThreadFinished = true;
        return;
      }
      if (callback != null) {
        callback.onStart();
      }
      try {
        synchronized (this) {
          while (runFlag) {
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            APDU_RESP ApduResp_TCD = new APDU_RESP();
            ret = api.TCD_Read_Test(ApduResp_TCD);
            if (0 == ret) {
              String strInfo = "";
              byte[] fingerByte = new byte[ApduResp_TCD.LenOut];
              try {
                System.arraycopy(ApduResp_TCD.DataOut, 0, fingerByte, 0, ApduResp_TCD.LenOut);
                Log.e("fingerCode:", ByteTool.byte2hex(fingerByte));
                if (fingerType == Config.WELL_FINGER) {
                  strInfo = FingerUnit.parseWellcom(fingerByte);
                } else if (fingerType == Config.SHENGYE_FINGER) {
                  strInfo = Base64.encodeToString(fingerByte, Base64.NO_WRAP);
                } else {
                  strInfo = Base64.encodeToString(fingerByte, Base64.NO_WRAP);
                }
              } catch (ArrayIndexOutOfBoundsException e) {
                continue;
              }
              callback.onRead(strInfo);
              runFlag = false;
              break;
            } else {

              // callback.onFail(ret, "未读取到指纹");
            }
          }
        }
      } finally {
        m_bThreadFinished = true;
      }
    }
예제 #6
0
  @Override
  public void requestPurchase(String sku) {
    try {
      SecureRandom sr;
      sr = SecureRandom.getInstance("SHA1PRNG");
      String uniqueId = Long.toHexString(sr.nextLong());

      JSONObject purchaseRequest = new JSONObject();
      purchaseRequest.put("uuid", uniqueId);
      purchaseRequest.put("identifier", sku);
      purchaseRequest.put("testing", TESTING);

      String purchaseRequestJson = purchaseRequest.toString();

      byte[] keyBytes = new byte[16];
      sr.nextBytes(keyBytes);
      SecretKey key = new SecretKeySpec(keyBytes, "AES");

      byte[] ivBytes = new byte[16];
      sr.nextBytes(ivBytes);
      IvParameterSpec iv = new IvParameterSpec(ivBytes);

      Cipher cipher;
      cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
      cipher.init(Cipher.ENCRYPT_MODE, key, iv);
      byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

      cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
      cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
      byte[] encryptedKey = cipher.doFinal(keyBytes);

      Purchasable purchasable =
          new Purchasable(
              sku,
              Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
              Base64.encodeToString(ivBytes, Base64.NO_WRAP),
              Base64.encodeToString(payload, Base64.NO_WRAP));

      //            synchronized (mOutstandingPurchaseRequests) {
      //                mOutstandingPurchaseRequests.put(uniqueId, product);
      //            }

      OuyaFacade.getInstance().requestPurchase(purchasable, this);

    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
예제 #7
0
 public static String encodeToString(byte[] input, int flags) {
   boolean websafeDesired = true;
   if (getSdkVersion() >= 8) {
     int newFlags = URL_SAFE;
     if ((flags & NO_PADDING) != 0) {
       newFlags = URL_SAFE | NO_PADDING;
     }
     if ((flags & URL_SAFE) != 0) {
       newFlags |= 8;
     }
     return Base64.encodeToString(input, newFlags);
   }
   boolean paddingDesired;
   if ((flags & NO_PADDING) == 0) {
     paddingDesired = true;
   } else {
     paddingDesired = false;
   }
   if ((flags & URL_SAFE) == 0) {
     websafeDesired = false;
   }
   if (websafeDesired) {
     return Base64.encodeWebSafe(input, paddingDesired);
   }
   return Base64.encode(input, paddingDesired);
 }
예제 #8
0
    @Override
    protected String doInBackground(String... urls) {

      for (String url : urls) {
        try {
          user_name = uname.getText().toString();
          HttpClient client = new DefaultHttpClient();
          String getURL = url;
          HttpGet get = new HttpGet(getURL);
          auth =
              Base64.encodeToString(((user_name + ":" + pwd.getText()).getBytes()), Base64.NO_WRAP);
          Log.d("auth", auth);
          get.addHeader("Authorization", "Basic " + auth);
          if (get.containsHeader("Authorization")) Log.d("get", "yes");
          HttpResponse responseGet = client.execute(get);
          HttpEntity resEntityGet = responseGet.getEntity();
          response = EntityUtils.toString(resEntityGet);
          Log.d("response", response);
        } catch (Exception e) {
          e.printStackTrace();
        }
        if (response.compareTo("1") == 0) {
          Log.d("auth", "Autheticated!");
        } else {
          Log.d("auth", "Authetication failed!");
        }
      }
      return response;
    }
예제 #9
0
  @Override
  public void onCreate() {
    super.onCreate();
    mInstance = this;

    AnalyticsTrackers.initialize(this);
    AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP);

    /*facebook*/
    FacebookSdk.sdkInitialize(getApplicationContext());
    try {
      PackageInfo info =
          getPackageManager()
              .getPackageInfo(
                  "com.jukesolutions.olahdana", // replace with your unique package name
                  PackageManager.GET_SIGNATURES);
      for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
      }
    } catch (PackageManager.NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }
  }
예제 #10
0
  private static void performDownload(
      Context ctx,
      BaseEntity content,
      List<NameValuePair> additionalParams,
      final OnDownloadResult callback) {
    String basicAuthBase64 = null;
    if (BASICAUTH != null)
      basicAuthBase64 = Base64.encodeToString(BASICAUTH.getBytes(), Base64.NO_WRAP);

    DownloadAsyncTask dlTask =
        new DownloadAsyncTask(
            URL,
            basicAuthBase64,
            WEBTASK_GETDOWNLOAD,
            TOKEN,
            additionalParams,
            ctx,
            content,
            callback);
    dlTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);

    if (activeDownloads == null) {
      activeDownloads = new ArrayList<DownloadAsyncTask>();
    }
    activeDownloads.add(dlTask);
  }
예제 #11
0
  /**
   * Provides the key hash to solve the openSSL issue with Amazon
   *
   * @return key hash
   */
  @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 "";
  }
예제 #12
0
  public static String getApplicationSignature(Context context) {
    if (context == null) {
      return null;
    }
    PackageManager packageManager = context.getPackageManager();
    if (packageManager == null) {
      return null;
    }

    String packageName = context.getPackageName();
    PackageInfo pInfo;
    try {
      pInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException e) {
      return null;
    }

    Signature[] signatures = pInfo.signatures;
    if (signatures == null || signatures.length == 0) {
      return null;
    }

    MessageDigest md;
    try {
      md = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
      return null;
    }

    md.update(pInfo.signatures[0].toByteArray());
    return Base64.encodeToString(md.digest(), Base64.URL_SAFE | Base64.NO_PADDING);
  }
예제 #13
0
 public String getStringImage(Bitmap bmp) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
   byte[] imageBytes = baos.toByteArray();
   String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
   return encodedImage;
 }
 public JSONObject toJSON() {
   JSONObject domainObject = new JSONObject();
   try {
     domainObject.put("domain", this.getDomain());
     if (this.url != null && this.url.length() > 0) {
       domainObject.put("url", this.getUrl());
     }
     if (this.username != null && this.username.length() > 0) {
       domainObject.put("username", this.getUsername());
     }
     if (this.legacyPassword != null && this.legacyPassword.length() > 0) {
       domainObject.put("legacyPassword", this.getLegacyPassword());
     }
     if (this.notes != null && this.notes.length() > 0) {
       domainObject.put("notes", this.getNotes());
     }
     domainObject.put("iterations", this.getIterations());
     domainObject.put("salt", Base64.encodeToString(this.getSalt(), Base64.DEFAULT));
     domainObject.put("length", this.getLength());
     domainObject.put("cDate", this.getCreationDate());
     domainObject.put("mDate", this.getModificationDate());
     domainObject.put("usedCharacters", this.getCharacterSetAsString());
     domainObject.put("extras", this.getExtraCharacterSetAsString());
     if (this.forceCharacterClasses) {
       domainObject.put("passwordTemplate", this.getFullTemplate());
     }
   } catch (JSONException e) {
     System.out.println("Settings packing error: Unable to pack the JSON data.");
   }
   return domainObject;
 }
예제 #15
0
  public static BankSession newInstance(Context context, String username, String password) {
    // Get the session id from the store if possible, otherwise log in
    SharedPreferences p = context.getSharedPreferences(PaymentsActivity.PREFS_NAME, 0);
    String sessionId = null;
    String savedUsername = p.getString("username", null);
    MessageDigest md;
    try {
      md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
      Log.e(TAG, "SHA-256 not supported", e);
      return null;
    }
    md.update(password.getBytes());
    String hashedPassword = Base64.encodeToString(md.digest(), Base64.DEFAULT);
    String savedPassword = p.getString("password", null);
    if (username.equals(savedUsername) && hashedPassword.equals(savedPassword)) {
      sessionId = p.getString("session_id", null);
    }

    // Session id not available
    if (sessionId == null) {
      sessionId = login(username, password);
      if (sessionId != null) {
        p.edit().putString("session_id", sessionId);
        p.edit().putString("username", username);
        p.edit().putString("password", hashedPassword);
      }
    }
    return new BankSession(sessionId);
  }
예제 #16
0
  /**
   * Get the signing key unique to this installation, or create it if it doesn't exist. The purpose
   * of this key is to allow signing of backup files (and any other such files) to ensure they are
   * not modified by some other program. Of course, if the other program has root then it can modify
   * or read this key anyway, so all bets are off.
   *
   * @return secret key for signing and verification
   */
  public SecretKey getOrCreateSigningKey() {
    String signingKey = this.prefs.getString(BACKUP_SIGNING_KEY, null);
    SecretKey secretKey = null;
    if (signingKey != null) {
      secretKey =
          new SecretKeySpec(
              Base64.decode(signingKey, Base64.DEFAULT),
              0,
              Base64.decode(signingKey, Base64.DEFAULT).length,
              "HmacSHA1");
    } else {
      // supporting multiple algorithms would be good, but then we also need to store the key
      // type...
      try {
        secretKey = KeyGenerator.getInstance("HmacSHA1").generateKey();
      } catch (NoSuchAlgorithmException e) {
      }

      Editor editor = this.prefs.edit();
      editor.putString(
          BACKUP_SIGNING_KEY, Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT));
      editor.commit();
    }

    return secretKey;
  }
  public static String convertBitmapToBase64(Bitmap bitmap) {
    final int size = bitmap.getByteCount();

    ByteBuffer dst = ByteBuffer.allocate(size);
    bitmap.copyPixelsToBuffer(dst);
    return Base64.encodeToString(dst.array(), Base64.DEFAULT);
  }
예제 #18
0
 private String createSecret() {
   byte[] nonce = new byte[16];
   for (int i = 0; i < 16; i++) {
     nonce[i] = (byte) (Math.random() * 256);
   }
   return Base64.encodeToString(nonce, Base64.DEFAULT).trim();
 }
예제 #19
0
  /**
   * 使用口令加密私钥(Base64编码)
   *
   * @return
   */
  public String encryptPrivateKey(String passphrase) {
    byte[] seeds = null;
    byte[] raw = mMyPrivKey.getEncoded();
    byte[] encrypted = null;

    Cipher cipher;
    try {
      seeds = getRawKey(passphrase.getBytes());
      SecretKeySpec skeySpec = new SecretKeySpec(seeds, PASS_ALGO);
      cipher = Cipher.getInstance(PASS_ALGO);
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      encrypted = cipher.doFinal(raw);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    String result = Base64.encodeToString(encrypted, Base64.DEFAULT);
    return result;
  }
예제 #20
0
  public static List<Tweet> getTweetsOfUser(String userName) {
    try {
      // Step 1: Encode consumer key and secret
      final String urlApiKey = URLEncoder.encode(Constants.Twitter.API_KEY, "UTF-8");
      final String urlApiSecret = URLEncoder.encode(Constants.Twitter.API_SECRET, "UTF-8");

      // Concatenate the encoded consumer key, a colon character, and the
      // encoded consumer secret
      final String combined = urlApiKey + ":" + urlApiSecret;

      // Base64 encode the string
      final String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

      // Retrieve the raw authorization token from Twitter
      final TwitterAuthenticated auth = getTwitterAuthentication(base64Encoded);

      // Applications should verify that the value associated with the
      // token_type key of the returned object is bearer
      if ((null != auth) && (null != auth.token_type) && (auth.token_type.equals("bearer"))) {
        return getTweets(userName, auth.access_token);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return getFakeTweets();
  }
예제 #21
0
  // getting authorisation token
  private AuthToken getAuthToken() {
    AuthToken token = null;
    try {
      String urlApiKey = URLEncoder.encode(Util.TwitterKey, "UTF-8");
      String urlApiSecret = URLEncoder.encode(Util.TwitterSecret, "UTF-8");
      String combined = urlApiKey + ":" + urlApiSecret;
      String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

      HttpPost httpPost = new HttpPost(TwitterTokenURL);
      httpPost.setHeader("Authorization", "Basic " + base64Encoded);
      httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
      httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
      String rawAuthorization = getResponseBody(httpPost);

      // decoding authentication token
      JSONObject jObj = new JSONObject(rawAuthorization);
      token = new AuthToken();
      token.setTokenType(jObj.getString("token_type"));
      token.setAccessToken(jObj.getString("access_token"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return token;
  }
예제 #22
0
파일: Utils.java 프로젝트: ppbox/webrtc-qt
  /**
   * 将图片转化为Base64的格式
   *
   * @param imgPath 图片的路径
   * @return 返回图片的String类型
   */
  public static String imageToBase64(String imgPath) {
    Bitmap bitmap = null;
    if (imgPath != null && imgPath.length() > 0) {
      bitmap = readBitmap(imgPath);
    }
    if (bitmap == null) {
      return null;
    }
    ByteArrayOutputStream out = null;
    try {
      out = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

      out.flush();
      out.close();

      byte[] imgBytes = out.toByteArray();
      return Base64.encodeToString(imgBytes, Base64.DEFAULT);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      try {
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
예제 #23
0
  public static void report(String app, String deviceId, SocketPacket packet) {
    String address = "http://172.19.207.87:8080/report/socket/output";
    // 传参数 服务端获取的方法为request.getParameter("name")
    List<FormEntry> params = new ArrayList<FormEntry>();
    params.add(new FormEntry(FormEntry.Type.String, "app", app));
    params.add(new FormEntry(FormEntry.Type.String, "domain", packet.getDomain()));
    params.add(new FormEntry(FormEntry.Type.String, "host", packet.getHost()));
    params.add(new FormEntry(FormEntry.Type.String, "type", packet.getType()));
    params.add(
        new FormEntry(FormEntry.Type.String, "timestamp", Long.toString(packet.getTimestamp())));
    params.add(
        new FormEntry(
            FormEntry.Type.String,
            "data",
            Base64.encodeToString(packet.getBytes(), Base64.DEFAULT)));
    params.add(new FormEntry(FormEntry.Type.String, "deviceId", deviceId));
    // post
    AsyncHttp.post(
        address,
        params,
        new AsyncHttp.ResultCallback() {
          @Override
          public void onSuccess(String url, int statusCode, String result) {}

          @Override
          public void onFailure(String url, int statusCode, int errorType, Throwable throwable) {}
        });
  }
예제 #24
0
  private String encodeAndScaleImage(String imagePath) {

    Bitmap original = BitmapFactory.decodeFile(imagePath);
    if (original == null) return null;

    // the smallest size has to be constant
    // the other size should scale accordingly
    int width = original.getWidth();
    int height = original.getHeight();
    if (width <= height) {
      float ratio = (float) height / (float) width;
      width = Consts.THUMB_MIN_SIZE;
      height = (int) (width * ratio);
    } else {
      float ratio = (float) height / (float) width;
      height = Consts.THUMB_MIN_SIZE;
      width = (int) (height * ratio);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // if image is larger than 1024px X 1024px (by longest side)
    if (!(original.getWidth() < Consts.THUMB_MIN_SIZE
        || original.getHeight() < Consts.THUMB_MIN_SIZE)) {
      // resize picture to 1024px X 1024px (by longest side)
      Bitmap scaledBitmap = Bitmap.createScaledBitmap(original, width, height, true);
      scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    } else original.compress(Bitmap.CompressFormat.JPEG, 90, baos);

    byte[] byteArrayImage = baos.toByteArray();
    return Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
  }
  /**
   * Synchronous call for logging in
   *
   * @param httpBody
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws JSONException
   */
  public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    HttpsURLConnection connection = createSecureConnection(url);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
      LoggingUtils.d(LOG_TAG, connection.toString());
      response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
      LoggingUtils.e(
          LOG_TAG,
          "Error reading stream \""
              + connection.getInputStream()
              + "\". "
              + e.getLocalizedMessage(),
          null);
    } catch (IOException e) {
      response = readFromStream(connection.getErrorStream());
    } finally {
      connection.disconnect();
    }

    return response;
  }
예제 #26
0
  @Kroll.method
  public String encode(HashMap args) {
    // encode text to cipher text
    //
    KrollDict arg = new KrollDict(args);
    String txt = arg.getString("plainText");
    String keyString = arg.getString("publicKey");
    byte[] encodedBytes = null;
    Key key;

    try {
      byte[] encodedKey = Base64.decode(keyString, 0);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encodedKey);
      KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
      key = keyFact.generatePublic(x509KeySpec);
    } catch (Exception e) {
      return "error key";
    }

    try {
      Cipher c = Cipher.getInstance("RSA");
      c.init(Cipher.ENCRYPT_MODE, key);
      encodedBytes = c.doFinal(txt.getBytes());
    } catch (Exception e) {
      Log.e(TAG, "RSA encryption error " + e.toString());
    }

    return Base64.encodeToString(encodedBytes, Base64.NO_WRAP);
  }
예제 #27
0
  private void initQuery() throws IOException {
    Hashtable<String, String> map = new Hashtable<String, String>();
    map.put("uid", "TEMP_USER");
    map.put("pwd", "TEMP_PASSWORD");
    map.put(QUERY_PARAM, Base64.encodeToString(TEST_QUERY.getBytes(), 0));

    HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, ConnectionManager.DEFAULT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, ConnectionManager.DEFAULT_TIMEOUT);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create post method
    HttpPost postMethod = new HttpPost(QUERY_URI);

    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    ObjectOutputStream objOS = new ObjectOutputStream(byteArrayOS);
    objOS.writeObject(map);
    ByteArrayEntity req_entity = new ByteArrayEntity(byteArrayOS.toByteArray());
    req_entity.setContentType(MIMETypeConstantsIF.BINARY_TYPE);

    // associating entity with method
    postMethod.setEntity(req_entity);

    // Executing post method
    executeHttpClient(httpClient, postMethod);
  }
예제 #28
0
  private static String encrypt(String baseKey, byte[] src)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidAlgorithmParameterException {

    byte[] key = SHA256(baseKey);

    if (secureKey == null) {
      secureKey = new SecretKeySpec(key, "AES");
    }

    if (encryptor == null) {
      encryptor = Cipher.getInstance("AES/CBC/PKCS5Padding");
      encryptor.init(Cipher.ENCRYPT_MODE, secureKey, new IvParameterSpec(IV.getBytes()));
    }

    byte[] encrypted = null;

    try {
      encrypted = encryptor.doFinal(src);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
    return Base64.encodeToString(encrypted, Base64.NO_WRAP);
  }
예제 #29
0
 // convert bitmap to base64
 public static String bitmapToBase64(Bitmap bitmap) {
   String result = null;
   ByteArrayOutputStream baos = null;
   try {
     if (bitmap != null) {
       baos = new ByteArrayOutputStream();
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
       baos.flush();
       baos.close();
       byte[] bitmapBytes = baos.toByteArray();
       result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (baos != null) {
         baos.flush();
         baos.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return result;
 }
예제 #30
0
    public void processingFinished() {
      try {
        Bitmap result = (Bitmap) processing.get();

        // generate filename
        byte[] hashBytes = ByteBuffer.allocate(4).putInt(result.hashCode()).array();
        processed =
            Uri.parse(
                "/sdcard/Download/"
                    + Base64.encodeToString(hashBytes, Base64.URL_SAFE).trim()
                    + ".png");

        // save to file
        FileOutputStream out = null;
        try {
          out = new FileOutputStream(processed.getPath());
          result.compress(Bitmap.CompressFormat.PNG, 90, out);
          Log.d(TAG, "saved to " + processed);
        } catch (Exception e) {
          Log.e(TAG, Log.getStackTraceString(e));
        } finally {
          try {
            out.close();
          } catch (Throwable ignore) {
          }
        }

        double sx = noteList.getWidth();
        double sy = (noteList.getWidth() / result.getWidth()) * result.getHeight();
        interestingThumbnail(Bitmap.createScaledBitmap(result, (int) sx, (int) sy, false));
      } catch (Exception e) {
        Log.d(TAG, Log.getStackTraceString(e));
      }
    }