在解密我得到
W/System.err(517): javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
我的加密和解密代码如下。我搜索了整个论坛也遇到了同样的问题,但我的代码无法正常工作。
还有一个问题,或者您可以说只是好奇,当我单击按钮时,我可以看到加密的字符串,但是一次又一次地按下按钮会在相同的输入文本上给我不同的加密字符串,只有最后 4 个字符发生变化....认为解密后获得相同的输入字符串将是一个问题。
public class MainActivity extends Activity implements OnClickListener {
EditText ed1, ed2, ed3;
private final char[] PASSWORD = "abcdefghijklmnop".toCharArray();
private byte[] SALT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting the SALT to android_id
SALT = Secure.getString(getContentResolver(), Secure.ANDROID_ID).getBytes();
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
ed1 = (EditText) findViewById(R.id.editText1);
ed2 = (EditText) findViewById(R.id.editText2);
ed3 = (EditText) findViewById(R.id.editText3);
}
public void onClick(View v)
{
String encrypted, decrypted, userpass = ed1.getText().toString().trim();
encrypted = encrypt(userpass);
ed2.setText(encrypted);
decrypted = decrypt(encrypted);
ed3.setText(decrypted);
}
public String encrypt(String original)
{
SecretKeyFactory secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = secretKey.generateSecret(new PBEKeySpec(PASSWORD));
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT,20));
String encrypted = cipher.doFinal(original.getBytes("UTF-8")).toString();
return encrypted;
}
public String decrypt(String original)
{
SecretKeyFactory secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = secretKey.generateSecret(new PBEKeySpec(PASSWORD));
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT,10));
String decrypted = cipher.doFinal(original.getBytes("UTF-8")).toString();
return decrypted;
}
}