标签归档:padding

使用PyCrypto AES 256加密和解密

问题:使用PyCrypto AES 256加密和解密

我正在尝试使用PyCrypto构建两个接受两个参数的函数:消息和密钥,然后对消息进行加密/解密。

我在网络上找到了几个链接可以帮助我,但每个链接都有缺陷:

在codekoala上,此代码使用os.urandom,PyCrypto不建议这样做。

此外,不能保证我提供给函数的键具有预期的确切长度。我该怎么做才能做到这一点?

另外,有几种模式,推荐哪种?我不知道该怎么用:/

最后,IV到底是什么?我可以提供不同的IV进行加密和解密,还是返回不同的结果?

编辑:删除了代码部分,因为它不安全。

I’m trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message.

I found several links on the web to help me out, but each one of them has flaws:

This one at codekoala uses os.urandom, which is discouraged by PyCrypto.

Moreover, the key I give to the function is not guaranteed to have the exact length expected. What can I do to make that happen ?

Also, there are several modes, which one is recommended? I don’t know what to use :/

Finally, what exactly is the IV? Can I provide a different IV for encrypting and decrypting, or will this return in a different result?

Edit: Removed the code part since it was not secure.


回答 0

这是我的实现,并通过一些修复为我工作,并用32字节和iv到16字节增强了密钥和秘密短语的对齐方式:

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):

    def __init__(self, key): 
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes:

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):

    def __init__(self, key): 
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

回答 1

您可能需要以下两个功能:padunpad当输入的长度不是BLOCK_SIZE的倍数时,填充(执行加密时)和-取消填充(执行解密时)。

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[:-ord(s[len(s)-1:])]

所以您要问密钥的长度?您可以使用密钥的md5sum而不是直接使用它。

而且,根据我使用PyCrypto的经验,在输入相同的情况下,IV用于混合加密输出,因此将IV选择为随机字符串,并将其用作加密输出的一部分,然后用它来解密消息。

这是我的实现,希望它将对您有用:

import base64
from Crypto.Cipher import AES
from Crypto import Random

class AESCipher:
    def __init__( self, key ):
        self.key = key

    def encrypt( self, raw ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( iv + cipher.encrypt( raw ) ) 

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc[16:] ))

You may need the following two functions: pad– to pad(when doing encryption) and unpad– to unpad (when doing decryption) when the length of input is not a multiple of BLOCK_SIZE.

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[:-ord(s[len(s)-1:])]

So you’re asking the length of key? You can use the md5sum of the key rather than use it directly.

More, according to my little experience of using PyCrypto, the IV is used to mix up the output of a encryption when input is same, so the IV is chosen as a random string, and use it as part of the encryption output, and then use it to decrypt the message.

And here’s my implementation, hope it will be useful for you:

import base64
from Crypto.Cipher import AES
from Crypto import Random

class AESCipher:
    def __init__( self, key ):
        self.key = key

    def encrypt( self, raw ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( iv + cipher.encrypt( raw ) ) 

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc[16:] ))

回答 2

让我解决您有关“模式”的问题。AES256是一种分组密码。它以32字节的密钥和16字节的字符串(称为块)作为输入,并输出一个块。我们在操作模式下使用AES 进行加密。上面的解决方案建议使用CBC,这是一个示例。另一个称为CTR,使用起来更容易一些:

from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random

# AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256).
key_bytes = 32

# Takes as input a 32-byte key and an arbitrary-length plaintext and returns a
# pair (iv, ciphtertext). "iv" stands for initialization vector.
def encrypt(key, plaintext):
    assert len(key) == key_bytes

    # Choose a random, 16-byte IV.
    iv = Random.new().read(AES.block_size)

    # Convert the IV to a Python integer.
    iv_int = int(binascii.hexlify(iv), 16) 

    # Create a new Counter object with IV = iv_int.
    ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)

    # Create AES-CTR cipher.
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)

    # Encrypt and return IV and ciphertext.
    ciphertext = aes.encrypt(plaintext)
    return (iv, ciphertext)

