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) { } }
public static String printKeyHash(Activity context) { PackageInfo packageInfo; String key = null; try { // getting application package name, as defined in manifest String packageName = context.getApplicationContext().getPackageName(); // Retriving package info packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); Log.e("Package Name=", context.getApplicationContext().getPackageName()); for (Signature signature : packageInfo.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); key = new String(Base64.encode(md.digest(), 0)); // String key = new String(Base64.encodeBytes(md.digest())); Log.e("Key Hash=", key); } } catch (PackageManager.NameNotFoundException e1) { Log.e("Name not found", e1.toString()); } catch (NoSuchAlgorithmException e) { Log.e("No such an algorithm", e.toString()); } catch (Exception e) { Log.e("Exception", e.toString()); } return key; }
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; }
@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); }
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) { } }
/** * 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); }
@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 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); }
/** * 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 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); }
public List<NameValuePair> addnew_crypt_K_param(List<NameValuePair> param, String url) { ArrayList<NameValuePair> localArrayList = new ArrayList<NameValuePair>(); generate_new_aes_key(); localArrayList.add(new BasicNameValuePair("K", get_K())); Iterator<NameValuePair> i = param.iterator(); boolean is_login = false; if (url.indexOf("login?") != -1 || url.indexOf("regist?") != -1) { is_login = true; ON = true; } while (i.hasNext()) { NameValuePair n = i.next(); // String val = Base64.encodeBase64String(new_encrypt_cn(E_CODE.AES,n.getValue())); String val = new String(Base64.encode(new_encrypt_cn(E_CODE.AES, n.getValue()), Base64.DEFAULT)); if (is_login == true) { // localArrayList.add(new BasicNameValuePair(n.getName(), // Base64.encodeBase64String(new_encrypt_cn(E_CODE.RSA_EP, val)))); localArrayList.add( new BasicNameValuePair( n.getName(), new String(Base64.encode(new_encrypt_cn(E_CODE.RSA_EP, val), Base64.DEFAULT)))); } else { localArrayList.add(new BasicNameValuePair(n.getName(), val)); } } return localArrayList; }
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); }
/** * 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); } }
@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; } }
@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(); }
public void rsaCypher(String rString, InputStream inputStream, File directory) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, IOException, BadPaddingException, IllegalBlockSizeException { kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); kp = kpg.genKeyPair(); privateKey = kp.getPrivate(); cipher = Cipher.getInstance("RSA"); File root = new File(Environment.getExternalStorageDirectory() + "/Notes/", "rsapublick.txt"); // Read text from file if (root.exists()) { StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(root)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close(); byte[] keyBytes = Base64.decode(text.toString().getBytes("utf-8"), 0); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); publicKey = keyFactory.generatePublic(spec); } catch (IOException e) { // You'll need to add proper error handling here } catch (InvalidKeySpecException e) { e.printStackTrace(); } } else { publicKey = kp.getPublic(); byte[] pKbytes = Base64.encode(publicKey.getEncoded(), 0); String pK = new String(pKbytes); String pubKey = "-----BEGIN public KEY-----\n" + pK + "-----END public KEY-----\n"; System.out.println(pubKey); generateNoteOnSD("rsapublick.txt", pK, directorio); } this.cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytes = getBytesFromInputStream(inputStream); byte[] encrypted = blockCipher(bytes, Cipher.ENCRYPT_MODE); FileOutputStream fileOutputStream = new FileOutputStream(directory); fileOutputStream.write(encrypted); fileOutputStream.close(); System.out.println("Encryptado RSA Finalizado"); root = new File(Environment.getExternalStorageDirectory() + "/Notes/", "rsaOrivatek.txt"); if (!root.exists()) { byte[] pKbytes = Base64.encode(getPrivateKey().getEncoded(), 0); String pK = new String(pKbytes); String pubKey = "-----BEGIN private KEY-----\n" + pK + "-----END private KEY-----\n"; System.out.println(pubKey); generateNoteOnSD("rsaOrivatek.txt", pK, directorio); } }
@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(); } }
/** * 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; }
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(); }
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; }
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); }
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) {} }); }
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"); }
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"); }
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); } }
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 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); }
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(); } }
// 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; }
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(); }