0
我正在使用代碼對base64編碼和加密c#中的數據,然後將文件發送到我的Android應用程序,我試圖解密它。Base64編碼數據問題(在c#中加密,在java中解密)
問題是,我得到一個「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));
}
不知道什麼是錯的。密鑰的長度是否必須是特定長度的字節數?
'bout.toByteArray()。toString()'沒有任何用處,當然不base64編碼任何東西。 –
已確認。然而,這是在我試圖解碼字符串的Android應用程序的Java代碼中。 – user1457227
Base64是一種編碼方式,無論如何都不加密,我的意思是你不會僅僅通過Base64編碼得到任何安全性 – BuddhiP