2012-05-12 76 views
9

我想使用C#加密字符串並使用Python對其進行解密。加密/解密部分按預期工作(即,我能夠解密最初加密的字符串)。然而,Python返回的字符串在開始時有2個額外的字節,每個字符之間用空格分隔。在Python中解密使用.NET加密的字符串

**Original string** (before encryption -- encrypted using C#) = "Something you want to keep private with AES" 

**Decrypted string** (using Python) = "��S o m e t h i n g y o u w a n t t o k e e p p r i v a t e w i t h A E S" 

爲什麼我在字符串的開頭得到這兩個額外的字節?爲什麼解密字符串中的所有空格?任何想法爲什麼?

謝謝!

加密用C#

public static string Encrypt<T>(string value, string password, string salt) 
     where T : SymmetricAlgorithm, new() 
{ 
    DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt)); 

    SymmetricAlgorithm algorithm = new T(); 

    byte[] rgbKey = rgb.GetBytes(algorithm.KeySize >> 3); 
    byte[] rgbIV = rgb.GetBytes(algorithm.BlockSize >> 3); 

    ICryptoTransform transform = algorithm.CreateEncryptor(rgbKey, rgbIV); 

    using (MemoryStream buffer = new MemoryStream()) 
    { 
     using (CryptoStream stream = new CryptoStream(buffer, transform, CryptoStreamMode.Write)) 
     { 
      using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode)) 
      { 
       writer.Write(value); 
      } 
     } 

     return Convert.ToBase64String(buffer.ToArray()); 
    } 
} 


string plain = "Something you want to keep private with AES"; 
string encrypted = CipherUtility.Encrypt<AesManaged>(plain, "password", "salt"); 

解密與Python + pycrypto

import base64, sys 
import Crypto.Cipher.AES 

password = base64.b64decode('PSCIQGfoZidjEuWtJAdn1JGYzKDonk9YblI0uv96O8s=') # See rgbKey 
salt = base64.b64decode('ehjtnMiGhNhoxRuUzfBOXw==') # See rgbIV 
aes = Crypto.Cipher.AES.new(password, Crypto.Cipher.AES.MODE_CBC, salt) 
text = base64.b64decode('QpHn/fnraLswwI2Znt1xTaBzRtDqO4V5QI78jLOlVsbvaIs0yXMUlqJhQtK+su2hYn28G2vNyLkj0zLOs+RIjElCSqJv1aK/Yu8uY07oAeStqRt4u/DVUzoWlxdrlF0u') 

print aes.decrypt(text) 
+0

如何解密使用Python的.NET RSA算法加密? – Neo

回答

10

的字符串被編碼爲使用UTF-16編碼字節。前兩個字節是BOM。然後每個字符被編碼爲兩個字節。

從文檔Encoding.Unicode

獲取用於使用所述小端排序的字節順序的UTF-16格式編碼。

要獲取原始字符串,您需要將其從UTF-16字節解碼回Unicode字符串。

print aes.decrypt(text).decode('utf-16') 
+1

哇!謝謝Mark!現在我正在使用utf-16對字符串進行解碼(如您所建議的那樣),結果字符串是:「您希望保持AES的私密性」。任何想法如何擺脫最後4個字符? – Martin

+1

嘗試將SymmetricAlgorithm的填充設置爲零http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.padding。默認情況下,它使用PKCS7 –

+1

我正在尋找一種在.net/C#中加密並在python中解密的方法,並且遇到了這篇文章..我也得到了填充。我的額外E字符顯示爲「test2ЄЄ」。我試圖從PKCS7的.net端更改PaddingMode爲無,它沒有區別? –