下面列出了android.util.Base64#decode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static KeyPair deserializeKeyPairOld(String str) {
if (str == null || str.length() == 0) {
return null;
}
try {
// base64 string to bytes
byte[] bytes = Base64.decode(str, Base64.DEFAULT);
// bytes to KeyPairData
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ios = new ObjectInputStream(bais);
KeyPairData obj = (KeyPairData) ios.readObject();
// KeyParData to KeyPair
JSch jsch = new JSch();
KeyPair keypair = KeyPair.load(jsch, obj.prvkey, obj.pubkey);
if (keypair != null) {
keypair.setPublicKeyComment(null);
}
return keypair;
} catch (Exception e) {
Log.e(TAG, "deserialize error: " + e.toString());
}
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;
}
private static byte[] loadStoredBitsFromPreferences(Context context, String settingName, int requestedSize, String sharedPrefFileName) {
SharedPreferences sharedPrefs = getSharedPreferences(context, sharedPrefFileName);
String base64 = sharedPrefs.getString(settingName, null);
if (base64 != null) {
try {
byte[] storedBits = Base64.decode(base64, Base64.DEFAULT);
if (isByteArrayInvalid(storedBits, requestedSize)) {
return null;
} else {
return storedBits;
}
} catch (IllegalArgumentException e) {
Log.w(TAG, "Stored bits were not properly encoded", e);
}
}
return null;
}
/**
* Print an image
*
* @param image String (BASE64 encoded image)
* @param width
* @param height
* @param align
*/
public void printImage(String image, int width, int height, int align) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
byte[] decodedByte = Base64.decode(image, 0);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
final int imgWidth = bitmap.getWidth();
final int imgHeight = bitmap.getHeight();
final int[] argb = new int[imgWidth * imgHeight];
bitmap.getPixels(argb, 0, imgWidth, 0, 0, imgWidth, imgHeight);
bitmap.recycle();
mPrinter.printImage(argb, width, height, align, true);
mPrinter.flush();
mCallbackContext.success();
} catch (Exception e) {
e.printStackTrace();
mCallbackContext.error(this.getErrorByCode(11, e));
}
}
/**
* string转成bitmap
*
* @param st
*/
public static Bitmap string2bitmap(String st)
{
// OutputStream out;
Bitmap bitmap = null;
try
{
// out = new FileOutputStream("/sdcard/aa.jpg");
byte[] bitmapArray;
bitmapArray = Base64.decode(st, Base64.DEFAULT);
bitmap =
BitmapFactory.decodeByteArray(bitmapArray, 0,
bitmapArray.length);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
return bitmap;
}
catch (Exception e)
{
return null;
}
}
/**
* Use private key to decrypt
*
* @param data
* @param privateKey
*
* @return
*/
public String decrypt(String data, PrivateKey privateKey) {
byte[] rst = null;
String rstStr = null;
try {
byte[] encodedContent = Base64.decode(data, Base64.NO_WRAP);
Cipher cipher = Cipher.getInstance(EncryptConfig.TRANSFORMATION_SETTING);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
rst = cipher.doFinal(encodedContent);
rstStr = new String(rst, "UTF-8");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rstStr;
}
public byte[] base64ToByte(String str){
byte[] ret = new byte[0];
try{
ret = Base64.decode(str, Base64.DEFAULT);
} catch(Exception e){
e.printStackTrace();
}
return ret;
}
@Override
public long writeBlock(OutputStream out, EncryptedOutputStream eos) throws IOException, InputOutputStreamException {
int ivsize = 0;
if(block.equals(CryptoUtil.CipherBlock.BLOCK_CBC))
ivsize = (algo.equals(CryptoUtil.CipherAlgo.ALGO_AES)) ? 16 : 8;
int length = MIN_PAYLOAD_SIZE;
if(type.equals(CipherType.TYPE_CIPHER_GROUP))
length += FIELD_GROUP_GID_SIZE+ivsize;
ByteBuffer blockBuffer= ByteBuffer.allocate(length);
blockBuffer.put((byte)type.value);
blockBuffer.put((byte)algo.value);
blockBuffer.put((byte)block.value);
blockBuffer.put((byte)padding.value);
if(type.equals(CipherType.TYPE_CIPHER_GROUP)) {
byte[] group_id = Base64.decode(gid, Base64.NO_WRAP);
blockBuffer.put(group_id, 0, FIELD_GROUP_GID_SIZE);
blockBuffer.put(ivBytes, 0, ivsize);
}
/* send the header and the payload */
header.setPayloadLength(length);
header.writeBlockHeader(out);
out.write(blockBuffer.array(), 0, length);
BlockDebug.d(TAG, "BlockCrypto sent (" + length + " bytes): " + Arrays.toString(blockBuffer.array()));
return header.getBlockLength()+BlockHeader.BLOCK_HEADER_LENGTH;
}
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 void handleNewFormat(SpannableStringBuilder builder, String misc, int titleLength) {
byte[] bytes = Base64.decode(misc, Base64.DEFAULT);
if (bytes != null) {
int pos = 0;
while (pos < bytes.length) {
// 1 表示主题bit数据
if (bytes[pos] == 1) {
String miscStr = StringUtils.toBinaryArray(bytes).substring(8);
int miscValue = new BigInteger(miscStr, 2).intValue();
if ((miscValue & ApiConstants.MASK_FONT_GREEN) == ApiConstants.MASK_FONT_GREEN) {
builder.setSpan(new ForegroundColorSpan(ContextUtils.getColor(R.color.title_green)), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if ((miscValue & ApiConstants.MASK_FONT_BLUE) == ApiConstants.MASK_FONT_BLUE) {
builder.setSpan(new ForegroundColorSpan(ContextUtils.getColor(R.color.title_blue)), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if ((miscValue & ApiConstants.MASK_FONT_RED) == ApiConstants.MASK_FONT_RED) {
builder.setSpan(new ForegroundColorSpan(ContextUtils.getColor(R.color.title_red)), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if ((miscValue & ApiConstants.MASK_FONT_ORANGE) == ApiConstants.MASK_FONT_ORANGE) {
builder.setSpan(new ForegroundColorSpan(ContextUtils.getColor(R.color.title_orange)), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if ((miscValue & ApiConstants.MASK_FONT_SILVER) == ApiConstants.MASK_FONT_SILVER) {
builder.setSpan(new ForegroundColorSpan(ContextUtils.getColor(R.color.silver)), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if ((miscValue & ApiConstants.MASK_FONT_BOLD) == ApiConstants.MASK_FONT_BOLD && (miscValue & ApiConstants.MASK_FONT_ITALIC) == ApiConstants.MASK_FONT_ITALIC) {
builder.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if ((miscValue & ApiConstants.MASK_FONT_ITALIC) == ApiConstants.MASK_FONT_ITALIC) {
builder.setSpan(new StyleSpan(Typeface.ITALIC), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if ((miscValue & ApiConstants.MASK_FONT_BOLD) == ApiConstants.MASK_FONT_BOLD) {
builder.setSpan(new StyleSpan(Typeface.BOLD), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if ((miscValue & ApiConstants.MASK_FONT_UNDERLINE) == ApiConstants.MASK_FONT_UNDERLINE) {
builder.setSpan(new UnderlineSpan(), 0, titleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
pos += 4;
}
}
}
public static String decrypt(String value) {
if (isBase64(value)) {
try {
DESKeySpec keySpec = new DESKeySpec(KEY);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT);
// Implement this in a thread safe way, or switch to AES.
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));
String decrypedText = new String(decrypedValueBytes);
Log.d("Oh snap!", "Decrypted: " + value + " -> " + decrypedText);
return decrypedText;
} catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException e) {
e.printStackTrace();
}
} else {
System.out.println("Not a string!");
}
return value;
}
/**
* Decode the Base64-encoded data in input and return the data in a new byte array.
* The padding '=' characters at the end are considered optional, but if any are present, there must be the correct number of them.
*
* @param context
* @param type
* @return
* @throws IllegalArgumentException if the input contains incorrect padding
*/
public static byte[] Base64decoding(String context, int type) throws IllegalArgumentException, IOException {
byte[] result;
if (getSdkVersion() > 17) {
result = Base64.decode(context, type);
} else {
result = com.marshalchen.ua.common.commonUtils.urlUtils.Base64.decode(context);
}
return result;
}
private byte[] generateSalt() {
byte[] salt;
String saltString = mSharedPrefs.getString(SALT, null);
if (TextUtils.isEmpty(saltString)) {
try {
if (DEBUG) {
Log.d(String.format(DEBUG_TAG, TAG), "salt is null. Generating one...");
}
// generate a new salt
SecureRandom secureRandom = new SecureRandom();
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(SALT_LENGTH, secureRandom);
SecretKey key = keyGenerator.generateKey();
salt = key.getEncoded();
// encode it
saltString = Base64.encodeToString(salt, Base64.DEFAULT);
if (DEBUG) {
Log.d(String.format(DEBUG_TAG, TAG), "Newly generated encoded salt: " + saltString);
}
// save to shared prefs
mSharedPrefs.edit().putString(SALT, saltString).apply();
} catch (NoSuchAlgorithmException e) {
Log.e(String.format(DEBUG_TAG, TAG), "Could not setup salt. This is bad.");
throw new RuntimeException("Unable to setup salt. Cannot run app.", e);
}
} else {
salt = Base64.decode(saltString, Base64.DEFAULT);
if (DEBUG) {
Log.d(String.format(DEBUG_TAG, TAG), "Salt loaded from disk: " + saltString);
}
}
return salt;
}
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
boolean append = false;
if (offset > 0) {
this.truncateFileAtURL(inputURL, offset);
append = true;
}
byte[] rawData;
if (isBinary) {
rawData = Base64.decode(data, Base64.DEFAULT);
} else {
rawData = data.getBytes();
}
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
try
{
byte buff[] = new byte[rawData.length];
FileOutputStream out = new FileOutputStream(this.filesystemPathForURL(inputURL), append);
try {
in.read(buff, 0, buff.length);
out.write(buff, 0, rawData.length);
out.flush();
} finally {
// Always close the output
out.close();
}
broadcastNewFile(inputURL);
}
catch (NullPointerException e)
{
// This is a bug in the Android implementation of the Java Stack
NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
throw realException;
}
return rawData.length;
}
public static int writeToUri(Context context, Filesystem filesystem, LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException {
Uri uri = filesystem.toNativeUri(inputURL);
OutputStream outputStream = null;
try {
outputStream = context.getContentResolver().openOutputStream(uri);
byte[] rawData;
if (isBinary) {
rawData = Base64.decode(data, Base64.DEFAULT);
} else {
rawData = data.getBytes(Charset.defaultCharset());
}
outputStream.write(rawData);
outputStream.flush();
outputStream.close();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
context.sendBroadcast(intent);
return rawData.length;
} catch (Exception e) {
NoModificationAllowedException exception = new NoModificationAllowedException("Couldn't write to file given its content URI");
exception.initCause(e);
throw exception;
}
}
@Override
public void parseText(XmlPullParser parser) {
if (inProtectionHeader) {
initData = Base64.decode(parser.getText(), Base64.DEFAULT);
}
}
public DNSServerItem(Context context, String name, String description, String sdns) throws Exception {
this.name = name;
this.description = description;
this.sdns = sdns;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean require_dnssec = sp.getBoolean("require_dnssec", false);
boolean require_nofilter = sp.getBoolean("require_nofilter", false);
boolean require_nolog = sp.getBoolean("require_nolog", false);
boolean use_dns_servers = sp.getBoolean("dnscrypt_servers", true);
boolean use_doh_servers = sp.getBoolean("doh_servers", true);
boolean use_ipv4_servers = sp.getBoolean("ipv4_servers", true);
boolean use_ipv6_servers = sp.getBoolean("ipv6_servers", false);
if (context.getText(R.string.package_name).toString().contains(".gp")) {
require_nofilter = true;
}
byte[] bin = Base64.decode(sdns.substring(0, 7).getBytes(), 16);
if (bin[0] == 0x01) {
protoDNSCrypt = true;
} else if (bin[0] == 0x02) {
protoDoH = true;
} else {
throw new Exception("Wrong sever type");
}
if (((bin[1]) & 1) == 1) {
this.dnssec = true;
}
if (((bin[1] >> 1) & 1) == 1) {
this.nolog = true;
}
if (((bin[1] >> 2) & 1) == 1) {
this.nofilter = true;
}
if (name.contains("v6") || name.contains("ip6")) {
ipv6 = true;
}
if (require_dnssec)
this.visibility = this.dnssec;
if (require_nofilter)
this.visibility = this.visibility && this.nofilter;
if (require_nolog)
this.visibility = this.visibility && this.nolog;
if (!use_dns_servers)
this.visibility = this.visibility && !this.protoDNSCrypt;
if (!use_doh_servers)
this.visibility = this.visibility && !this.protoDoH;
if (!use_ipv4_servers)
this.visibility = this.visibility && ipv6;
if (!use_ipv6_servers)
this.visibility = this.visibility && !ipv6;
}
@Override
public long writeBlock(OutputStream out, EncryptedOutputStream eos) throws IOException,InputOutputStreamException {
/* preparing some buffer and calculate the block size */
byte[] group_id = Base64.decode(status.getGroup().getGid(), Base64.NO_WRAP);
byte[] sender_id = Base64.decode(DatabaseFactory.getContactDatabase(RumbleApplication.getContext())
.getLocalContact().getUid(), Base64.NO_WRAP);
byte[] author_id = Base64.decode(status.getAuthor().getUid(), Base64.NO_WRAP);
byte[] author_name = status.getAuthor().getName().getBytes(Charset.forName("UTF-8"));
byte[] post = status.getPost().getBytes(Charset.forName("UTF-8"));
byte[] filename = status.getFileName().getBytes(Charset.forName("UTF-8"));
int length = MIN_PAYLOAD_SIZE +
author_name.length +
post.length +
filename.length;
/* prepare the block buffer */
ByteBuffer blockBuffer = ByteBuffer.allocate(length);
blockBuffer.put(group_id, 0, FIELD_GROUP_GID_SIZE);
blockBuffer.put(sender_id, 0, FIELD_SENDER_UID_SIZE);
blockBuffer.put(author_id, 0, FIELD_AUTHOR_UID_SIZE);
blockBuffer.put((byte) author_name.length);
blockBuffer.put(author_name, 0, author_name.length);
blockBuffer.putShort((short) post.length);
blockBuffer.put(post, 0, post.length);
blockBuffer.put((byte) filename.length);
blockBuffer.put(filename, 0, filename.length);
blockBuffer.putLong(status.getTimeOfCreation());
blockBuffer.putLong(status.getTTL());
blockBuffer.putShort((short) status.getHopCount());
blockBuffer.putShort((short) status.getHopLimit());
blockBuffer.putShort((short) status.getReplication());
blockBuffer.put((byte) status.getLike());
/* send the status and the block file */
header.setPayloadLength(length);
header.writeBlockHeader(out);
if(header.isEncrypted() && (eos != null)) {
eos.write(blockBuffer.array(), 0, length);
} else {
out.write(blockBuffer.array(), 0, length);
}
BlockDebug.d(TAG, "BlockStatus sent (" + length + " bytes): " + Arrays.toString(blockBuffer.array()));
return header.getBlockLength()+BlockHeader.BLOCK_HEADER_LENGTH;
}
public Realm getInstance() {
SharedPreferences sharedPreferences = G.context.getSharedPreferences("AES-256", Context.MODE_PRIVATE);
String stringArray = sharedPreferences.getString("myByteArray", null);
if (stringArray == null) {
byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
SharedPreferences.Editor editor = sharedPreferences.edit();
String saveThis = Base64.encodeToString(key, Base64.DEFAULT);
editor.putString("myByteArray", saveThis);
editor.commit();
}
byte[] mKey = Base64.decode(sharedPreferences.getString("myByteArray", null), Base64.DEFAULT);
RealmConfiguration newConfig = new RealmConfiguration.Builder()
.name(context.getResources().getString(R.string.encriptedDB))
.encryptionKey(mKey)
.schemaVersion(REALM_SCHEMA_VERSION)
.migration(new RealmMigration())
.build();
File newRealmFile = new File(newConfig.getPath());
if (newRealmFile.exists()) {
return Realm.getInstance(newConfig);
} else {
Realm realm = null;
try {
configuration = new RealmConfiguration.Builder().name(context.getResources().getString(R.string.planDB))
.schemaVersion(REALM_SCHEMA_VERSION)
.compactOnLaunch()
.migration(new RealmMigration()).build();
realm = Realm.getInstance(configuration);
realm.writeEncryptedCopyTo(newRealmFile, mKey);
realm.close();
Realm.deleteRealm(configuration);
return Realm.getInstance(newConfig);
} catch (OutOfMemoryError oom) {
realm.close();
return getPlainInstance();
} catch (Exception e) {
realm.close();
return getPlainInstance();
}
}
}
/**
* Gets the bitmap image.
*
* @param context the context
* @param base64 the base64
* @return the bitmap image
*/
public static Bitmap getBitmapImage(Context context, String base64) {
byte[] imageAsBytes = Base64.decode(base64.getBytes(), 5);
return BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length);
}