我正在使用代码对 c# 中的数据进行 Base-64 编码和加密,然后将文件发送到我的 Android 应用程序,在那里我尝试对其进行解密。
问题是,我得到一个“Base64 编码输入字符串的长度不是 4 的倍数”。解密时出错:
(Android 的 Java 代码):
try
{
Boolean inEvent = false;
// read encrypted file to string
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(filename));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte buffer[] = new byte[8192];
int read = fin.read(buffer);
while(read != -1) {
bout.write(buffer, 0, read);
read = fin.read(buffer);
}
fin.close();
String encryptedText = bout.toByteArray().toString();
String unencryptedText = "";
// decrypt string
try
{
unencryptedText = Decrypt(encryptedText, sKey); <-- error occurs here
}
catch ( Exception e)
{
alert(e.getMessage());
return sched;
}
解密方法:
protected String Decrypt(String text, String key) throws Exception
{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
byte[] keyBytes= new byte[16];
byte[] b= key.getBytes("UTF-8");
int len= b.length;
if (len > keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
byte [] results = cipher.doFinal(Base64Coder.decode(text));
return new String(results,"UTF-8");
}
最后,这是我用来加密的 c# 代码:
(c#代码):
string Encrypt(string textToEncrypt, string key)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 0x80;
rijndaelCipher.BlockSize = 0x80;
byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[0x10];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
}
不知道出了什么问题。密钥的长度是否必须是某个特定的字节数?