本文整理汇总了Python中cryptography.hazmat.primitives.padding.PKCS7属性的典型用法代码示例。如果您正苦于以下问题:Python padding.PKCS7属性的具体用法?Python padding.PKCS7怎么用?Python padding.PKCS7使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类cryptography.hazmat.primitives.padding
的用法示例。
在下文中一共展示了padding.PKCS7属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: aes_encrypt_b64
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def aes_encrypt_b64(key, data):
"""
This function encrypts the data using AES-128-CBC. It generates
and adds an IV.
This is used for PSKC.
:param key: Encryption key (binary format)
:type key: bytes
:param data: Data to encrypt
:type data: bytes
:return: base64 encrypted output, containing IV and encrypted data
:rtype: str
"""
# pad data
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
iv = geturandom(16)
encdata = aes_cbc_encrypt(key, iv, padded_data)
return b64encode_and_unicode(iv + encdata)
示例2: aes_decrypt_b64
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def aes_decrypt_b64(key, enc_data_b64):
"""
This function decrypts base64 encoded data (containing the IV)
using AES-128-CBC. Used for PSKC
:param key: binary key
:param enc_data_b64: base64 encoded data (IV + encdata)
:type enc_data_b64: str
:return: encrypted data
"""
data_bin = base64.b64decode(enc_data_b64)
iv = data_bin[:16]
encdata = data_bin[16:]
padded_data = aes_cbc_decrypt(key, iv, encdata)
# remove padding
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
output = unpadder.update(padded_data) + unpadder.finalize()
return output
# @log_with(log)
示例3: decrypt
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def decrypt(self, k, a, iv, e, t):
""" Decrypt according to the selected encryption and hashing
functions.
:param k: Encryption key (optional)
:param a: Additional Authenticated Data
:param iv: Initialization Vector
:param e: Ciphertext
:param t: Authentication Tag
Returns plaintext or raises an error
"""
hkey = k[:_inbytes(self.keysize)]
dkey = k[_inbytes(self.keysize):]
# verify mac
if not constant_time.bytes_eq(t, self._mac(hkey, a, iv, e)):
raise InvalidSignature('Failed to verify MAC')
# decrypt
cipher = Cipher(algorithms.AES(dkey), modes.CBC(iv),
backend=self.backend)
decryptor = cipher.decryptor()
d = decryptor.update(e) + decryptor.finalize()
unpadder = PKCS7(self.blocksize).unpadder()
return unpadder.update(d) + unpadder.finalize()
示例4: get_encryptor
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def get_encryptor(key, iv=None):
algoer = algorithms.AES(key) #这里的AES算法(若要换成des算法,这里换成TripleDES,该加密库中,DES 事实上等于 TripleDES 的密钥长度为 64bit 时的加解密)
cipher = Cipher(algoer, modes.CBC(iv), backend=default_backend()) #这里的CBC模式
def enc(bitstring):
padder = padding.PKCS7(algoer.block_size).padder()
bitstring = padder.update(bitstring) + padder.finalize()
encryptor = cipher.encryptor()
return encryptor.update(bitstring) + encryptor.finalize()
def dec(bitstring):
decryptor = cipher.decryptor()
ddata = decryptor.update(bitstring) + decryptor.finalize()
unpadder = padding.PKCS7(algoer.block_size).unpadder()
return unpadder.update(ddata) + unpadder.finalize()
class f:pass
f.encrypt = enc
f.decrypt = dec
return f
示例5: _encrypt_from_parts
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def _encrypt_from_parts(self, data, current_time, iv):
if not isinstance(data, bytes):
raise TypeError("data must be bytes.")
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
encryptor = Cipher(
algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
).encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
basic_parts = (
b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
)
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(basic_parts)
hmac = h.finalize()
return base64.urlsafe_b64encode(basic_parts + hmac)
示例6: _encrypt_from_parts
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def _encrypt_from_parts(self, data, current_time, iv):
utils._check_bytes("data", data)
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
encryptor = Cipher(
algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
).encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
basic_parts = (
b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
)
h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
h.update(basic_parts)
hmac = h.finalize()
return base64.urlsafe_b64encode(basic_parts + hmac)
示例7: _serialize_secure_string
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def _serialize_secure_string(self, value):
if self.cipher is None:
raise SerializationError("Cannot generate secure string as cipher "
"is not initialised")
# convert the string to a UTF-16 byte string as that is what is
# expected in Windows. If a byte string (native string in Python 2) was
# passed in, the sender must make sure it is a valid UTF-16
# representation and not UTF-8 or else the server will fail to decrypt
# the secure string in most cases
string_bytes = to_bytes(value, encoding='utf-16-le')
padder = PKCS7(self.cipher.algorithm.block_size).padder()
padded_data = padder.update(string_bytes) + padder.finalize()
encryptor = self.cipher.encryptor()
ss_value = encryptor.update(padded_data) + encryptor.finalize()
ss_string = to_string(base64.b64encode(ss_value))
return ss_string
示例8: decrypt_mdmcert
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def decrypt_mdmcert(response: bytes, decrypt_with: RSAPrivateKeyWithSerialization) -> bytes:
"""Decrypt a .plist.b64.p7 supplied by mdmcert.download.
In order to decrypt this we need to:
- decode the payload using unhexlify()
- find the private key that corresponded to the request.
Args:
response (bytes): The still encryped and hex encoded payload
decrypt_with (RSAPrivateKeyWithSerialization): The private key that should be used to decrypt the payload.
Returns:
bytes - the decrypted response
"""
decoded_payload = unhexlify(response)
# try:
result = decrypt_smime_content(decoded_payload, decrypt_with)
# except ValueError as e:
# return abort(400, e)
# result = decrypt_with.decrypt(
# decoded_payload,
# padding.PKCS7(block_size=8)
# )
return result
示例9: decrypt
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def decrypt(self, pk, *args):
km = pk.keymaterial
if km.oid == EllipticCurveOID.Curve25519:
v = x25519.X25519PublicKey.from_public_bytes(self.p.x)
s = km.__privkey__().exchange(v)
else:
# assemble the public component of ephemeral key v
v = ec.EllipticCurvePublicNumbers(self.p.x, self.p.y, km.oid.curve()).public_key(default_backend())
# compute s using the inverse of how it was derived during encryption
s = km.__privkey__().exchange(ec.ECDH(), v)
# derive the wrapping key
z = km.kdf.derive_key(s, km.oid, PubKeyAlgorithm.ECDH, pk.fingerprint)
# unwrap and unpad m
_m = aes_key_unwrap(z, self.c, default_backend())
padder = PKCS7(64).unpadder()
return padder.update(_m) + padder.finalize()
示例10: test_validate_encryption
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def test_validate_encryption(self):
# Arrange
self.bbs.require_encryption = True
kek = KeyWrapper('key1')
self.bbs.key_encryption_key = kek
blob_name = self._create_small_blob('block_blob')
# Act
self.bbs.require_encryption = False
self.bbs.key_encryption_key = None
blob = self.bbs.get_blob_to_bytes(self.container_name, blob_name)
encryption_data = _dict_to_encryption_data(loads(blob.metadata['encryptiondata']))
iv = encryption_data.content_encryption_IV
content_encryption_key = _validate_and_unwrap_cek(encryption_data, kek, None)
cipher = _generate_AES_CBC_cipher(content_encryption_key, iv)
decryptor = cipher.decryptor()
unpadder = PKCS7(128).unpadder()
content = decryptor.update(blob.content) + decryptor.finalize()
content = unpadder.update(content) + unpadder.finalize()
self.assertEqual(self.bytes, content)
示例11: _CKM_AES_CBC_encrypt
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def _CKM_AES_CBC_encrypt(self, key, pt_data, session):
iv = self._generate_random(_CBC_IV_SIZE, session)
ck_mechanism = self._build_cbc_mechanism(iv)
rv = self.lib.C_EncryptInit(session, ck_mechanism.mech, key)
self._check_error(rv)
padder = padding.PKCS7(_CBC_BLOCK_SIZE).padder()
padded_pt_data = padder.update(pt_data)
padded_pt_data += padder.finalize()
pt_len = len(padded_pt_data)
ct_len = self.ffi.new("CK_ULONG *", pt_len)
ct = self.ffi.new("CK_BYTE[{}]".format(ct_len[0]))
rv = self.lib.C_Encrypt(session, padded_pt_data, pt_len, ct, ct_len)
self._check_error(rv)
return {
"iv": self.ffi.buffer(iv)[:],
"ct": self.ffi.buffer(ct, ct_len[0])[:]
}
示例12: _CKM_AES_CBC_decrypt
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def _CKM_AES_CBC_decrypt(self, key, iv, ct_data, session):
iv = self.ffi.new("CK_BYTE[{}]".format(len(iv)), iv)
ck_mechanism = self._build_cbc_mechanism(iv)
rv = self.lib.C_DecryptInit(session, ck_mechanism.mech, key)
self._check_error(rv)
ct_len = len(ct_data)
pt_len = self.ffi.new("CK_ULONG *", ct_len)
pt = self.ffi.new("CK_BYTE[{0}]".format(pt_len[0]))
rv = self.lib.C_Decrypt(session, ct_data, ct_len, pt, pt_len)
self._check_error(rv)
pt = self.ffi.buffer(pt, pt_len[0])[:]
unpadder = padding.PKCS7(_CBC_BLOCK_SIZE).unpadder()
unpadded_pt = unpadder.update(pt)
unpadded_pt += unpadder.finalize()
return unpadded_pt
示例13: get_decryption_aes_key
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
"""
Get decryption key for a given S3 object
:param key: Base64 decoded version of x-amz-key
:param material_description: JSON decoded x-amz-matdesc
:return: Raw AES key bytes
"""
# So it seems when java just calls Cipher.getInstance('AES') it'll default to AES/ECB/PKCS5Padding
aesecb = self._cipher.decryptor()
padded_result = await self._loop.run_in_executor(None, lambda: (aesecb.update(key) + aesecb.finalize()))
unpadder = PKCS7(AES.block_size).unpadder()
result = await self._loop.run_in_executor(None, lambda: (unpadder.update(padded_result) + unpadder.finalize()))
return result
示例14: get_encryption_aes_key
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
"""
Get encryption key to encrypt an S3 object
:return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key
"""
random_bytes = os.urandom(32)
padder = PKCS7(AES.block_size).padder()
padded_result = await self._loop.run_in_executor(
None, lambda: (padder.update(random_bytes) + padder.finalize()))
aesecb = self._cipher.encryptor()
encrypted_result = await self._loop.run_in_executor(
None, lambda: (aesecb.update(padded_result) + aesecb.finalize()))
return random_bytes, {}, base64.b64encode(encrypted_result).decode()
示例15: _wrap_object_with_symmetric_key
# 需要导入模块: from cryptography.hazmat.primitives import padding [as 别名]
# 或者: from cryptography.hazmat.primitives.padding import PKCS7 [as 别名]
def _wrap_object_with_symmetric_key(plaintext):
import json
import base64
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
#Pad data
padder = padding.PKCS7(128).padder()
padded_plaintext = padder.update(plaintext)
padded_plaintext += padder.finalize()
#Generate random symmetric key and intialization vector
key = os.urandom(32)
iv = os.urandom(16)
#Encrypt object
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
wrapped_object= {'ciphertext': base64.b64encode(ciphertext), 'symmetric_key':base64.b64encode(key), 'iv':base64.b64encode(iv)}
return wrapped_object