示例#1
0
 public static byte[] decode(String s, 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.decode(s, newFlags);
   }
   boolean paddingDesired;
   if ((flags & NO_PADDING) == 0) {
     paddingDesired = true;
   } else {
     paddingDesired = false;
   }
   if ((flags & URL_SAFE) == 0) {
     websafeDesired = false;
   }
   if (websafeDesired) {
     return Base64.decodeWebSafe(s);
   }
   return Base64.decode(s);
 }
  public byte[] new_decrypt_cn(E_CODE paramE_CODE, byte[] paramArrayOfByte)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
          InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    byte[] localObject = null;

    if (paramE_CODE == E_CODE.RSA) {
      if (rsa_key.length() > 2) {
        Cipher localCipher;
        byte[] arrayOfByte = new byte[0];
        //		    PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new
        // X509EncodedKeySpec(Base64.decodeBase64(rsa_key)));
        PublicKey localPublicKey =
            KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(Base64.decode(rsa_key, Base64.DEFAULT)));
        System.out.println("key  length-" + (Base64.decode(rsa_key, Base64.DEFAULT)).length);
        System.out.println("data length-" + paramArrayOfByte.length);
        localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher.init(Cipher.DECRYPT_MODE, localPublicKey);
        //		    localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);

        arrayOfByte = localCipher.doFinal(paramArrayOfByte);
        //		    int oldLength;
        //		    for (int i = 0; i < paramArrayOfByte.length; i += 8) {
        //		        byte[] temp = localCipher.doFinal(paramArrayOfByte, i, i + 8);
        //		        oldLength = arrayOfByte.length;
        //		        arrayOfByte  = Arrays.copyOf(arrayOfByte, temp.length+arrayOfByte.length);
        //		        System.arraycopy(temp, 0, arrayOfByte, oldLength, temp.length);
        //		    }

        //		    arrayOfByte = paramArrayOfByte;

        return arrayOfByte;
      }
    } else if (paramE_CODE == E_CODE.RSA_EP) {
      if (rsa_ep_key.length() >= 2) {
        //        PrivateKey localPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(new
        // PKCS8EncodedKeySpec(Base64.decodeBase64(rsa_ep_key)));
        PrivateKey localPrivateKey =
            KeyFactory.getInstance("RSA")
                .generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.decode(rsa_ep_key, Base64.DEFAULT)));
        Cipher localCipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher2.init(2, localPrivateKey);
        localObject = localCipher2.doFinal(paramArrayOfByte);
      }
    } else if (paramE_CODE == E_CODE.AES) {
      //      SecretKeySpec localSecretKeySpec = new
      // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES");
      //      byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte);
      SecretKeySpec localSecretKeySpec =
          new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES");
      byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT);
      Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding");
      localCipher1.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
      byte[] arrayOfByte2 = localCipher1.doFinal(arrayOfByte1);
      localObject = arrayOfByte2;
    }

    return localObject;
  }
示例#3
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;
  }