# Takes as input a 32-byte key, a 16-byte IV, and a ciphertext, and outputs the
# corresponding plaintext.
def decrypt(key, iv, ciphertext):
    assert len(key) == key_bytes

    # Initialize counter for decryption. iv should be the same as the output of
    # encrypt().
    iv_int = int(iv.encode('hex'), 16) 
    ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)

    # Create AES-CTR cipher.
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)

    # Decrypt and return the plaintext.
    plaintext = aes.decrypt(ciphertext)
    return plaintext

(iv, ciphertext) = encrypt(key, 'hella')
print decrypt(key, iv, ciphertext)

这通常称为AES-CTR。在将AES-CBC与PyCrypto结合使用时,我建议您谨慎使用。原因是它要求您指定填充方案,如其他给出的解决方案所示。通常,如果您对填充不太谨慎,则可以完全破坏加密的攻击

现在,必须注意,密钥必须是一个随机的32字节字符串;密码足够。通常,密钥是这样生成的:

# Nominal way to generate a fresh key. This calls the system's random number
# generator (RNG).
key1 = Random.new().read(key_bytes)

密钥也可以从密码派生

# It's also possible to derive a key from a password, but it's important that
# the password have high entropy, meaning difficult to predict.
password = "This is a rather weak password."

# For added # security, we add a "salt", which increases the entropy.
#
# In this example, we use the same RNG to produce the salt that we used to
# produce key1.
salt_bytes = 8 
salt = Random.new().read(salt_bytes)

# Stands for "Password-based key derivation function 2"
key2 = PBKDF2(password, salt, key_bytes)

上面的一些解决方案建议使用SHA256派生密钥,但这通常被认为是不良的加密做法。查阅Wikipedia,了解更多有关操作模式的信息。

Let me address your question about “modes.” AES256 is a kind of block cipher. It takes as input a 32-byte key and a 16-byte string, called the block and outputs a block. We use AES in a mode of operation in order to encrypt. The solutions above suggest using CBC, which is one example. Another is called CTR, and it’s somewhat easier to use:

from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random

# AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256).
key_bytes = 32

# Takes as input a 32-byte key and an arbitrary-length plaintext and returns a
# pair (iv, ciphtertext). "iv" stands for initialization vector.
def encrypt(key, plaintext):
    assert len(key) == key_bytes

    # Choose a random, 16-byte IV.
    iv = Random.new().read(AES.block_size)

    # Convert the IV to a Python integer.
    iv_int = int(binascii.hexlify(iv), 16) 

    # Create a new Counter object with IV = iv_int.
    ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)

    # Create AES-CTR cipher.
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)

    # Encrypt and return IV and ciphertext.
    ciphertext = aes.encrypt(plaintext)
    return (iv, ciphertext)

# Takes as input a 32-byte key, a 16-byte IV, and a ciphertext, and outputs the
# corresponding plaintext.
def decrypt(key, iv, ciphertext):
    assert len(key) == key_bytes

    # Initialize counter for decryption. iv should be the same as the output of
    # encrypt().
    iv_int = int(iv.encode('hex'), 16) 
    ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)

    # Create AES-CTR cipher.
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)

    # Decrypt and return the plaintext.
    plaintext = aes.decrypt(ciphertext)
    return plaintext

(iv, ciphertext) = encrypt(key, 'hella')
print decrypt(key, iv, ciphertext)

This is often referred to as AES-CTR. I would advise caution in using AES-CBC with PyCrypto. The reason is that it requires you to specify the padding scheme, as exemplified by the other solutions given. In general, if you’re not very careful about the padding, there are attacks that completely break encryption!

Now, it’s important to note that the key must be a random, 32-byte string; a password does not suffice. Normally, the key is generated like so:

# Nominal way to generate a fresh key. This calls the system's random number
# generator (RNG).
key1 = Random.new().read(key_bytes)

A key may be derived from a password, too:

# It's also possible to derive a key from a password, but it's important that
# the password have high entropy, meaning difficult to predict.
password = "This is a rather weak password."

# For added # security, we add a "salt", which increases the entropy.
#
# In this example, we use the same RNG to produce the salt that we used to
# produce key1.
salt_bytes = 8 
salt = Random.new().read(salt_bytes)

# Stands for "Password-based key derivation function 2"
key2 = PBKDF2(password, salt, key_bytes)

