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 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 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); } }
private void getScreenshotAsURI(Bitmap bitmap, int quality) { try { ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); if (bitmap.compress(CompressFormat.JPEG, quality, jpeg_data)) { byte[] code = jpeg_data.toByteArray(); byte[] output = Base64.encode(code, Base64.NO_WRAP); String js_out = new String(output); js_out = "data:image/jpeg;base64," + js_out; JSONObject jsonRes = new JSONObject(); jsonRes.put("URI", js_out); PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes); mCallbackContext.sendPluginResult(result); js_out = null; output = null; code = null; } jpeg_data = null; } catch (JSONException e) { mCallbackContext.error(e.getMessage()); } catch (Exception e) { mCallbackContext.error(e.getMessage()); } }
/** * @param s * @return * @throws GeneralSecurityException * @throws UnsupportedEncodingException */ public static String encrypt(final String s) throws GeneralSecurityException, UnsupportedEncodingException { String encrypted = 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.ENCRYPT_MODE, secretKey, new PBEParameterSpec(SALT, 20)); final byte[] stringBytes = s.getBytes("UTF-8"); final byte[] encryptedBytes = cipher.doFinal(stringBytes); final byte[] encodedBytes = Base64.encode(encryptedBytes, Base64.DEFAULT); encrypted = new String(encodedBytes, "UTF-8"); } } catch (GeneralSecurityException x) { throw x; } catch (UnsupportedEncodingException x) { throw x; } catch (Exception x) { DBG.m(x); } return encrypted; }
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); }
/** * 加密字符串,返回加密后的字节数组 * * @param msg 字符串 * @param srcKey 会话密钥 * @throws Exception Exception * @return byte[] 字节数组 */ public static byte[] encode2Byte(String msg, String srcKey) throws Exception { SecretKey sercKey = new SecretKeySpec(srcKey.getBytes(), SecurityUtils.ALGORITHM_3DES); byte[] base64Msg = Base64.encode(msg.getBytes("UTF-8"), Base64.DEFAULT); return SecurityUtils.encrypt(sercKey, base64Msg, SecurityUtils.ALGORITHM_3DES); }
/** * Ensure arbitrary data is only Base 64 encoded once. */ public static byte[] finalEncode(byte[] src) { byte[] dest = null; if (isArrayByteBase64(src)) { dest = src; } else { dest = Base64.encode(src, Base64.NO_WRAP); } return dest; }
private void genPhoto() { photo.setPartyId(entity.getPartyId()); photo.setName(entity.getPartyface()); byte[] input = ImageUtil.Bitmap2Bytes(bitMap); byte[] newly = Base64.encode(input, Base64.DEFAULT); photo.setContent(new String(newly)); photo.setPhotoUpdateDate(DateTimeUtil.format(new Date())); }
/** * 把bitmap转换成String * * @return */ public static String bitmapToString(Bitmap bitmap) { if (null != bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] bytes = baos.toByteArray(); return new String(Base64.encode(bytes, Base64.DEFAULT)); } return ""; }
public static String longKeyId2Base64String(long keyId) { try { return new String( Base64.encode(ByteBuffer.allocate(Long.SIZE / 8).putLong(keyId).array(), Base64.NO_WRAP), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } }
/** * As a security feature, this class will not allow queries of authentication passwords. This * method will instead encode the security credentials (username and password) using * Base64-encryption, and return the encrypted data as a byte array. * * @return the encrypted credentials * @see #username() * @see #password(String) */ public byte[] getEncodedCredentials() { StringBuilder auth = new StringBuilder(); if (username != null) { auth.append(username); } if (password != null) { auth.append(":").append(password); } return Base64.encode(auth.toString().getBytes(), Base64.NO_WRAP); }
public static String getStringMD5(String key) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.update(key.getBytes()); // important: use Base64.URL_SAFE flag to avoid "+" and "/" return new String(Base64.encode(md5.digest(), Base64.URL_SAFE)); }
public static <T> String listToString(List<T> list) throws IOException { // 实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 然后将得到的字符数据装载到ObjectOutputStream ObjectOutputStream oos = new ObjectOutputStream(baos); // writeObject 方法负责写入特定类的对象的状态,以便相应的readObject可以还原它 oos.writeObject(list); // 最后,用Base64.encode将字节文件转换成Base64编码,并以String形式保存 String listString = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT)); // 关闭oos oos.close(); return listString; }
public static String encodeWithBase64(String paramString) { SecretKeySpec localSecretKeySpec = new SecretKeySpec(BaseSecretKey, "AES"); try { byte[] arrayOfByte = paramString.getBytes(); Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); localCipher.init(Cipher.ENCRYPT_MODE, localSecretKeySpec); // String str = Base64.encodeBase64String(localCipher.doFinal(arrayOfByte)); String str = new String(Base64.encode(localCipher.doFinal(arrayOfByte), Base64.DEFAULT)); return str; } catch (Exception localException) { } return null; }
public void generate_new_aes_key() { try { KeyGenerator localKeyGenerator = KeyGenerator.getInstance("AES"); localKeyGenerator.init(128, SecureRandom.getInstance("SHA1PRNG")); // aes_key = Base64.encodeBase64String(localKeyGenerator.generateKey().getEncoded()); aes_key = new String(Base64.encode(localKeyGenerator.generateKey().getEncoded(), Base64.DEFAULT)); } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) { System.out.println(localNoSuchAlgorithmException); } return; }
/** * Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript. * * @param bitmap */ public void processPicture(Bitmap bitmap) { ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); try { if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) { byte[] code = jpeg_data.toByteArray(); byte[] output = Base64.encode(code, Base64.NO_WRAP); String js_out = new String(output); ResultPicture(js_out); } } catch (Exception e) { jpeg_data = null; this.ResultPicture("Error compressing image."); } }
public static void download(List<ArgumentWrapper> argsArray, Session currentSession) { // Get path from arguments String path = Common.getParamString(argsArray, "path"); Integer offset = Integer.parseInt(Common.getParamString(argsArray, "offset")); // Start sending structure currentSession.startTransmission(); currentSession.startResponse(); currentSession.startData(); File file = new File(path); InputStream in = null; int buffSize = 50 * 1024; // 50KB try { in = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[buffSize]; for (int i = 0; i < offset; i++) in.read(); int bytesRead = in.read(buffer, 0, buffSize); currentSession.send( new String(Base64.encode(buffer, 0, bytesRead, Base64.DEFAULT)) + "\n", false); // End data section of structure currentSession.endData(); currentSession.noError(); } catch (Exception e) { currentSession.endData(); currentSession.error(e.getMessage()); } finally { // Close file if (in != null) { try { in.close(); } catch (Exception e) { } } // End transmission currentSession.endResponse(); currentSession.endTransmission(); } }
public String encrypt(String key, String plainText) { try { byte[] keyBytes = key.getBytes(); SecretKey secretKey = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); setIvParams(cipher); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParams); byte[] ciphertext = cipher.doFinal(plainText.getBytes("UTF-8")); String bCipher = new String(Base64.encode(ciphertext, Base64.NO_WRAP)); return bCipher; } catch (Exception e) { e.printStackTrace(); } return null; }
public String getCapHash() { StringBuilder s = new StringBuilder(); s.append("client/" + IDENTITY_TYPE + "//" + getIdentityName() + "<"); MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return null; } for (String feature : getFeatures()) { s.append(feature + "<"); } byte[] sha1 = md.digest(s.toString().getBytes()); return new String(Base64.encode(sha1, Base64.DEFAULT)).trim(); }
public String convertBitmap(Bitmap bitmap) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 将图片进行压缩 bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); try { outputStream.flush(); outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte[] buffer = outputStream.toByteArray(); byte[] encode = Base64.encode(buffer, Base64.DEFAULT); return new String(encode); }
/** * 将对象进行base64编码后保存到SharePref中 * * @param context * @param key * @param object */ public static void saveObj(Context context, String key, Object object) { if (sp == null) sp = context.getSharedPreferences(SP_NAME, 0); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(object); // 将对象的转为base64码 String objBase64 = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT)); sp.edit().putString(key, objBase64).commit(); oos.close(); } catch (IOException e) { e.printStackTrace(); } }
public static String encryptData(String data) { String base64EncryptedData = null; DataEncryption encrptor = null; try { encrptor = new DataEncryption(ENCRYPTION_KEY.getBytes("utf-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } byte[] byteData = null; try { byteData = data.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] encryptedPassword = encrptor.rockeTalkEncrypt(byteData); // base64EncryptedData = Base64.encode(encryptedPassword, // 0);//MyBase64.encode(encryptedPassword); return new String(Base64.encode(encryptedPassword, 0)); }
/** * 加密 * * @param secretKey 密钥 * @param msg 明文 * @param algorithm 加密方式 * @return 密文 * @throws UtilException UtilException * @see [类、类#方法、类#成员] */ public static String encrypt(SecretKey secretKey, String msg, String algorithm) throws Exception { try { Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] base64 = Base64.encode(cipher.doFinal(stringToBytes(msg)), Base64.DEFAULT); return bytesToSting(base64); } catch (NoSuchAlgorithmException e) { throw new Exception(e); } catch (NoSuchPaddingException e) { throw new Exception(e); } catch (InvalidKeyException e) { throw new Exception(e); } catch (IllegalBlockSizeException e) { throw new Exception(e); } catch (BadPaddingException e) { throw new Exception(e); } catch (Exception e) { throw new Exception(e); } }
/** * @description 修改会员信息 * @param info * @param backListener */ public void updateUserInfo(UserInfo info, CallBackListener backListener) { HashMap<String, Object> map = createMap(); try { HashMap<String, String> inputBodyMap = new HashMap<String, String>(); inputBodyMap.put("UserId", info.getUid()); inputBodyMap.put("Name", info.getName()); inputBodyMap.put("Sex", info.getSex()); inputBodyMap.put( "NickName", new String(Base64.encode(info.getNickName().getBytes(), Base64.NO_WRAP), "UTF-8")); inputBodyMap.put("CertNO", info.getCertNO()); inputBodyMap.put("Email", info.getEmail()); String inputBody = createInputBody(inputBodyMap); finishMap(map, inputBody); } catch (Exception e) { e.printStackTrace(); } InvokeRequest request = new InvokeRequest(map, FunctionCode.USER_INFO_UPDATE, backListener); request.invoke(); }
public String get_K() { if (rsa_key.length() < 2) return null; Cipher localCipher; byte[] arrayOfByte = null; PublicKey localPublicKey; try { // byte[] b = Base64.decode(rsa_key); byte[] b = Base64.decode(rsa_key, Base64.DEFAULT); X509EncodedKeySpec sp = new X509EncodedKeySpec(b); localPublicKey = KeyFactory.getInstance("RSA").generatePublic(sp); localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey); arrayOfByte = localCipher.doFinal(aes_key.getBytes("utf-8")); } catch (Exception e) { // e.printStackTrace(); return null; } // return new String(Base64.encode(arrayOfByte)); return new String(Base64.encode(arrayOfByte, Base64.DEFAULT)); }
public static ArrayList<BingResult> makeQuery(String query) { ArrayList<BingResult> result = new ArrayList<>(); try { String bingUrl = BING_URL + "?Query=%27" + Uri.encode(query) + "%27&$top=" + BING_RESULTS + "&$format=json"; byte[] accountKeyBytes = Base64.encode((":" + BING_PASSWORD).getBytes(), Base64.DEFAULT); String accountKeyEnc = new String(accountKeyBytes); URL url = new URL(bingUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc); if (urlConnection.getResponseCode() == 200) { StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = reader.readLine()) != null) sb.append(line + "\n"); JSONObject jo = new JSONObject(sb.toString()); JSONArray ja = jo.getJSONObject("d").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { jo = ja.getJSONObject(i); String imageUrl = jo.getString("MediaUrl"); String thumbnailUrl = jo.getJSONObject("Thumbnail").getString("MediaUrl"); result.add(new BingResult(thumbnailUrl, imageUrl)); } } } catch (Exception e) { e.printStackTrace(); } return result; }
public String processPicture(Bitmap bitmap) { int mQuality = 80; ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); String js_out = ""; try { if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) { byte[] code = jpeg_data.toByteArray(); byte[] output = android.util.Base64.encode(code, android.util.Base64.NO_WRAP); js_out = new String(output); // this.callbackContext.success(js_out); // Clean Up jpeg_data = null; output = null; code = null; } return js_out; } catch (Exception e) { debugMessage(TAG + " Unable To Process Picture"); return TAG + " " + e.getMessage(); } finally { js_out = null; } }
/** * @param url String * @param username String * @param password String * @return Username and Password are a valid Login-Combination for the given URL. */ public static LoginStatus isValidLogin(String url, String username, String password) { try { String targetURL = url + "index.php/apps/notes/api/v0.2/notes"; HttpURLConnection con = (HttpURLConnection) new URL(targetURL).openConnection(); con.setRequestMethod("GET"); con.setRequestProperty( "Authorization", "Basic " + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP))); con.setConnectTimeout(10 * 1000); // 10 seconds con.connect(); if (con.getResponseCode() == 200) { StringBuilder result = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } System.out.println(result.toString()); new JSONArray(result.toString()); return LoginStatus.OK; } else if (con.getResponseCode() >= 401 && con.getResponseCode() <= 403) { return LoginStatus.AUTH_FAILED; } else { return LoginStatus.SERVER_FAILED; } } catch (MalformedURLException e) { Log.e(NotesClientUtil.class.getSimpleName(), "Exception", e); return LoginStatus.CONNECTION_FAILED; } catch (IOException e) { Log.e(NotesClientUtil.class.getSimpleName(), "Exception", e); return LoginStatus.CONNECTION_FAILED; } catch (JSONException e) { Log.e(NotesClientUtil.class.getSimpleName(), "Exception", e); return LoginStatus.JSON_FAILED; } }
@Nonnull static String toX(@Nonnull String message, @Nonnull String key) { return new String(Base64.encode(x(message, key).getBytes(), 0)); }