dvv*_*dvv 5 eclipse android 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();
}
}
Run Code Online (Sandbox Code Playgroud)
}
有人知道为什么会发生这种情况或任何建议能够获得正确的解密消息吗?
如果去掉加密解密,这应该是身份转换,剩下的是:
Base64.encodeToString(Base64.decode(msg))
Run Code Online (Sandbox Code Playgroud)
"Msg 1.5 to encrypt"不是 Base64 编码的字符串,无需尝试对其进行解码。如果您这样做,就像您所做的那样,非 Base64 字符会被剥离,并且您会得到一些字节,这些字节在编码回来时看起来就像您得到的结果。
| 归档时间: |
|
| 查看次数: |
3449 次 |
| 最近记录: |