在Android中使用AES / CBC / PKCS5Padding进行不正确的解密

时间:2011-03-11 23:52:37

标签: android eclipse aes

我在Android(v2.2 API 8)中编写了以下代码,其中输入了纯文本,代码使用用户密码和随机盐对其进行加密,然后对其进行解密。运行代码后,我只能获得正确文本的一部分。例如,用户输入“Msg 1.5 to encrypt”,解密代码的结果为“Msg15toencrypg ==”

这是代码:     

 private EditText plain_msg;
    private EditText pwd;
    private TextView result;
    byte[] iv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    plain_msg = (EditText)findViewById(R.id.msg2encypt);
    pwd = (EditText)findViewById(R.id.password);
    result = (TextView)findViewById(R.id.decrypttxt);
}

public void mybuttonHandler(View view){
    String S_plain_msg = plain_msg.getText().toString();
    String S_pwd = pwd.getText().toString();
    setAES(S_plain_msg, S_pwd);
}


private byte[] generateSalt() throws NoSuchAlgorithmException{
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    byte[] ransalt = new byte[20];
    random.nextBytes(ransalt);
    return ransalt;
}


private void setAES(String msg, String pwd){
    try {
        //Generation of Key
        byte[] salt = generateSalt();
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHSHA256AND256BITAES-CBC-BC");
        KeySpec spec = new PBEKeySpec(pwd.toCharArray(),salt,1024, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        //Encryption process
        byte[] btxt = Base64.decode(msg, 0);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret); 
        AlgorithmParameters params = cipher.getParameters(); 
        iv = params.getParameterSpec(IvParameterSpec.class).getIV(); 
        byte[] ciphertext = cipher.doFinal(btxt);
        String encryptedtext = Base64.encodeToString(ciphertext, 0);

        //Decryption process
        byte[] bencryptxt = Base64.decode(encryptedtext, 0);
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); 
        ciphertext = cipher.doFinal(bencryptxt);
        String cipherS = Base64.encodeToString(ciphertext, 0); 

        result.setText(cipherS);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } 

}

}

有人知道为什么会发生这种情况或任何建议能够获得正确的解密信息吗?

1 个答案:

答案 0 :(得分:1)

如果你拿出加密解密,这应该是一个身份转换,剩下的就是:

Base64.encodeToString(Base64.decode(msg))

"Msg 1.5 to encrypt"不是Base64编码的字符串,不需要尝试解码它。如果你这样做,非Base64字符会被剥离,你得到一些字节,当编码回来时,看起来就像你得到的结果。