示例#4
0
  @Kroll.method
  public String decode(HashMap args) {
    // decode string back to plain text
    //
    KrollDict arg = new KrollDict(args);
    String txt = arg.getString("cipherText");
    byte[] bytesEncoded = Base64.decode(txt, 0);
    String keyString = arg.getString("privateKey");
    PrivateKey key;

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

    byte[] decodedBytes = null;

    try {
      Cipher c = Cipher.getInstance("RSA");
      c.init(Cipher.DECRYPT_MODE, key);
      decodedBytes = c.doFinal(bytesEncoded);
    } catch (Exception e) {
      Log.e(TAG, "RSA decryption error " + e.toString());
      return "error";
    }
    return new String(decodedBytes);
  }
  public CryptEngineImpl(Context ctx) throws Exception {

    // Получаем действующее хранилище
    IKeyStorage storage = KeyStorageFactory.getKeyStorage(ctx);

    Log.v("TFORWARD.CryptEngineImpl", "Decoding public key...");
    byte[] publicKey = Base64.decode(storage.getKey(IKeyStorage.PUBLIC_KEY_TYPE), Base64.DEFAULT);

    Log.v("TFORWARD.CryptEngineImpl", "Decoding ASN1 Structure");
    ASN1InputStream asnStream = new ASN1InputStream(publicKey);

    ASN1Sequence sequence = null;
    try {
      Log.v("TFORWARD.CryptEngineImpl", "Reading ASN1 Sequence");
      sequence = (ASN1Sequence) asnStream.readObject();
    } finally {
      asnStream.close();
    }

    Log.v("TFORWARD.CryptEngineImpl", "Creating certificate. " + sequence.size());
    Certificate certificate = Certificate.getInstance(sequence);
    SubjectPublicKeyInfo publicKeyInfo = certificate.getSubjectPublicKeyInfo();

    RSAPublicKey publicKeyStructure = RSAPublicKey.getInstance(publicKeyInfo.parsePublicKey());
    BigInteger mod = publicKeyStructure.getModulus();
    BigInteger pubExp = publicKeyStructure.getPublicExponent();

    publicRsaKey = new RSAKeyParameters(false, mod, pubExp);

    // ------------------------ PRIVATE KEY --------------------------------
    byte[] privateKeyData =
        Base64.decode(storage.getKey(IKeyStorage.SECRET_KEY_TYPE), Base64.DEFAULT);
    asnStream = new ASN1InputStream(privateKeyData);

    ASN1Sequence asnSequence = null;
    try {
      asnSequence = (ASN1Sequence) asnStream.readObject();
    } finally {
      asnStream.close();
    }

    RSAPrivateKey privateKey = RSAPrivateKey.getInstance(asnSequence);
    privateRsaKey =
        new RSAPrivateCrtKeyParameters(
            privateKey.getModulus(),
            privateKey.getPublicExponent(),
            privateKey.getPrivateExponent(),
            privateKey.getPrime1(),
            privateKey.getPrime2(),
            privateKey.getExponent1(),
            privateKey.getExponent2(),
            privateKey.getCoefficient());

    RSAEngine engine = new RSAEngine();
    digest = new MD5Digest();
    cipher = new PKCS1Encoding(engine);
  }
示例#6
0
 /**
  * Constructs a new bundle of ciphertext and IV from a string of the format <code>
  * base64(iv):base64(ciphertext)</code>.
  *
  * @param base64IvAndCiphertext A string of the format <code>iv:ciphertext</code> The IV and
  *     ciphertext must each be base64-encoded.
  */
 public CipherTextIvMac(String base64IvAndCiphertext) {
   String[] civArray = base64IvAndCiphertext.split(":");
   if (civArray.length != 3) {
     throw new IllegalArgumentException("Cannot parse iv:ciphertext:mac");
   } else {
     iv = Base64.decode(civArray[0], BASE64_FLAGS);
     mac = Base64.decode(civArray[1], BASE64_FLAGS);
     cipherText = Base64.decode(civArray[2], BASE64_FLAGS);
   }
 }