Some solutions above suggest using SHA256 for deriving the key, but this is generally considered bad cryptographic practice. Check out wikipedia for more on modes of operation.


回答 3

对于想使用urlsafe_b64encode和urlsafe_b64decode的用户,以下是对我有用的版本(花了一些时间处理unicode问题之后)

BS = 16
key = hashlib.md5(settings.SECRET_KEY).hexdigest()[:BS]
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[:-ord(s[len(s)-1:])]

class AESCipher:
    def __init__(self, key):
        self.key = key

    def encrypt(self, raw):
        raw = pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.urlsafe_b64encode(iv + cipher.encrypt(raw)) 

    def decrypt(self, enc):
        enc = base64.urlsafe_b64decode(enc.encode('utf-8'))
        iv = enc[:BS]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return unpad(cipher.decrypt(enc[BS:]))

For someone who would like to use urlsafe_b64encode and urlsafe_b64decode, here are the version that’re working for me (after spending some time with the unicode issue)

BS = 16
key = hashlib.md5(settings.SECRET_KEY).hexdigest()[:BS]
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[:-ord(s[len(s)-1:])]

class AESCipher:
    def __init__(self, key):
        self.key = key

    def encrypt(self, raw):
        raw = pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.urlsafe_b64encode(iv + cipher.encrypt(raw)) 

    def decrypt(self, enc):
        enc = base64.urlsafe_b64decode(enc.encode('utf-8'))
        iv = enc[:BS]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return unpad(cipher.decrypt(enc[BS:]))

回答 4

您可以使用SHA-1或SHA-256之类的加密哈希函数(不是 Python的内置函数)从任意密码中获取密码短语hash。Python在其标准库中包括对两者的支持:

import hashlib

hashlib.sha1("this is my awesome password").digest() # => a 20 byte string
hashlib.sha256("another awesome password").digest() # => a 32 byte string

您可以仅使用[:16]或来截断加密哈希值,[:24]并且它将在指定长度内保持其安全性。

You can get a passphrase out of an arbitrary password by using a cryptographic hash function (NOT Python’s builtin hash) like SHA-1 or SHA-256. Python includes support for both in its standard library:

import hashlib

hashlib.sha1("this is my awesome password").digest() # => a 20 byte string
hashlib.sha256("another awesome password").digest() # => a 32 byte string

You can truncate a cryptographic hash value just by using [:16] or [:24] and it will retain its security up to the length you specify.


回答 5

感谢其他启发但对我不起作用的答案。

在花了数小时试图弄清楚它是如何工作之后,我想到了下面的实现,并带有最新的PyCryptodomex库(这是我如何在Windows上的virtualenv .. phew中成功设置它的代理)

。在实现时,请记住写下填充,编码,加密步骤(反之亦然)。您必须打包和拆包,并牢记顺序。

导入base64
导入hashlib
从Cryptodome.Cipher导入AES
从Cryptodome.Random导入get_random_bytes

__key__ = hashlib.sha256(b'16个字符的键').digest()

def加密(原始):
    BS = AES.block_size
    pad = lambda s:s +(BS-len%BS)* chr(BS-len%BS)

    原始= base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(AES.block_size)
    密码= AES.new(密钥= __密钥__,模式= AES.MODE_CFB,iv = iv)
    返回base64.b64encode(iv + cipher.encrypt(raw))

def解密(enc):
    unpad = lambda s:s [:-ord(s [-1:])]

    enc = base64.b64decode(enc)
    iv = enc [:AES.block_size]
    cipher = AES.new(__ key__,AES.MODE_CFB,iv)
    返回unpad(base64.b64decode(cipher.decrypt(enc [AES.block_size:]))。decode('utf8'))

Grateful for the other answers which inspired but didn’t work for me.

After spending hours trying to figure out how it works, I came up with the implementation below with the newest PyCryptodomex library (it is another story how I managed to set it up behind proxy, on Windows, in a virtualenv.. phew)

Working on your implementation, remember to write down padding, encoding, encrypting steps (and vice versa). You have to pack and unpack keeping in mind the order.

import base64
import hashlib
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

