java - 安卓 AES 问题

标签 java android jaxb aes

我需要在我的 Android 应用程序中实现 AES 算法,我在下面创建了这段代码,它可以像 Java 应用程序一样完美地工作,但 Android 似乎无法识别 JAXB。因为如您所见,我使用了 import javax.xml.bind.DatatypeConverter,因为我使用数据类型转换器将 byte[] 转换为字符串...

我尝试导入 jaxb jar,但它再次失败并出现此错误:Conversion to Dalvik format failed with error 1。

我该如何解决这个问题?

代码如下:

public class AESCrypt {

private final Cipher cipher;
private final SecretKeySpec key;
private AlgorithmParameterSpec spec;
private String encryptedText, decryptedText;
ByteArrayOutputStream baos;


public AESCrypt(String password) throws Exception {
    // hash password with SHA-256 and crop the output to 128-bit for key
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.update(password.getBytes("UTF-8"));
    byte[] keyBytes = new byte[16];
    System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);

    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    key = new SecretKeySpec(keyBytes, "AES");
    spec = getIV();
    }

public AlgorithmParameterSpec getIV() {
    AlgorithmParameterSpec ivspec;
    byte[] iv = new byte[cipher.getBlockSize()];
    new SecureRandom().nextBytes(iv);
    ivspec = new IvParameterSpec(iv);
    return ivspec;
    }

public String encrypt(String plainText) throws Exception {      
    cipher.init(Cipher.ENCRYPT_MODE, key, spec);
    byte[] encrypted = cipher.doFinal(plainText.getBytes());
    encryptedText = DatatypeConverter.printBase64Binary(encrypted);
    return encryptedText;
}

public String decrypt(String cryptedText) throws Exception {
    cipher.init(Cipher.DECRYPT_MODE, key, spec);
    byte[] bytes = DatatypeConverter.parseBase64Binary(cryptedText);
    byte[] decrypted = cipher.doFinal(bytes);
    decryptedText = new String(decrypted, "UTF-8");
    return decryptedText;
}   

最佳答案

Android 库有类 Base64 (android.util.Base64) 非常方便的将base64字符串转换为数据。

关于java - 安卓 AES 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15686527/

相关文章:

java - 如何从原生View获取属性

java - 使用 JAXB 解码字符串 XML 不起作用并仅返回空值

Android "can' t 打开文件“来自某些文件管理器

Android 偷偷解锁拍照

java - 没有时区的 Jaxb DateTime

java - ant "customization is not associated with any schema element"的 xjc 错误

java - 如何在 validator 的消息中写入java变量值

java - Eclipse:在调试 Java EE 时不显示变量

java - Spring MVC、 hibernate : Lazy initialization exception

java - 从十六进制值到字符串的转换