示例#7
0
        @Override
        public void run() {
          Looper.prepare();
          while (bool_thread) {
            try {
              Log.i("check_time", check_time);
              Thread.sleep(Integer.parseInt(check_time) * 60000);
              if (Utils.isNetworkAvailable(BaseActivity.this)) {
                List<ExpressModel> list =
                    finalDb.findAllByWhere(ExpressModel.class, "IsDownLoad=0");
                list.size();
                for (ExpressModel e : list) {
                  ImageObject[] imgs = new ImageObject[3];

                  ImageObject imageObject1 = new ImageObject();
                  imageObject1.setImageId("ConsignIdentityImageId");
                  if (!VikiccUtils.isEmptyString(e.getConsignIdentityImageId())) {
                    imageObject1.setImageData(
                        Utils.getBitmapFromByte(
                            Base64.decode(e.getConsignIdentityImageId(), Base64.DEFAULT)));
                  }
                  ImageObject imageObject2 = new ImageObject();
                  imageObject2.setImageId("GoodsImageId");
                  imageObject2.setImageData(
                      Utils.getBitmapFromByte(Base64.decode(e.getGoodsImageId(), Base64.DEFAULT)));
                  ImageObject imageObject3 = new ImageObject();
                  imageObject3.setImageId("OrderImageId");
                  imageObject3.setImageData(
                      Utils.getBitmapFromByte(Base64.decode(e.getOrderImageId(), Base64.DEFAULT)));
                  //                            if
                  // (!VikiccUtils.isEmptyString(e.getConsignIdentityImageId())) {
                  //
                  // imageObject1.setImageData(Utils.getBitmapFromByte(e.getConsignIdentityImageId().getBytes()));
                  //                            }
                  //
                  // imageObject2.setImageData(Utils.getBitmapFromByte(e.getGoodsImageId().getBytes()));
                  //
                  // imageObject3.setImageData(Utils.getBitmapFromByte(e.getOrderImageId().getBytes()));
                  imgs[0] = imageObject1;
                  imgs[1] = imageObject2;
                  imgs[2] = imageObject3;
                  e.setImages(imgs);
                  AddExpress(e);
                }
              }
              Message message = new Message();
              message.what = 1;
              handler.sendMessage(message); // 发送消息
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
          Looper.loop();
        }
  /**
   * Returns an ArrayList containing all the Addresses stored in the application's database
   *
   * @return An ArrayList containing one Address object for each record in the Addresses table.
   */
  public ArrayList<Address> getAllAddresses() {
    ArrayList<Address> addresses = new ArrayList<Address>();

    // Specify which columns from the table we are interested in
    String[] projection = {
      AddressesTable.COLUMN_ID,
      AddressesTable.COLUMN_CORRESPONDING_PUBKEY_ID,
      AddressesTable.COLUMN_LABEL,
      AddressesTable.COLUMN_ADDRESS,
      AddressesTable.COLUMN_PRIVATE_SIGNING_KEY,
      AddressesTable.COLUMN_PRIVATE_ENCRYPTION_KEY,
      AddressesTable.COLUMN_RIPE_HASH,
      AddressesTable.COLUMN_TAG
    };

    // Query the database via the ContentProvider
    Cursor cursor =
        mContentResolver.query(
            DatabaseContentProvider.CONTENT_URI_ADDRESSES, projection, null, null, null);

    if (cursor.moveToFirst()) {
      do {
        long id = cursor.getLong(0);
        long correspondingPubkeyId = cursor.getLong(1);
        String label = cursor.getString(2);
        String address = cursor.getString(3);
        String privateSigningKey = cursor.getString(4);
        String privateEncryptionKey = cursor.getString(5);
        byte[] ripeHash = Base64.decode(cursor.getString(6), Base64.DEFAULT);
        byte[] tag = Base64.decode(cursor.getString(7), Base64.DEFAULT);

        Address a = new Address();
        a.setId(id);
        a.setCorrespondingPubkeyId(correspondingPubkeyId);
        a.setLabel(label);
        a.setAddress(address);
        a.setPrivateSigningKey(privateSigningKey);
        a.setPrivateEncryptionKey(privateEncryptionKey);
        a.setRipeHash(ripeHash);
        a.setTag(tag);

        addresses.add(a);
      } while (cursor.moveToNext());
    }

    cursor.close();
    return addresses;
  }
 private void updateUI() {
   if (mModelInfo != null) {
     byte[] htmlContent = Base64.decode(mModelInfo.content, Base64.DEFAULT);
     Logger.i(TAG, "ContractContent = " + new String(htmlContent));
     mWebView.loadDataWithBaseURL(null, new String(htmlContent), "text/html", "UTF-8", null);
   }
 }
    protected void onPostExecute(JSONObject json) {

      int success;
      String mensaje;

      try {

        success = json.getInt(Constantes.JSON_SUCCESS);
        mensaje = json.getString(Constantes.JSON_MESSAGE);

        if (success == 1) { // si fue bien
          // Getting Array of Events
          String image_string = json.getString("image");
          byte[] image_byte = Base64.decode(image_string, Base64.DEFAULT);
          event.setCartel(image_byte);

          setEventsFields();
          // ivCartel.setImageBitmap(BitmapFactory.decodeByteArray(image_byte, 0,
          // image_byte.length));

        } else {
          Toast.makeText(getActivity(), mensaje, Toast.LENGTH_LONG).show();
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  private static Bitmap convertJsonStringBytes2Bitmap(byte[] bytes, String key)
      throws IOException, OutOfMemoryError {
    int size = bytes.length;
    // reduce json header and ender size
    // json header: {"key":"
    // json ender: "}
    String jHeader = "{\"" + key + "\":\"";
    int start = jHeader.getBytes().length;
    String jEnd = "\"}";
    int length = size - start - jEnd.getBytes().length;
    // Log.i(TAG, "start:" + start + ",length:" + length);

    if (start >= size - 1 || length < 0) {
      return null;
    }
    bytes = Base64.decode(bytes, start, length, Base64.DEFAULT);

    // reduce auth header and ender
    size = bytes.length;
    start = AUTH_HEAD_BYTES_SIZE;
    length = size - start - AUTH_END_BYTES_SIZE;

    // Log.i(TAG, "bitmap start:" + start + ",length:" + length);
    if (start >= size - 1 || length < 0) {
      return null;
    }
    Bitmap map = BitmapFactory.decodeByteArray(bytes, start, length);
    return map;
  }
 private OpenForReadResult readDataUri(Uri paramUri) {
   Object localObject = paramUri.getSchemeSpecificPart();
   int k = ((String) localObject).indexOf(',');
   if (k == -1) {
     return null;
   }
   String[] arrayOfString = ((String) localObject).substring(0, k).split(";");
   String str = null;
   int j = 0;
   if (arrayOfString.length > 0) {
     str = arrayOfString[0];
   }
   int i = 1;
   while (i < arrayOfString.length) {
     if ("base64".equalsIgnoreCase(arrayOfString[i])) {
       j = 1;
     }
     i += 1;
   }
   localObject = ((String) localObject).substring(k + 1);
   if (j != 0) {}
   for (localObject = Base64.decode((String) localObject, 0);
       ;
       localObject = EncodingUtils.getBytes((String) localObject, "UTF-8")) {
     return new OpenForReadResult(
         paramUri, new ByteArrayInputStream((byte[]) localObject), str, localObject.length, null);
   }
 }
示例#13
0
  private void createCrossImage() {
    mCrossImage = new ImageView(getContext());
    // Dismiss the dialog when user click on the 'x'
    mCrossImage.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            mListener.onCancel();
            FbDialog.this.dismiss();
          }
        });

    int px30 =
        (int)
            TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 30, getContext().getResources().getDisplayMetrics());
    mCrossImage.setLayoutParams(new FrameLayout.LayoutParams(px30, px30));
    mCrossImage.setScaleType(ImageView.ScaleType.FIT_CENTER);

    byte[] decodedString = Base64.decode(CLOSE_BT, Base64.DEFAULT);
    Bitmap cross = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    mCrossImage.setImageBitmap(cross);
    /* 'x' should not be visible while webview is loading
     * make it visible only after webview has fully loaded
     */
    mCrossImage.setVisibility(View.INVISIBLE);
  }
示例#14
0
  @Override
  public boolean execute(String action, JSONArray data, CallbackContext callbackContext)
      throws JSONException {

    if (action.equals(ACTION)) {

      String base64 = data.optString(0);
      if (base64.equals("")) // isEmpty() requires API level 9
      callbackContext.error("Missing base64 string");

      // Create the bitmap from the base64 string
      Log.d("Canvas2ImagePlugin", base64);
      byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
      Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
      if (bmp == null) {
        callbackContext.error("The image could not be decoded");
      } else {

        // Save the image
        File imageFile = savePhoto(bmp);
        if (imageFile == null) callbackContext.error("Error while saving image");

        // Update image gallery
        scanPhoto(imageFile);

        callbackContext.success(imageFile.toString());
      }

      return true;
    } else {
      return false;
    }
  }
 private void loadImage(String image) {
   byte[] img;
   img = Base64.decode(image, Base64.DEFAULT);
   ByteArrayInputStream in = new ByteArrayInputStream(img);
   Bitmap bmp = BitmapFactory.decodeStream(in);
   imgView.setImageBitmap(bmp);
 }
示例#16
0
 public Bitmap getThumbnail() {
   if (thumbnail == null && thumbnailBase64 != null) {
     byte[] decodeString = Base64.decode(thumbnailBase64, Base64.DEFAULT);
     thumbnail = BitmapFactory.decodeByteArray(decodeString, 0, decodeString.length);
   }
   return thumbnail;
 }
示例#17
0
  public static String decryptIt(String value) {
    try {
      DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey key = keyFactory.generateSecret(keySpec);

      byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT);
      // cipher is not thread safe
      Cipher cipher = Cipher.getInstance("DES");
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));

      String decrypedValue = new String(decrypedValueBytes);
      Log.d(TAG, "Decrypted: " + value + " -> " + decrypedValue);
      return decrypedValue;

    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    }
    return value;
  }
