【问题标题】:C# AES CBC PKCS7 to PythonC# AES CBC PKCS7 到 Python
【发布时间】:2015-08-04 05:10:56
【问题描述】:

我目前正在尝试将简单的 AES 代码从 C# 转换为 Python。我对这两种语言都很熟悉,但我对加密领域(尤其是 AES)一无所知。我之前在 C# 中编写了这个 AES 代码,但现在我不知道如何让它在 Python 中工作(我正在使用 PyCrypto,因为 Python2.7 没有内置的 AES)。下面是我的 C# 代码:

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);
        }
    }
}

请注意,我还希望 BlockSize = 128、KeySize = 256、Padding = PKCS7 和 Cipher CBC for Python。提前致谢!

【问题讨论】:

  • 您只发布了 C# 版本。你的哪一部分 Python 代码不起作用?
  • @Carsten 嗨,我忘了澄清一下,我想获得有关将此 C# 转换为 Python 代码的帮助。我试图查看 PyCrypto 文档,但没有任何关于使用 PKCS7 填充/取消填充的内容。另外,我对 AES 加密的东西一无所知。

标签: c# python encryption aes pycrypto


【解决方案1】:

我意识到这个问题已经有将近一年的历史了,但我在寻找一些解决方案来与在其 AES 实现中使用 PKCS7 填充的遗留 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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-11
    • 2021-10-15
    • 2015-06-24
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多