本文整理汇总了Python中Crypto.Cipher.AES属性的典型用法代码示例。如果您正苦于以下问题:Python Cipher.AES属性的具体用法?Python Cipher.AES怎么用?Python Cipher.AES使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类Crypto.Cipher
的用法示例。
在下文中一共展示了Cipher.AES属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: runTest
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def runTest(self):
"Simple test of AllOrNothing"
from Crypto.Cipher import AES
import base64
# The current AllOrNothing will fail
# every so often. Repeat the test
# several times to force this.
for i in range(50):
x = AllOrNothing.AllOrNothing(AES)
msgblocks = x.digest(text)
# get a new undigest-only object so there's no leakage
y = AllOrNothing.AllOrNothing(AES)
text2 = y.undigest(msgblocks)
self.assertEqual(text, text2)
示例2: _AESUnwrap
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def _AESUnwrap(kek, wrapped):
C = []
for i in range(len(wrapped)//8):
C.append(_unpack64bit(wrapped[i * 8:i * 8 + 8]))
n = len(C) - 1
R = [0] * (n+1)
A = C[0]
for i in range(1, n+1):
R[i] = C[i]
for j in reversed(range(0, 6)):
for i in reversed(range(1, n+1)):
todec = _pack64bit(A ^ (n * j + i))
todec += _pack64bit(R[i])
B = Crypto.Cipher.AES.new(kek, Crypto.Cipher.AES.MODE_ECB).decrypt(todec)
A = _unpack64bit(B[:8])
R[i] = _unpack64bit(B[8:])
if A != 0xa6a6a6a6a6a6a6a6:
return None
res = b"".join(map(_pack64bit, R[1:]))
return res
示例3: setSessionKey
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def setSessionKey( self, key, iv ):
"""
Set AES' session key and the initialisation vector for counter mode.
The given `key' and `iv' are used as 256-bit AES key and as 128-bit
initialisation vector for counter mode. Both, the key as well as the
IV must come from a CSPRNG.
"""
self.sessionKey = key
# Our 128-bit counter has the following format:
# [ 64-bit static and random IV ] [ 64-bit incrementing counter ]
# Counter wrapping is not allowed which makes it possible to transfer
# 2^64 * 16 bytes of data while avoiding counter reuse. That amount is
# effectively out of reach given today's networking performance.
log.debug("Setting IV for AES-CTR.")
self.counter = Crypto.Util.Counter.new(64,
prefix = iv,
initial_value = 1,
allow_wraparound = False)
log.debug("Setting session key for AES-CTR.")
self.crypter = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CTR,
counter=self.counter)
示例4: encrypt_aes
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def encrypt_aes(plaintext, key, padding=chr(0)):
"""
AES-256-OCB encryption
`Requires`
:param str plaintext: plain text/data
:param str key: session encryption key
`Optional`
:param str padding: default: (null byte)
Returns encrypted ciphertext as base64-encoded string
"""
cipher = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_OCB)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
output = b''.join((cipher.nonce, tag, ciphertext))
return base64.b64encode(output)
示例5: decrypt_aes
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def decrypt_aes(ciphertext, key, padding=chr(0)):
"""
AES-256-OCB decryption
`Requires`
:param str ciphertext: encrypted block of data
:param str key: session encryption key
`Optional`
:param str padding: default: (null byte)
Returns decrypted plaintext as string
"""
data = StringIO(base64.b64decode(ciphertext))
nonce, tag, ciphertext = [ data.read(x) for x in (Crypto.Cipher.AES.block_size - 1, Crypto.Cipher.AES.block_size, -1) ]
cipher = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_OCB, nonce)
return cipher.decrypt_and_verify(ciphertext, tag)
示例6: decrypt_file
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def decrypt_file(filename, key):
"""
Decrypt a file that was encrypted with AES-256-OCB encryption
`Required`
:param str filename: target filename
:param str aes_key: 256-bit key
Returns True if succesful, otherwise False
"""
try:
if os.path.isfile(filename):
with open(filename, 'rb') as fp:
ciphertext = fp.read()
plaintext = decrypt_aes(ciphertext, key)
with open(filename, 'wb') as fd:
fd.write(plaintext)
util.log('{} decrypted'.format(filename))
return True
else:
util.log("File '{}' not found".format(filename))
except Exception as e:
util.log("{} error: {}".format(decrypt_file.__name__, str(e)))
return False
示例7: test_internal_caching
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def test_internal_caching(self):
"""Verify that internal caching is implemented correctly"""
data_to_mac = get_tag_random("data_to_mac", 128)
key = get_tag_random("key", 16)
ref_mac = CMAC.new(key, msg=data_to_mac, ciphermod=AES).digest()
# Break up in chunks of different length
# The result must always be the same
for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
chunks = [data_to_mac[i:i+chunk_length] for i in
range(0, len(data_to_mac), chunk_length)]
mac = CMAC.new(key, ciphermod=AES)
for chunk in chunks:
mac.update(chunk)
self.assertEqual(ref_mac, mac.digest())
示例8: test_update_after_digest
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def test_update_after_digest(self):
msg = b"rrrrttt"
key = b"4" * 16
# Normally, update() cannot be done after digest()
h = CMAC.new(key, msg[:4], ciphermod=AES)
dig1 = h.digest()
self.assertRaises(TypeError, h.update, msg[4:])
dig2 = CMAC.new(key, msg, ciphermod=AES).digest()
# With the proper flag, it is allowed
h2 = CMAC.new(key, msg[:4], ciphermod=AES, update_after_digest=True)
self.assertEquals(h2.digest(), dig1)
# ... and the subsequent digest applies to the entire message
# up to that point
h2.update(msg[4:])
self.assertEquals(h2.digest(), dig2)
示例9: runTest
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def runTest(self):
key = b"0" * 16
data = b"\x00\x01\x02"
# Data and key can be a bytearray (during initialization)
key_ba = bytearray(key)
data_ba = bytearray(data)
h1 = CMAC.new(key, data, ciphermod=AES)
h2 = CMAC.new(key_ba, data_ba, ciphermod=AES)
key_ba[:1] = b'\xFF'
data_ba[:1] = b'\xFF'
self.assertEqual(h1.digest(), h2.digest())
# Data can be a bytearray (during operation)
key_ba = bytearray(key)
data_ba = bytearray(data)
h1 = CMAC.new(key, ciphermod=AES)
h2 = CMAC.new(key, ciphermod=AES)
h1.update(data)
h2.update(data_ba)
data_ba[:1] = b'\xFF'
self.assertEqual(h1.digest(), h2.digest())
示例10: parse_sha1_ctx
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def parse_sha1_ctx(ctx, winver):
if not (winver in CNG_STRUCTURES):
raise Exception('Unsupported Windows version: %d' % winver)
ofs = CNG_STRUCTURES[winver]['SHA1']
ofs_state = ofs['state']
ofs_buffer = ofs['buffer']
ofs_size = ofs['size']
# sha1 state is at offset 0x40 for win7 and is 20 bytes long
sha1_state = ctx[ofs_state:ofs_state + 0x14]
# Check sha1_ctx is still in initial state (i.e. no Sha1Transform yet)
if sha1_state != struct.pack('<LLLLL', 0x67452301, 0x0EFCDAB89, 0x98BADCFE, 0x10325476, 0x0C3D2E1F0):
return None
seed_size = struct.unpack('<L', ctx[ofs_size:ofs_size+4])[0]
return ctx[ofs_buffer:ofs_buffer+seed_size]
# Extract the key from the AES key schedule
# The raw AES key is xor'ed into the plaintext at the start of the first round, i.e. it is
# the very first (of 11 for AES128) subkeys
示例11: AESdecryptCBC
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def AESdecryptCBC(data, key, iv=b"\x00" * 16):
if len(data) % 16:
print("WARN: AESdecryptCBC: data length not /16, truncating")
data = data[0:(len(data)/16) * 16]
data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
return data
示例12: __init__
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def __init__( self ):
"""
Initialise a PayloadCrypter object.
"""
log.debug("Initialising AES-CTR instance.")
self.sessionKey = None
self.crypter = None
self.counter = None
示例13: encrypt
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def encrypt( self, data ):
"""
Encrypts the given `data' using AES in counter mode.
"""
return self.crypter.encrypt(data)
# Encryption equals decryption in AES-CTR.
示例14: new
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def new(key):
cipher = Crypto.Cipher.AES.new(bytes(key))
def encrypt(plaintext):
return bytearray(cipher.encrypt(bytes(plaintext)))
return AESGCM(key, "pycrypto", encrypt)
示例15: load_crypto_libraries
# 需要导入模块: from Crypto import Cipher [as 别名]
# 或者: from Crypto.Cipher import AES [as 别名]
def load_crypto_libraries():
global aes256_cbc_decrypt, aes256_ofb_decrypt, pbkdf2
try:
import Crypto.Cipher.AES, Crypto.Protocol.KDF
aes256_cbc_decrypt = lambda key, iv, ciphertext: \
Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(ciphertext)
aes256_ofb_decrypt = lambda key, iv, ciphertext: \
Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_OFB, iv).decrypt(ciphertext)
pbkdf2 = lambda password, salt, iter_count, len: \
Crypto.Protocol.KDF.PBKDF2(password, salt, len, iter_count)
return
except ImportError: pass
# The pure python AES library is attributed to GitHub user serprex; please see the
# aespython README.txt for more information.
#
# Add the parent directory of this script's location to the library search path
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
import aespython
#
expandKey = aespython.key_expander.expandKey
def aes256_decrypt_factory(BlockMode):
def aes256_decrypt(key, iv, ciphertext):
block_cipher = aespython.aes_cipher.AESCipher( expandKey(bytearray(key)) )
stream_cipher = BlockMode(block_cipher, 16)
stream_cipher.set_iv(bytearray(iv))
plaintext = bytearray()
for i in xrange(0, len(ciphertext), 16):
plaintext.extend( stream_cipher.decrypt_block(bytearray(ciphertext[i:i+16])) )
return str(plaintext)
return aes256_decrypt
aes256_cbc_decrypt = aes256_decrypt_factory(aespython.cbc_mode.CBCMode)
aes256_ofb_decrypt = aes256_decrypt_factory(aespython.ofb_mode.OFBMode)
import passlib.utils.pbkdf2
pbkdf2 = passlib.utils.pbkdf2.pbkdf2
################################### Main ###################################