__key__ = hashlib.sha256(b'16-character key').digest()

def encrypt(raw):
    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(AES.block_size)
    cipher = AES.new(key= __key__, mode= AES.MODE_CFB,iv= iv)
    return base64.b64encode(iv + cipher.encrypt(raw))

def decrypt(enc):
    unpad = lambda s: s[:-ord(s[-1:])]

    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(__key__, AES.MODE_CFB, iv)
    return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))

回答 6

为了他人的利益,这是我结合@Cyril和@Marcus的答案所获得的解密实现。假定此消息是通过HTTP请求传入的,该消息带有quoted和base64编码。

import base64
import urllib2
from Crypto.Cipher import AES


def decrypt(quotedEncodedEncrypted):
    key = 'SecretKey'

    encodedEncrypted = urllib2.unquote(quotedEncodedEncrypted)

    cipher = AES.new(key)
    decrypted = cipher.decrypt(base64.b64decode(encodedEncrypted))[:16]

    for i in range(1, len(base64.b64decode(encodedEncrypted))/16):
        cipher = AES.new(key, AES.MODE_CBC, base64.b64decode(encodedEncrypted)[(i-1)*16:i*16])
        decrypted += cipher.decrypt(base64.b64decode(encodedEncrypted)[i*16:])[:16]

    return decrypted.strip()

For the benefit of others, here is my decryption implementation which I got to by combining the answers of @Cyril and @Marcus. This assumes that this coming in via HTTP Request with the encryptedText quoted and base64 encoded.

import base64
import urllib2
from Crypto.Cipher import AES


def decrypt(quotedEncodedEncrypted):
    key = 'SecretKey'

    encodedEncrypted = urllib2.unquote(quotedEncodedEncrypted)

    cipher = AES.new(key)
    decrypted = cipher.decrypt(base64.b64decode(encodedEncrypted))[:16]

    for i in range(1, len(base64.b64decode(encodedEncrypted))/16):
        cipher = AES.new(key, AES.MODE_CBC, base64.b64decode(encodedEncrypted)[(i-1)*16:i*16])
        decrypted += cipher.decrypt(base64.b64decode(encodedEncrypted)[i*16:])[:16]

    return decrypted.strip()

回答 7

对此的另一种看法(很大程度上来自上述解决方案),但

  • 使用null进行填充
  • 不使用lambda(从不成为粉丝)
  • 用python 2.7和3.6.5测试

    #!/usr/bin/python2.7
    # you'll have to adjust for your setup, e.g., #!/usr/bin/python3
    
    
    import base64, re
    from Crypto.Cipher import AES
    from Crypto import Random
    from django.conf import settings
    
    class AESCipher:
        """
          Usage:
          aes = AESCipher( settings.SECRET_KEY[:16], 32)
          encryp_msg = aes.encrypt( 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppp' )
          msg = aes.decrypt( encryp_msg )
          print("'{}'".format(msg))
        """
        def __init__(self, key, blk_sz):
            self.key = key
            self.blk_sz = blk_sz
    
        def encrypt( self, raw ):
            if raw is None or len(raw) == 0:
                raise NameError("No value given to encrypt")
            raw = raw + '\0' * (self.blk_sz - len(raw) % self.blk_sz)
            raw = raw.encode('utf-8')
            iv = Random.new().read( AES.block_size )
            cipher = AES.new( self.key.encode('utf-8'), AES.MODE_CBC, iv )
            return base64.b64encode( iv + cipher.encrypt( raw ) ).decode('utf-8')
    
        def decrypt( self, enc ):
            if enc is None or len(enc) == 0:
                raise NameError("No value given to decrypt")
            enc = base64.b64decode(enc)
            iv = enc[:16]
            cipher = AES.new(self.key.encode('utf-8'), AES.MODE_CBC, iv )
            return re.sub(b'\x00*$', b'', cipher.decrypt( enc[16:])).decode('utf-8')

