java - Java中的Base64编码,使用android.util.Base64
问题描述
我知道,关于这个主题有很多线索——我已经阅读了大部分内容,但没有一个给我正确的答案。
我有以下代码:
import android.util.Base64;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Crypter {
public static void main(String[] args) {
String data = "Arnab C";
final String enc = DarKnight.getEncrypted(data);
System.out.println("Encrypted : " + enc);
System.out.println("Decrypted : " + DarKnight.getDecrypted(enc));
}
static class DarKnight {
private static final String ALGORITHM = "AES";
private static final byte[] SALT = "tHeApAcHe6410111".getBytes();// THE KEY MUST BE SAME
private static final String X = DarKnight.class.getSimpleName();
static String getEncrypted(String plainText) {
if (plainText == null) {
return null;
}
Key salt = getSalt();
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, salt);
byte[] encodedValue = cipher.doFinal(plainText.getBytes());
return Base64.encode(encodedValue,Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
throw new IllegalArgumentException("Failed to encrypt data");
}
public static String getDecrypted(String encodedText) {
if (encodedText == null) {
return null;
}
Key salt = getSalt();
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, salt);
byte[] decodedValue = Base64.decode(encodedText, Base64.DEFAULT);
byte[] decValue = cipher.doFinal(decodedValue);
return new String(decValue);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static Key getSalt() {
return new SecretKeySpec(SALT, ALGORITHM);
}
}
}
我从PHP 和 Java 之间的加密中复制了这个- 但改变了
import com.sun.org.apache.xml.internal.security.utils.Base64;
至
import android.util.Base64;
因为 apache-version 在 Java8 中不起作用。
由于这种变化,我不得不向 Base64.decode 和 Base64.encode 添加一个标志。在解码中工作正常:
byte[] decodedValue = Base64.decode(encodedText, Base64.DEFAULT);
但是当向 Base64.encode 添加一个标志时,会发生一些奇怪的事情:
当我写“return Base64.encode(”时,Android Studio 告诉我它需要一个 byte[] 输入和一个 int 标志。所以我想,我可以简单地使用变量 encodedValue 作为第一个参数,因为那是一个 byte[] . 作为下一个参数,我可以使用 Base64.DEFAULT,它是一个值为 0 的 int。但 Android Studio 不同意:不兼容的类型,必需:java.lang.String,找到:byte[]。
为什么 Android Studio 需要一个字符串,当它第一次说它需要一个 byte[] 时?
实际上,“为什么”并不重要,更重要的是:我该如何解决这个问题?
任何帮助,将不胜感激。
解决方案
使用encodeToString()
而不是encode()
. 第一个String
按您的函数返回类型返回 a ,后者返回 a byte[]
。
文档:https ://developer.android.com/reference/android/util/Base64
推荐阅读
- html - WooCommerce 热收据打印显示 HTML 标签
- reactjs - 在 React 中使用 If 语句
- amazon-web-services - ECS Fargate 在从 SQS 接收消息时如何在可用任务之间分配流量?
- php - 如何覆盖 function.php 中的 WooCommerce 总运费?
- javascript - 如何在 iframe 中提醒而不在 iframe 之外放置代码?
- java - findFragmentById 是否接受 FrameLayout 而不是 Fragment?
- javascript - 使用扩展运算符从 API 操作/过滤对象的道具
- lua - 如何防止 renderBlocks() 函数进入无限循环?
- c# - 执行 .net 方法登录某些服务器而不是其他服务器
- google-data-studio - 如何在 Data Studio 中使用嵌入式报表创建 RLS 过滤器