1

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

我尝试导入 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;
}   

}

4

2 回答 2

2

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

于 2013-03-28T16:59:19.530 回答
0

转换 encryptedTextbyte[]

byte[] encryptedTextByte = Base64.decode(encryptedText, 1);
于 2016-06-02T08:40:50.380 回答