我知道,有很多关于这个主题的帖子 - 我读过其中的大部分,但没有一个给我正确的答案。
我有以下代码:
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);
}
}
}
我从Encryption Between PHP & Java复制了这个- 但改变了
import com.sun.org.apache.xml.internal.security.utils.Base64;
至
import android.util.Base64;
因为 apache 版本在 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不同意:类型不兼容,Required:java.lang.String,found:byte[]。
为什么 Android Studio 第一次说需要 byte[] 时却需要 String ?
其实,“为什么”并不那么重要,更重要的是:我该如何解决这个问题?
如有任何帮助,我们将不胜感激。
最佳答案
使用encodeToString()
而不是encode()
。第一个返回一个String
,如您的函数返回类型所期望的那样,后者返回一个byte[]
。
文档:https://developer.android.com/reference/android/util/Base64
关于java - Java 中的 Base64 编码,使用 android.util.Base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321054/