Android的密码加密/解密密码、Android

2023-09-05 09:51:26 作者:自作多情必自毙°

我用密码来加密和解密消息:

I'm using cipher to encrypt and decrypt messages:

public String encrypt(String string) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
  cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
  byte[] stringBytes = string.getBytes("UTF-8");
  byte[] encryptedBytes = cipher.doFinal(stringBytes);
  return android.util.Base64.encodeToString(encryptedBytes, android.util.Base64.DEFAULT);
}

public String decrypt(String string) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
  cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
  byte[] stringBytes = android.util.Base64.decode(string.getBytes(), android.util.Base64.DEFAULT);
  byte[] decryptedBytes = cipher.doFinal(stringBytes);
  return new String(decryptedBytes,"UTF-8");
}

出于某种原因,虽然我用的Base64为en code和德$ C C字符串$,我仍然得到这个错误:

For some reason although I'm using Base64 to encode and decode the string, I still get this error:

javax.crypto.IllegalBlockSizeException:最后一个块不完整的解密

javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

我是什么做错了吗?

编辑:

这是我的JSONObject - 我试图解密M:

This is my JSONObject - I'm trying to decrypt the "m":

{"m":"Cu7FR2be0E6ZP2BrZaLU2ZWQSfycNg0-fPibphTIZno\r\n"}

奇怪的是,错误只出现在Android系统。我的服务器是用Java编写的,我使用Apache的Base64 EN codeR,它的伟大工程。

The weird thing is that the error only appears in Android. My server is written in Java and I'm using Apache Base64 encoder and it works great.

推荐答案

您需要转换BASE-64第一。

You need to convert Base-64 first.

codeED =加密(Base64.en code(MyString的,Base64.DEFAULT));

CODEED = encrypt(Base64.encode(MYSTRING, Base64.DEFAULT));

MyString的= Base64.de code(解密(codeED),Base64.DEFAULT);

MYSTRING = Base64.decode(decrypt(CODEED), Base64.DEFAULT);

这里是一个链接的http://android$c$cmonkey.blogspot.com/2010/03/how-to-base64-en$c$c-de$c$c-android.html