Another take on this (heavily derived from solutions above) but

  • uses null for padding
  • does not use lambda (never been a fan)
  • tested with python 2.7 and 3.6.5

    #!/usr/bin/python2.7
    # you'll have to adjust for your setup, e.g., #!/usr/bin/python3
    
    
    import base64, re
    from Crypto.Cipher import AES
    from Crypto import Random
    from django.conf import settings
    
    class AESCipher:
        """
          Usage:
          aes = AESCipher( settings.SECRET_KEY[:16], 32)
          encryp_msg = aes.encrypt( 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppp' )
          msg = aes.decrypt( encryp_msg )
          print("'{}'".format(msg))
        """
        def __init__(self, key, blk_sz):
            self.key = key
            self.blk_sz = blk_sz
    
        def encrypt( self, raw ):
            if raw is None or len(raw) == 0:
                raise NameError("No value given to encrypt")
            raw = raw + '\0' * (self.blk_sz - len(raw) % self.blk_sz)
            raw = raw.encode('utf-8')
            iv = Random.new().read( AES.block_size )
            cipher = AES.new( self.key.encode('utf-8'), AES.MODE_CBC, iv )
            return base64.b64encode( iv + cipher.encrypt( raw ) ).decode('utf-8')
    
        def decrypt( self, enc ):
            if enc is None or len(enc) == 0:
                raise NameError("No value given to decrypt")
            enc = base64.b64decode(enc)
            iv = enc[:16]
            cipher = AES.new(self.key.encode('utf-8'), AES.MODE_CBC, iv )
            return re.sub(b'\x00*$', b'', cipher.decrypt( enc[16:])).decode('utf-8')
    

回答 8

我都用了CryptoPyCryptodomex库,它是速度极快…

import base64
import hashlib
from Cryptodome.Cipher import AES as domeAES
from Cryptodome.Random import get_random_bytes
from Crypto import Random
from Crypto.Cipher import AES as cryptoAES

BLOCK_SIZE = AES.block_size

key = "my_secret_key".encode()
__key__ = hashlib.sha256(key).digest()
print(__key__)

def encrypt(raw):
    BS = cryptoAES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(cryptoAES.block_size)
    cipher = cryptoAES.new(key= __key__, mode= cryptoAES.MODE_CFB,iv= iv)
    a= base64.b64encode(iv + cipher.encrypt(raw))
    IV = Random.new().read(BLOCK_SIZE)
    aes = domeAES.new(__key__, domeAES.MODE_CFB, IV)
    b = base64.b64encode(IV + aes.encrypt(a))
    return b

def decrypt(enc):
    passphrase = __key__
    encrypted = base64.b64decode(enc)
    IV = encrypted[:BLOCK_SIZE]
    aes = domeAES.new(passphrase, domeAES.MODE_CFB, IV)
    enc = aes.decrypt(encrypted[BLOCK_SIZE:])
    unpad = lambda s: s[:-ord(s[-1:])]
    enc = base64.b64decode(enc)
    iv = enc[:cryptoAES.block_size]
    cipher = cryptoAES.new(__key__, cryptoAES.MODE_CFB, iv)
    b=  unpad(base64.b64decode(cipher.decrypt(enc[cryptoAES.block_size:])).decode('utf8'))
    return b

encrypted_data =encrypt("Hi Steven!!!!!")
print(encrypted_data)
print("=======")
decrypted_data = decrypt(encrypted_data)
print(decrypted_data)

I have used both Crypto and PyCryptodomex library and it is blazing fast…

import base64
import hashlib
from Cryptodome.Cipher import AES as domeAES
from Cryptodome.Random import get_random_bytes
from Crypto import Random
from Crypto.Cipher import AES as cryptoAES

BLOCK_SIZE = AES.block_size

key = "my_secret_key".encode()
__key__ = hashlib.sha256(key).digest()
print(__key__)

def encrypt(raw):
    BS = cryptoAES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(cryptoAES.block_size)
    cipher = cryptoAES.new(key= __key__, mode= cryptoAES.MODE_CFB,iv= iv)
    a= base64.b64encode(iv + cipher.encrypt(raw))
    IV = Random.new().read(BLOCK_SIZE)
    aes = domeAES.new(__key__, domeAES.MODE_CFB, IV)
    b = base64.b64encode(IV + aes.encrypt(a))
    return b