示例#18
0
 /**
  * Verifies that the signature from the server matches the computed signature on the data. Returns
  * true if the data is correctly signed.
  *
  * @param publicKey public key associated with the developer account
  * @param signedData signed data from server
  * @param signature server signature
  * @return true if the data and signature match
  */
 public static boolean verify(PublicKey publicKey, String signedData, String signature) {
   if (Consts.DEBUG) {
     Log.i(TAG, "signature: " + signature);
   }
   Signature sig;
   try {
     sig = Signature.getInstance(SIGNATURE_ALGORITHM);
     sig.initVerify(publicKey);
     sig.update(signedData.getBytes());
     // if (!sig.verify(Base64.decode(signature))) {
     if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
       Log.e(TAG, "Signature verification failed.");
       return false;
     }
     return true;
   } catch (NoSuchAlgorithmException e) {
     Log.e(TAG, "NoSuchAlgorithmException.");
   } catch (InvalidKeyException e) {
     Log.e(TAG, "Invalid key specification.");
   } catch (SignatureException e) {
     Log.e(TAG, "Signature exception.");
   } // catch (Base64DecoderException e) {
   //    Log.e(TAG, "Base64 decoding failed.");
   // }
   return false;
 }
示例#19
0
文件: Util.java 项目: gubo/slipwire
  /**
   * @param s
   * @return
   * @throws GeneralSecurityException
   * @throws UnsupportedEncodingException
   */
  public static String decrypt(final String s)
      throws GeneralSecurityException, UnsupportedEncodingException {
    String decrypted = null;

    try {
      if (s != null) {
        final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        final SecretKey secretKey =
            secretKeyFactory.generateSecret(new PBEKeySpec(secret.toCharArray()));
        final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new PBEParameterSpec(SALT, 20));
        final byte[] stringBytes = s.getBytes("UTF-8");
        final byte[] decodedBytes = Base64.decode(stringBytes, Base64.DEFAULT);
        final byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        decrypted = new String(decryptedBytes, "UTF-8");
      }
    } catch (GeneralSecurityException x) {
      throw x;
    } catch (UnsupportedEncodingException x) {
      throw x;
    } catch (Exception x) {
      DBG.m(x);
    }

    return decrypted;
  }
