Android AES问题

时间:2013-03-28 15:58:33

标签: java android jaxb aes

我需要在我的Android应用程序中实现AES算法,我在下面创建了这个代码,它完全可以作为Java应用程序工作,但似乎Android不识别JAXB。因为你可以看到我使用import javax.xml.bind.DatatypeConverter,因为我使用数据类型转换器从byte []转换为字符串...

我尝试导入jaxb jar,但是再次失败并出现此错误:转换为Dalvik格式失败,错误为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;
}   

}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

encryptedText转换为byte[]

byte[] encryptedTextByte = Base64.decode(encryptedText, 1);