def decrypt(enc):
    passphrase = __key__
    encrypted = base64.b64decode(enc)
    IV = encrypted[:BLOCK_SIZE]
    aes = domeAES.new(passphrase, domeAES.MODE_CFB, IV)
    enc = aes.decrypt(encrypted[BLOCK_SIZE:])
    unpad = lambda s: s[:-ord(s[-1:])]
    enc = base64.b64decode(enc)
    iv = enc[:cryptoAES.block_size]
    cipher = cryptoAES.new(__key__, cryptoAES.MODE_CFB, iv)
    b=  unpad(base64.b64decode(cipher.decrypt(enc[cryptoAES.block_size:])).decode('utf8'))
    return b

encrypted_data =encrypt("Hi Steven!!!!!")
print(encrypted_data)
print("=======")
decrypted_data = decrypt(encrypted_data)
print(decrypted_data)

回答 9

还不晚,但是我认为这将非常有帮助。没有人提及像PKCS#7填充这样的使用方案。您可以使用它代替以前的函数进行填充(加密时)和取消填充(解密时)。i将在下面提供完整的源代码。

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
import pkcs7
class Encryption:

    def __init__(self):
        pass

    def Encrypt(self, PlainText, SecurePassword):
        pw_encode = SecurePassword.encode('utf-8')
        text_encode = PlainText.encode('utf-8')

        key = hashlib.sha256(pw_encode).digest()
        iv = Random.new().read(AES.block_size)

        cipher = AES.new(key, AES.MODE_CBC, iv)
        pad_text = pkcs7.encode(text_encode)
        msg = iv + cipher.encrypt(pad_text)

        EncodeMsg = base64.b64encode(msg)
        return EncodeMsg

    def Decrypt(self, Encrypted, SecurePassword):
        decodbase64 = base64.b64decode(Encrypted.decode("utf-8"))
        pw_encode = SecurePassword.decode('utf-8')

        iv = decodbase64[:AES.block_size]
        key = hashlib.sha256(pw_encode).digest()

        cipher = AES.new(key, AES.MODE_CBC, iv)
        msg = cipher.decrypt(decodbase64[AES.block_size:])
        pad_text = pkcs7.decode(msg)

        decryptedString = pad_text.decode('utf-8')
        return decryptedString

import StringIO
import binascii


def decode(text, k=16):
    nl = len(text)
    val = int(binascii.hexlify(text[-1]), 16)
    if val > k:
        raise ValueError('Input is not padded or padding is corrupt')

    l = nl - val
    return text[:l]


def encode(text, k=16):
    l = len(text)
    output = StringIO.StringIO()
    val = k - (l % k)
    for _ in xrange(val):
        output.write('%02x' % val)
    return text + binascii.unhexlify(output.getvalue())

It’s little late but i think this will be very helpful. No one mention about use scheme like PKCS#7 padding. You can use it instead the previous functions to pad(when do encryption) and unpad(when do decryption).i will provide the full Source Code below.

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
import pkcs7
class Encryption:

    def __init__(self):
        pass

    def Encrypt(self, PlainText, SecurePassword):
        pw_encode = SecurePassword.encode('utf-8')
        text_encode = PlainText.encode('utf-8')

        key = hashlib.sha256(pw_encode).digest()
        iv = Random.new().read(AES.block_size)

        cipher = AES.new(key, AES.MODE_CBC, iv)
        pad_text = pkcs7.encode(text_encode)
        msg = iv + cipher.encrypt(pad_text)

        EncodeMsg = base64.b64encode(msg)
        return EncodeMsg

    def Decrypt(self, Encrypted, SecurePassword):
        decodbase64 = base64.b64decode(Encrypted.decode("utf-8"))
        pw_encode = SecurePassword.decode('utf-8')

        iv = decodbase64[:AES.block_size]
        key = hashlib.sha256(pw_encode).digest()

        cipher = AES.new(key, AES.MODE_CBC, iv)
        msg = cipher.decrypt(decodbase64[AES.block_size:])
        pad_text = pkcs7.decode(msg)

        decryptedString = pad_text.decode('utf-8')
        return decryptedString

import StringIO
import binascii