示例#20
0
  /**
   * @param src
   * @return source data
   * @throws NoSuchPaddingException
   * @throws NoSuchAlgorithmException
   * @throws InvalidAlgorithmParameterException
   * @throws InvalidKeyException
   */
  public byte[] decrypt(String baseKey, String src)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidAlgorithmParameterException {

    byte[] key = SHA256(baseKey);

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

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

    byte[] dec = Base64.decode(src, 0);
    byte[] ret = null;

    try {
      ret = decryptor.doFinal(dec);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    return ret;
  }
 private OpenForReadResult readDataUri(Uri uri) {
   String uriAsString = uri.getSchemeSpecificPart();
   int commaPos = uriAsString.indexOf(',');
   if (commaPos == -1) {
     return null;
   }
   String[] mimeParts = uriAsString.substring(0, commaPos).split(";");
   String contentType = null;
   boolean base64 = false;
   if (mimeParts.length > 0) {
     contentType = mimeParts[0];
   }
   for (int i = 1; i < mimeParts.length; ++i) {
     if ("base64".equalsIgnoreCase(mimeParts[i])) {
       base64 = true;
     }
   }
   String dataPartAsString = uriAsString.substring(commaPos + 1);
   byte[] data =
       base64
           ? Base64.decode(dataPartAsString, Base64.DEFAULT)
           : EncodingUtils.getBytes(dataPartAsString, "UTF-8");
   InputStream inputStream = new ByteArrayInputStream(data);
   return new OpenForReadResult(uri, inputStream, contentType, data.length, null);
 }
示例#22
0
 static List<HeartRateItem> a(String str) {
   List<HeartRateItem> arrayList = new ArrayList();
   try {
     JSONObject jSONObject = new JSONObject(str);
     if (jSONObject.optInt(b.a) != 1) {
       return null;
     }
     JSONArray jSONArray = jSONObject.getJSONArray(b.b);
     int length = jSONArray.length();
     for (int i = 0; i < length; i++) {
       jSONObject = jSONArray.getJSONObject(i);
       byte[] decode = Base64.decode(jSONObject.getString(O.j), 2);
       if (decode != null && decode.length > 0) {
         long j = jSONObject.getLong(g.f);
         for (int i2 = 0; i2 < decode.length; i2++) {
           if (decode[i2] != (byte) 0) {
             HeartRateItem heartRateItem = new HeartRateItem();
             heartRateItem.type = 1;
             heartRateItem.time = ((long) i2) + j;
             heartRateItem.hr = decode[i2] & HeartRateInfo.HR_EMPTY_VALUE;
             arrayList.add(heartRateItem);
           }
         }
       }
     }
     return arrayList;
   } catch (JSONException e) {
     e.printStackTrace();
     return arrayList;
   }
 }
示例#23
0
 static {
   density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density;
   SharedPreferences preferences =
       ApplicationLoader.applicationContext.getSharedPreferences("primes", Context.MODE_PRIVATE);
   String primes = preferences.getString("primes", null);
   if (primes == null) {
     goodPrimes.add(
         "C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B");
   } else {
     try {
       byte[] bytes = Base64.decode(primes, Base64.DEFAULT);
       if (bytes != null) {
         SerializedData data = new SerializedData(bytes);
         int count = data.readInt32();
         for (int a = 0; a < count; a++) {
           goodPrimes.add(data.readString());
         }
       }
     } catch (Exception e) {
       FileLog.e("tmessages", e);
       goodPrimes.clear();
       goodPrimes.add(
           "C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B");
     }
   }
   System.loadLibrary("tmessages");
 }
示例#24
0
  /**
   * 将加密的byte[]解密,返回解密后字节数组
   *
   * @param msg 加密消息体
   * @param srcKey 会话密钥
   * @return byte[] 解密后byte[]
   * @throws Exception Exception
   */
  public static byte[] decode2Byte(byte[] msg, String srcKey) throws Exception {
    SecretKey sercKey = new SecretKeySpec(srcKey.getBytes(), ALGORITHM_3DES);

    byte[] base64Msg = decrypt(sercKey, msg, ALGORITHM_3DES);

    return Base64.decode(base64Msg, Base64.DEFAULT);
  }
  public String decrypt(String encrypted, Cipher cipher) throws Exception {
    byte[] bts = Base64.decode(encrypted, Base64.DEFAULT);

    byte[] decrypted = blockCipher(bts, Cipher.DECRYPT_MODE, cipher);

    return new String(decrypted, "UTF-8");
  }
示例#26
0
  /**
   * 将加密的字符串解密,返回解密后字符串
   *
   * @param msg 加密消息体
   * @param srcKey 会话密钥
   * @return String 解密后byte[]
   * @throws Exception Exception
   */
  public static String decode2Str(String msg, String srcKey) throws Exception {
    SecretKey sercKey = new SecretKeySpec(srcKey.getBytes(), ALGORITHM_3DES);

    String base64Msg = decrypt(sercKey, msg, ALGORITHM_3DES);

    return new String(Base64.decode(base64Msg, Base64.DEFAULT), "UTF-8");
  }
示例#27
0
 public static TodoList todoListFromString(String todoListData)
     throws IOException, ClassNotFoundException {
   ByteArrayInputStream bis =
       new ByteArrayInputStream(Base64.decode(todoListData, Base64.DEFAULT));
   ObjectInputStream ois = new ObjectInputStream(bis);
   return (TodoList) ois.readObject();
 }
示例#28
0
  /**
   * 将Base64的图片转化为jpg格式保存
   *
   * @param base64Data Base64图片数据
   * @param savePath 保存的路径
   * @return 返回图片的Bitmap
   */
  public static Bitmap base64ToBitmap(String base64Data, String savePath) {
    byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

    File file = new File(savePath);
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    try {
      boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
      if (isSuccess) {
        fos.flush();
        fos.close();
        return bitmap;
      } else {
        fos.close();
        return null;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
示例#29
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);
  }
示例#30
0
 public static String base64Decode(String encoded) {
   if (encoded == null) {
     return null;
   }
   byte[] decoded = Base64.decode(encoded, Base64.DEFAULT);
   return new String(decoded);
 }