【发布时间】:2011-03-11 23:52:36
【问题描述】:
我在 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();
}
}
}
有人可以知道为什么会发生这种情况或有什么建议可以得到正确的解密消息吗?
【问题讨论】:
-
就像在黑暗中随机刺伤一样,如果将 PKCS5PAdding 替换为 NoPadding 会怎样?
-
好的,我使用 getBytes("UTF-8") 和 new String(byte[], "UTF-8") 解决它。