2012-12-15 52 views
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)); 
    } 

不知道什麼是錯的。密鑰的長度是否必須是特定長度的字節數?

+3

'bout.toByteArray()。toString()'沒有任何用處,當然不base64編碼任何東西。 –

+0

已確認。然而,這是在我試圖解碼字符串的Android應用程序的Java代碼中。 – user1457227

+0

Base64是一種編碼方式,無論如何都不加密,我的意思是你不會僅僅通過Base64編碼得到任何安全性 – BuddhiP

回答

2

評論已經確定了問題,如果您在此調試關鍵項目,您會立即看到它:您認爲您正在閱讀的基本64字符串。

您從bout的文件中收集您的字節。但是你試圖將它轉換爲字符串表示的做法並不像你想象的那樣。這將會是「[B @ 2352544e]」,只是Java的內部默認toString()來自陣列。相反,請嘗試new String(bout.toByteArray(), Charset.forName("US-ASCII"))