def decode(text, k=16):
    nl = len(text)
    val = int(binascii.hexlify(text[-1]), 16)
    if val > k:
        raise ValueError('Input is not padded or padding is corrupt')

    l = nl - val
    return text[:l]


def encode(text, k=16):
    l = len(text)
    output = StringIO.StringIO()
    val = k - (l % k)
    for _ in xrange(val):
        output.write('%02x' % val)
    return text + binascii.unhexlify(output.getvalue())


回答 10

https://stackoverflow.com/a/21928790/11402877

兼容的utf-8编码

def _pad(self, s):
    s = s.encode()
    res = s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs).encode()
    return res

https://stackoverflow.com/a/21928790/11402877

compatible utf-8 encoding

def _pad(self, s):
    s = s.encode()
    res = s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs).encode()
    return res

回答 11

from Crypto import Random
from Crypto.Cipher import AES
import base64

BLOCK_SIZE=16
def trans(key):
     return md5.new(key).digest()

def encrypt(message, passphrase):
    passphrase = trans(passphrase)
    IV = Random.new().read(BLOCK_SIZE)
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return base64.b64encode(IV + aes.encrypt(message))

def decrypt(encrypted, passphrase):
    passphrase = trans(passphrase)
    encrypted = base64.b64decode(encrypted)
    IV = encrypted[:BLOCK_SIZE]
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return aes.decrypt(encrypted[BLOCK_SIZE:])
from Crypto import Random
from Crypto.Cipher import AES
import base64

BLOCK_SIZE=16
def trans(key):
     return md5.new(key).digest()

def encrypt(message, passphrase):
    passphrase = trans(passphrase)
    IV = Random.new().read(BLOCK_SIZE)
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return base64.b64encode(IV + aes.encrypt(message))

def decrypt(encrypted, passphrase):
    passphrase = trans(passphrase)
    encrypted = base64.b64decode(encrypted)
    IV = encrypted[:BLOCK_SIZE]
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return aes.decrypt(encrypted[BLOCK_SIZE:])

Python strftime-日期前无0?

问题:Python strftime-日期前无0?

使用Python时strftime,有一种方法可以删除日期的第一个0(如果它在10之前)。所以011?找不到%东西吗?

谢谢!

When using Python strftime, is there a way to remove the first 0 of the date if it’s before the 10th, ie. so 01 is 1? Can’t find a %thingy for that?

Thanks!


回答 0

实际上,我遇到了同样的问题,并且我意识到,如果在%和字母之间添加连字符,则可以删除前导零。

例如%Y/%-m/%-d

这仅适用于Unix(Linux,OS X),而不适用于Windows(包括Cygwin)。在Windows上,您可以使用#,例如%Y/%#m/%#d

Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter, you can remove the leading zero.

For example %Y/%-m/%-d.

This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %Y/%#m/%#d.


回答 1

format从python2.6开始,随着方法的出现,我们可以做这种事情:

>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'

尽管可能超出原始问题的范围,但是对于更有趣的格式,您可以执行以下操作:

>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'

从python3.6开始,这可以表示为嵌入式格式的字符串

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'

We can do this sort of thing with the advent of the format method since python2.6:

>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'

Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:

>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'

And as of python3.6, this can be expressed as an inline formatted string:

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'

回答 2

%根据http://docs.python.org/library/time.html的介绍,某些平台可能支持字母之间的宽度和精度规范(例如月份中的“ d”),但这绝对是不可移植的解决方案(例如,在我的Mac上不起作用;-)。也许您可以在之后使用字符串替换(或RE,对于真正讨厌的格式)strftime进行补救?例如:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

Some platforms may support width and precision specification between % and the letter (such as ‘d’ for day of month), according to http://docs.python.org/library/time.html — but it’s definitely a non-portable solution (e.g. doesn’t work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

回答 3

strftime()GNU C库支持的修饰符的文档。(就像之前说过的那样,它可能不是便携式的。)您可能感兴趣的是:

  • %e而不是%d将月份中的前导零替换为空格

它适用于我的Python(在Linux上)。我不知道它是否对您有用。

Here is the documentation of the modifiers supported by strftime() in the GNU C library. (Like people said before, it might not be portable.) Of interest to you might be:

  • %e instead of %d will replace leading zero in day of month with a space

