【发布时间】:2020-04-06 19:36:23
【问题描述】:
我知道,关于这个主题有很多线索 - 我已经阅读了大部分内容,但没有一个给我正确的答案。
我有以下代码:
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-version 在 Java8 中不起作用。
由于该更改,我不得不为 Base64.decode 和 Base64.encode 添加一个标志。在解码中工作正常:
byte[] decodedValue = Base64.decode(encodedText, Base64.DEFAULT);
但是当向 Base64.encode 添加一个标志时,会发生一些奇怪的事情:
当我写“return Base64.encode(”时,Android Studio 告诉我它需要一个 byte[] 输入和一个 int 标志。 所以我想,我可以简单地使用变量 encodedValue 作为第一个参数,因为那是一个字节 []。 作为下一个参数,我可以使用 Base64.DEFAULT,它是一个值为 0 的 int。 但Android Studio不同意:不兼容的类型,必选:java.lang.String,找到:byte[]。
为什么Android Studio需要一个String,当它第一次说它需要一个字节[]时??
其实,“为什么”并不重要,更重要的是:我该如何解决这个问题?
任何帮助将不胜感激。
【问题讨论】:
标签: java android encryption base64