2015-05-22 59 views
1

我正在嘗試將簡單的AES代碼從C#轉換爲Python。我非常瞭解這兩種語言,但我不知道加密字段(特別是AES)。我之前在C#中編寫了這個AES代碼,但現在我不知道如何使它在Python中工作(我使用PyCrypto,因爲Python2.7沒有內置的AES)。下面是我的C#代碼:C#AES CBC PKCS7到Python

using System.Collections; 
using System.Text; 
using System.Security.Cryptography; 

namespace DefaultClasses 
{ 
    public class SimpleAES 
    { 
     private const string KEY = "someKey"; 
     private const string IV = "someIV"; 
     private AesCryptoServiceProvider _aes; 
     private ICryptoTransform _crypto; 

     public SimpleAES() 
     { 
      _aes = new AesCryptoServiceProvider(); 
      _aes.BlockSize = 128; 
      _aes.KeySize = 256; 
      _aes.Key = ASCIIEncoding.ASCII.GetBytes(KEY); 
      _aes.IV = ASCIIEncoding.ASCII.GetBytes(IV); 
      _aes.Padding = PaddingMode.PKCS7; 
      _aes.Mode = CipherMode.CBC; 
     } 

     public string encrypt(string message) 
     { 
      _crypto = _aes.CreateEncryptor(_aes.Key, _aes.IV); 
      byte[] encrypted = _crypto.TransformFinalBlock(
       ASCIIEncoding.ASCII.GetBytes(message), 0, ASCIIEncoding.ASCII.GetBytes(message).Length); 
      _crypto.Dispose(); 
      return System.Convert.ToBase64String(encrypted); 
     } 

     public string decrypt(string message) 
     { 
      _crypto = _aes.CreateDecryptor(_aes.Key, _aes.IV); 
      byte[] decrypted = _crypto.TransformFinalBlock(
       System.Convert.FromBase64String(message), 0, System.Convert.FromBase64String(message).Length); 
      _crypto.Dispose(); 
      return ASCIIEncoding.ASCII.GetString(decrypted); 
     } 
    } 
} 

請注意,我想也有塊大小= 128,密鑰長度= 256,填充= PKCS7和密碼CBC爲Python。感謝進步!

+0

你只發布了C#版本。你的哪部分Python代碼不起作用? – Carsten

+0

@Carsten你好,我忘了澄清,我想獲得幫助,將這個C#翻譯成Python代碼。我試圖查看PyCrypto文檔,但沒有關於使用PKCS7填充/解壓縮的說明。另外,我不知道AES加密的東西。 – Tim

+0

[使用PyCrypto AES 256加密和解密]的可能重複(http://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256) –

回答

0

我意識到這個問題已經快一年了,但是我在尋找一些解決方案來與使用PKCS7填充實現AES的遺留Windows進程進行通信時發現它。這是一個很好的例子,對我很好。希望它對其他人來說非常有用。我有相同的塊大小,密鑰大小和填充作爲問題作者指定。

from Crypto.Cipher import AES 
from pkcs7 import PKCS7Encoder 
import base64 

shared_key = "abc123ty9TW1abc123ty9TW1" #some random key for a working example 
IV = "rTF25nTrrTF25nTr" 

clear_text = "Testing 123" 
aes = AES.new(shared_key, AES.MODE_CBC, IV) 
aes.block_size = 128 
cipher_text = base64.b64encode(aes.encrypt(PKCS7Encoder().encode(clear_text))) 
print(cipher_text) 

aes_decrypter = AES.new(shared_key, AES.MODE_CBC, IV) 
aes_decrypter.block_size = 128 
clear_text = PKCS7Encoder().decode(aes_decrypter.decrypt(base64.b64decode(cipher_text))) 
print(clear_text) 

我使用的PKCS7填充工具是從Github project複製:

import binascii 
import StringIO 

class PKCS7Encoder(object): 
    def __init__(self, k=16): 
     self.k = k 

    ## @param text The padded text for which the padding is to be removed. 
    # @exception ValueError Raised when the input padding is missing or corrupt. 
    def decode(self, text): 
     ''' 
     Remove the PKCS#7 padding from a text string 
     ''' 
     nl = len(text) 
     val = int(binascii.hexlify(text[-1]), 16) 
     if val > self.k: 
      raise ValueError('Input is not padded or padding is corrupt') 

     l = nl - val 
     return text[:l] 

    ## @param text The text to encode. 
    def encode(self, text): 
     ''' 
     Pad an input string according to PKCS#7 
     ''' 
     l = len(text) 
     output = StringIO.StringIO() 
     val = self.k - (l % self.k) 
     for _ in xrange(val): 
      output.write('%02x' % val) 
     return text + binascii.unhexlify(output.getvalue())