It works on my Python (on Linux). I don’t know if it will work on yours.


回答 4

>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'
>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','')
'5/5/2011'

回答 5

在Windows上,添加一个’#’,例如’%#m /%#d /%Y%#I:%M:%S%p’

供参考:https : //msdn.microsoft.com/en-us/library/fe06s4ak.aspx

On Windows, add a ‘#’, as in ‘%#m/%#d/%Y %#I:%M:%S %p’

For reference: https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx


回答 6

晚会很晚,但是%-d对我有帮助。

datetime.now().strftime('%B %-d, %Y')产生类似“ 2014年11月5日”的内容

欢呼:)

quite late to the party but %-d works on my end.

datetime.now().strftime('%B %-d, %Y') produces something like “November 5, 2014”

cheers :)


回答 7

我发现Django模板日期格式过滤器非常简单快捷。它去除了前导零。如果您不介意导入Django模块,请签出。

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')    

I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don’t mind importing the Django module, check it out.

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

from django.template.defaultfilters import date as django_date_filter
print django_date_filter(mydate, 'P, D M j, Y')    

回答 8

看一下-波纹管:

>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)

Take a look at - bellow:

>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)

回答 9

只需这样使用replace

(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")

它会输出:

'2017/7/21'

simply use replace like this:

(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")

it will output:

'2017/7/21'

回答 10

因为%d您可以使用转换为整数,int()否则它将自动删除前导0并变为整数。然后,您可以使用将其转换回字符串str()

For %d you can convert to integer using int() then it’ll automatically remove leading 0 and becomes integer. You can then convert back to string using str().


回答 11

例如,即使在同一OS的不同版本之间使用“%-d”也不是可移植的。更好的解决方案是分别提取日期成分,然后在日期特定的格式运算符和每个成分的日期属性访问之间进行选择。

e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)

using, for example, “%-d” is not portable even between different versions of the same OS. A better solution would be to extract the date components individually, and choose between date specific formatting operators and date attribute access for each component.

e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)

回答 12

因为Python实际上只是strftime(3)在您的平台上调用C语言函数,所以可能是有些格式字符可用于控制前导零;尝试man strftime看看。但是,当然,结果不会是可移植的,因为Python手册会提醒您。:-)

我会尝试使用一种新样式的datetime对象,该对象具有诸如t.yeart.month和的属性t.day,并通过%运算符的正常高效能格式来设置这些对象,该格式确实支持对前导零的控制。有关详细信息,请参见http://docs.python.org/library/datetime.html。更好的是,"".format()如果您的Python拥有运算符,并且更现代,请使用运算符。它也有许多数字格式选项。请参阅:http : //docs.python.org/library/string.html#string-formatting

Because Python really just calls the C language strftime(3) function on your platform, it might be that there are format characters you could use to control the leading zero; try man strftime and take a look. But, of course, the result will not be portable, as the Python manual will remind you. :-)

I would try using a new-style datetime object instead, which has attributes like t.year and t.month and t.day, and put those through the normal, high-powered formatting of the % operator, which does support control of leading zeros. See http://docs.python.org/library/datetime.html for details. Better yet, use the "".format() operator if your Python has it and be even more modern; it has lots of format options for numbers as well. See: http://docs.python.org/library/string.html#string-formatting.


回答 13

基于Alex的方法,这将适用于字符串开头和空格后的情况:

re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")

我喜欢它比.format或%-d好,因为它是跨平台的,可以让我继续使用strftime(获取“ 11月”和“星期一”之类的信息)。

Based on Alex’s method, this will work for both the start-of-string and after-spaces cases:

re.sub('^0|(?<= )0', '', "01 January 2000 08:00am")

I like this better than .format or %-d because this is cross-platform and allows me to keep using strftime (to get things like “November” and “Monday”).


回答 14

老问题了,但是%l(小写L)在strftime中对我有用:但是,这可能不适用于每个人,因为我发现的Python文档中未列出

Old question, but %l (lower-case L) worked for me in strftime: this may not work for everyone, though, as it’s not listed in the Python documentation I found


回答 15

import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")
import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")