Python Crypto.Cipher.AES 模块,new() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用Crypto.Cipher.AES.new()。
def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024):
# Split .crypt extension to restore file format
if not out_filename:
out_filename = os.path.splitext(in_filename)[0]
with open(in_filename, 'rb') as infile:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
with open(out_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
# Truncate file to original size
outfile.truncate(origsize)
def encrypt(key, filename):
chunksize = 64 * 1024
outFile = os.path.join(os.path.dirname(filename), ".hell"+os.path.basename(filename))
filesize = str(os.path.getsize(filename)).zfill(16)
IV = ''
for i in range(16):
IV += chr(random.randint(0, 0xFF))
encryptor = AES.new(key, IV)
with open(filename, "rb") as infile:
with open(outFile, "wb") as outfile:
outfile.write(filesize)
outfile.write(IV)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 !=0:
chunk += ' ' * (16 - (len(chunk) % 16))
outfile.write(encryptor.encrypt(chunk))
def get_encryption():
return '''
import base64
from Crypto import Random
from Crypto.Cipher import AES
abbrev = '{2}'
{0} = base64.b64decode('{1}')
def encrypt(raw):
iv = Random.new().read( AES.block_size )
cipher = AES.new({0},AES.MODE_CFB,iv )
return (base64.b64encode( iv + cipher.encrypt( raw ) ) )
def decrypt(enc):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new({0},iv )
return cipher.decrypt( enc[16:] )
'''.format(st_obf[0],aes_encoded,aes_abbrev)
################################################################################
# st_protocol.py stitch_gen variables #
################################################################################
def encrypt_file(key, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + '.crypt'
iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
encryptor = AES.new(key, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(struct.pack('<Q', filesize))
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
outfile.write(encryptor.encrypt(chunk))
def AESEnc(sour, key):
from Crypto.Cipher import AES
from Crypto import Random
sour = sour.encode('utf8')
key = key.encode('utf8')
bs = AES.block_size
pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
iv = Random.new().read(bs)
cipher = AES.new(key, AES.MODE_ECB, iv)
resData1 = cipher.encrypt(pad(sour))
resData2 = resData1.encode('hex')
resData3 = resData2.upper()
print resData3
return resData3
def encrypt(self, passwd=None, length=32):
"""
encrypt gen password
???????????
"""
if not passwd:
passwd = self.gen_rand_pass()
cryptor = AES.new(self.key, self.mode, b'8122ca7d906ad5e1')
try:
count = len(passwd)
except TypeError:
raise ServerError('Encrypt password error,TYpe error.')
add = (length - (count % length))
passwd += ('\0' * add)
cipher_text = cryptor.encrypt(passwd)
return b2a_hex(cipher_text)
def reencrypt(self, data):
try:
self.decoder = DES.new(self.key, DES.MODE_CBC, self.iv) # need to reinit it each time because of CBC
decrypted=self.unpad(self.decoder.decrypt(base64.b64decode(data)))
if debug:
if len(decrypted)==8 and re.match(self.autogen,decrypted) is not None:
self.debugf.write(self.currentdn+" =* "+decrypted+"\n")
elif re.match(self.alphanumchar,decrypted) is not None:
self.debugf.write(self.currentdn+" => "+decrypted+"\n")
else:
self.debugf.write(self.currentdn+" =x "+decrypted+"\n")
encrypted=self.encoder.encrypt(self.pad(decrypted))
newdata=base64.b64encode(encrypted)
return newdata
except:
raise
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
def aesEncrypt(text, secKey):
pad = 16 - len(text) % 16
# aes????byte???
# ??????????????????
# ???try?if????
try:
text = text.decode()
except:
pass
text = text + pad * chr(pad)
try:
text = text.encode()
except:
pass
encryptor = AES.new(secKey, 2, bytes('0102030405060708', 'utf-8'))
ciphertext = encryptor.encrypt(text)
ciphertext = base64.b64encode(ciphertext)
return ciphertext
def __init__(self):
self.iv = Random.new().read(AES.block_size)
self.key = Random.new().read(AES.block_size)
self.cipher = AES.new(key=self.key, mode=AES.MODE_CBC, IV=self.iv)
texts = []
self.plaintexts = []
# Reads all the lines from the data,as binary strings,then decodes
# them from base64 and applies Pkcs7 padding.
with open('data/7.txt', 'rb') as dataFile:
texts = dataFile.readlines()
for text in texts:
strText = base64.b64decode(text)
self.plaintexts.append(Pkcs7(strText))
def __init__(self, key=None, mode=AES.MODE_ECB, iv=None):
"""Initialize a AES cipher with the given mode,and key (as a byte string)
Parameters:
key: the key,as a byte string (e.g. b'YELLOW SUBMARINE'). If None,
a random one will be generated.
mode: AES mode. Default: AES.MODE_ECB.
iv: IV. If None,a random one will be generated internally.
"""
if iv is None:
self._iv = self.GeneraterandomBytes(AES.block_size)
else:
self._iv = iv
if key is None:
self._key = self.GeneraterandomBytes(AES.block_size)
else:
self._key = key
self.mode = mode
self._cipher = AES.new(key=self._key, mode=self.mode, IV=self._iv)
def Merkledamgard(message, state, stateLen):
"""Applies an arbitrary Merkle-damgard construction to the message.
The default state length and initial state are those used all over
this program.
"""
newState = state
# The state length we use is shorter than what AES wants for the keys.
newState = padPKCS7(newState)
for i in range(GetNumBlocks(message)):
cipher = AES.new(newState, AES.MODE_ECB)
newState = cipher.encrypt(GetBlock(message, i))
# This would be a really bad idea to do in practice,if we are
# actually using AES or an algorithm that requires keys of
# a certain size. It's needed here because the hash and
# the key needs to be the same for the challenge to work,and
# the hash we return has 2 bytes.
newState = padPKCS7(newState[:stateLen])
return newState[:stateLen]
# Generates the initial 2**k states of the tree at random. We make
# all of them different with each other.
def CBCMacWithStates(message, iv):
"""Computes the CBC-MAC of a message given the IV.
Returns a tuple with the hash and a list of tuples; the first
element is the block index and the second is the intermediate state
associated with that block,as a byte string.
It is expected that this returns the same hash as CBC-MAC above
given the same inputs.
"""
M_states = []
paddedMessage = padPKCS7(message)
intermediateMessage = b''
currentState = iv
for bIndex in range(GetNumBlocks(paddedMessage)):
intermediateMessage = GetBlock(paddedMessage, bIndex)
cipher = AES.new(b'YELLOW SUBMARINE', currentState)
currentState = cipher.encrypt(intermediateMessage)
currentState = currentState[-AES.block_size:]
M_states.append( ( bIndex, currentState ) )
return currentState, M_states
def encrypt(self, plaintext):
"""CBC encryption."""
cipher = AES.new(key=self._key, mode=AES.MODE_ECB)
# The full URL is not necessary for this setup,so I am just encrypting
# the plaintext as it is. I don't even need to support padding.
prev_ct = self._iv
block_index = 0
ciphertext = b''
# The loop simulates encryption through AES in CBC mode.
while block_index < len(plaintext):
block = plaintext[block_index : block_index + AES.block_size]
final_block = strxor(block, prev_ct)
cipher_block = cipher.encrypt(final_block)
prev_ct = cipher_block
ciphertext += cipher_block
block_index += AES.block_size
return ciphertext
def EditCTR(ciphertext, offset, newText, ctrObj):
numBlocks = block_utils.GetNumBlocks(ciphertext)
# Sanity checking.
if offset < 0 or offset > numBlocks - 1:
raise ValueError("Invalid offset.")
if len(newText) != AES.block_size:
raise ValueError("New plaintext must be 1 block in size")
# Encrypt the new block of text using the value of the
# counter for the 'offset' block of the ciphertext. The idea
# is that newBlock will replace the block at position 'offset'
# in the ciphertext,although here we do not perform the
# actual substitution.
newBlock = ctrObj.OneBlockCrypt(newText, offset)
return newBlock
# This function is only here to recover the text as explained
# in the challenge. Of course here we need to kNow the key :)
def _decrypt_stealth_auth(content, authentication_cookie):
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto.Util.number import bytes_to_long
# byte 1 = authentication type,2-17 = input vector,18 on = encrypted content
iv, encrypted = content[1:17], content[17:]
counter = Counter.new(128, initial_value = bytes_to_long(iv))
cipher = AES.new(authentication_cookie, AES.MODE_CTR, counter = counter)
return cipher.decrypt(encrypted)
def decrypt_secret(secret, key):
"""Python implementation of SystemFunction005.
Decrypts a block of data with DES using given key.
Note that key can be longer than 7 bytes."""
decrypted_data = ''
j = 0 # key index
for i in range(0,len(secret),8):
enc_block = secret[i:i+8]
block_key = key[j:j+7]
des_key = str_to_key(block_key)
des = DES.new(des_key, DES.MODE_ECB)
decrypted_data += des.decrypt(enc_block)
j += 7
if len(key[j:j+7]) < 7:
j = len(key[j:j+7])
(dec_data_len,) = unpack("<L", decrypted_data[:4])
return decrypted_data[8:8+dec_data_len]
def decrypt_aes(secret, key):
sha = SHA256.new()
sha.update(key)
for _i in range(1, 1000+1):
sha.update(secret[28:60])
aeskey = sha.digest()
data = ""
for i in range(60, len(secret), 16):
aes = AES.new(aeskey, "\x00"*16)
buf = secret[i : i + 16]
if len(buf) < 16:
buf += (16-len(buf)) * "\00"
data += aes.decrypt(buf)
return data
def decryptStreamChunkOld(self,response, wfile, chunksize=24*1024, startOffset=0):
if ENCRYPTION_ENABLE == 0:
return
# with open(in_filename,'rb') as infile:
origsize = struct.unpack('<Q', response.read(struct.calcsize('Q')))[0]
decryptor = AES.new(self.key, AES.MODE_ECB)
count = 0
while True:
chunk = response.read(chunksize)
count = count + 1
if len(chunk) == 0:
break
responseChunk = decryptor.decrypt(chunk)
if count == 1 and startOffset !=0:
wfile.write(responseChunk[startOffset:])
elif (len(chunk)) < (len(responseChunk.strip())):
wfile.write(responseChunk.strip())
else:
wfile.write(responseChunk)
def decryptCalculatePadding(self, chunksize=24*1024):
if ENCRYPTION_ENABLE == 0:
return
# with open(in_filename, AES.MODE_ECB)
count = 0
while True:
chunk = response.read(chunksize)
count = count + 1
if len(chunk) == 0:
break
responseChunk = decryptor.decrypt(chunk)
return int(len(chunk) - len(responseChunk.strip()))
def encryptString(self, stringDecrypted):
if ENCRYPTION_ENABLE == 0:
return
# key = generate_key(key,salt,NUMBER_OF_IteraTIONS)
# iv = ''.join(chr(random.randint(0,0xFF)) for i in range(16))
encryptor = AES.new(self.key, AES.MODE_ECB)
if len(stringDecrypted) == 0:
return
elif len(stringDecrypted) % 16 != 0:
stringDecrypted += ' ' * (16 - len(stringDecrypted) % 16)
import base64
stringEncrypted = base64.b64encode(encryptor.encrypt(stringDecrypted))
stringEncrypted = re.sub('/', '---', stringEncrypted)
return stringEncrypted
def encrypt(self, rsa_public_key, out_file_path=None):
if not out_file_path:
out_file_path = self._path + ".encrypted"
aes_key = AESKey()
aes_encryptor = AES.new(aes_key.key,
aes_key.mode,
IV=aes_key.IV)
keys_chunk = KeysChunk(aes_key, rsa_public_key).compute()
with open(self._path, 'rb') as plain_file:
with open(out_file_path, 'wb') as encrypted_file:
encrypted_file.write(struct.pack('>Q', self._file_size))
encrypted_file.write(keys_chunk)
while True:
chunk = plain_file.read(self.chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b'\x00' * (16 - len(chunk) % 16)
encrypted_file.write(aes_encryptor.encrypt(chunk))
def decrypt(self, rsa_private_key, out_file_path=None):
if not self._keys_chunk:
self.load_keys_chunk()
if not out_file_path:
out_file_path = os.path.splitext(self._path)[0]
self._keys_chunk.aes_key.decrypt(rsa_private_key)
decryptor = AES.new(self._keys_chunk.aes_key.key,
self._keys_chunk.aes_key.mode,
IV=self._keys_chunk.aes_key.IV)
with open(self._path, 'rb') as encrypted_file:
original_file_size = self.get_original_file_size(encrypted_file)
encrypted_file.seek(16 + 512 + 8)
with open(out_file_path, 'wb') as decrypted_file:
while True:
chunk = encrypted_file.read(self.chunksize)
if len(chunk) == 0:
break
decrypted_file.write(decryptor.decrypt(chunk))
decrypted_file.truncate(original_file_size)
def get_track_url(self, data):
join = u'\u00a4'.join
proxy = data['MD5_ORIGIN'][0]
if data['FILESIZE_MP3_320']:
track_format = 3
elif data['FILESIZE_MP3_256']:
track_format = 5
else:
track_format = 1
payload = join(map(str, [data['MD5_ORIGIN'], track_format, data['SNG_ID'], data['MEDIA_VERSION']]))
payloadHash = get_md5(payload)
def pad(s, BS=16):
return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
reference = pad(join([payloadHash, payload, '']).encode('latin-1'))
cipher = AES.new('jo6aey6haid2Teih', mode=AES.MODE_ECB)
reference = cipher.encrypt(reference).encode('hex').lower()
return "http://e-cdn-proxy-{}.deezer.com/mobile/1/{}".format(proxy, reference)
def _pseudo_random_data(self, 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
def get_key(encoded_key):
IV = None
CIPHER = None
if encoded_key is False:
try:
MYFILE = Tools.__path__[0]+os.sep+"admin"+os.sep+'secret.key'
with open(MYFILE, 'r') as myfileHandle:
encoded_key = myfileHandle.read()
except IOError:
print_error("Could not find the secret.key file in Tools/Admin!")
try:
IV = Random.new().read(AES.block_size)
CIPHER = AES.new(base64.b64decode(encoded_key), AES.MODE_CFB, IV)
except Exception as e:
print_exception("Some problem occured: {0}".format(e))
return IV, CIPHER
def simple_hash(text, key='', salt='', digest_alg='md5'):
"""Generate hash with the given text using the specified digest algorithm."""
text = to_bytes(text)
key = to_bytes(key)
salt = to_bytes(salt)
if not digest_alg:
raise RuntimeError("simple_hash with digest_alg=None")
elif not isinstance(digest_alg, str): # manual approach
h = digest_alg(text + key + salt)
elif digest_alg.startswith('pbkdf2'): # latest and coolest!
iterations, keylen, alg = digest_alg[7:-1].split(',')
return to_native(pbkdf2_hex(text, salt, int(iterations),
int(keylen), get_digest(alg)))
elif key: # use hmac
digest_alg = get_digest(digest_alg)
h = hmac.new(key + salt, text, digest_alg)
else: # compatible with third party systems
h = get_digest(digest_alg)()
h.update(text + salt)
return h.hexdigest()
def secure_loads(data, encryption_key, hash_key=None, compression_level=None):
components = data.count(b':')
if components == 1:
return secure_loads_deprecated(data, hash_key, compression_level)
if components != 2:
return None
version, signature, encrypted_data = data.split(b':', 2)
if version != b'hmac256':
return None
encryption_key = to_bytes(encryption_key)
if not hash_key:
hash_key = hashlib.sha256(encryption_key).digest()
actual_signature = hmac.new(to_bytes(hash_key), encrypted_data, hashlib.sha256).hexdigest()
if not compare(to_native(signature), actual_signature):
return None
encrypted_data = base64.urlsafe_b64decode(encrypted_data)
IV, encrypted_data = encrypted_data[:16], encrypted_data[16:]
cipher, _ = AES_new(pad(encryption_key)[:32], IV=IV)
try:
data = unpad(AES_dec(cipher, encrypted_data))
if compression_level:
data = zlib.decompress(data)
return pickle.loads(data)
except Exception as e:
return None
def leaves(self, value):
if value is None:
raise ValueError('Leaves should be a list.')
elif not isinstance(value, list) and \
not isinstance(value, types.GeneratorType):
raise ValueError('Leaves should be a list or a generator (%s).' % type(value))
if self.prehashed:
# it will create a copy of list or
# it will create a new list based on the generator
self._leaves = list(value)
else:
self._leaves = [ShardManager.hash(leaf) for leaf in value]
if not len(self._leaves) > 0:
raise ValueError('Leaves must contain at least one entry.')
for leaf in self._leaves:
if not isinstance(leaf, six.string_types):
raise ValueError('Leaves should only contain strings.')
def decrypt_file_aes(self, in_file, out_file, password, key_length=32):
bs = AES.block_size
salt = in_file.read(bs)[len('Salted__'):]
key, iv = self.derive_key_and_iv(password, key_length, bs)
cipher = AES.new(key, 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])
if padding_length < 1 or padding_length > bs:
raise ValueError('bad decrypt pad (%d)' % padding_length)
# all the pad-bytes must be the same
if chunk[-padding_length:] != (padding_length * chr(padding_length)):
# this is similar to the bad decrypt:evp_enc.c from openssl program
raise ValueError('bad decrypt')
chunk = chunk[:-padding_length]
finished = True
out_file.write(chunk)
def decrypt(cls, key, keyusage, ciphertext):
if len(ciphertext) < 24:
raise ValueError('ciphertext too short')
cksum, basic_ctext = ciphertext[:16], ciphertext[16:]
ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
ke = HMAC.new(ki, cksum, MD5).digest()
basic_plaintext = ARC4.new(ke).decrypt(basic_ctext)
exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
ok = _mac_equal(cksum, exp_cksum)
if not ok and keyusage == 9:
# Try again with usage 8,due to RFC 4757 errata.
ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()
exp_cksum = HMAC.new(ki, MD5).digest()
ok = _mac_equal(cksum, exp_cksum)
if not ok:
raise InvalidChecksum('ciphertext integrity failure')
# discard the confounder.
return basic_plaintext[8:]
def ComputeSessionKeyStrongKey(sharedSecret, clientChallenge, serverChallenge, sharedSecretHash = None):
# added the ability to receive hashes already
if sharedSecretHash is None:
M4SS = ntlm.NTOWFv1(sharedSecret)
else:
M4SS = sharedSecretHash
md5 = hashlib.new('md5')
md5.update('\x00'*4)
md5.update(clientChallenge)
md5.update(serverChallenge)
finalMD5 = md5.digest()
hm = hmac.new(M4SS)
hm.update(finalMD5)
return hm.digest()
def getHBootKey(self):
LOG.debug('Calculating HashedBootKey from SAM')
QWERTY = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\0"
DIGITS = "0123456789012345678901234567890123456789\0"
F = self.getValue(ntpath.join('SAM\Domains\Account','F'))[1]
domainData = DOMAIN_ACCOUNT_F(F)
rc4Key = self.MD5(domainData['Key0']['Salt'] + QWERTY + self.__bootKey + DIGITS)
rc4 = ARC4.new(rc4Key)
self.__hashedBootKey = rc4.encrypt(domainData['Key0']['Key']+domainData['Key0']['CheckSum'])
# Verify key with checksum
checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY)
if checkSum != self.__hashedBootKey[16:]:
raise Exception('hashedBootKey CheckSum Failed,Syskey startup password probably in use! :(')
def __decryptLSA(self, value):
if self.__vistaStyle is True:
# Todo: There Could be more than one LSA Keys
record = LSA_SECRET(value)
tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32])
plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])
record = LSA_SECRET_BLOB(plainText)
self.__LSAKey = record['Secret'][52:][:32]
else:
md5 = hashlib.new('md5')
md5.update(self.__bootKey)
for i in range(1000):
md5.update(value[60:76])
tmpKey = md5.digest()
rc4 = ARC4.new(tmpKey)
plainText = rc4.decrypt(value[12:60])
self.__LSAKey = plainText[0x10:0x20]
def decryptSecret(key, value):
# [MS-LSAD] Section 5.1.2
plainText = ''
key0 = key
for i in range(0, len(value), 8):
cipherText = value[:8]
tmpStrKey = key0[:7]
tmpKey = transformKey(tmpStrKey)
Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
plainText += Crypt1.decrypt(cipherText)
cipherText = cipherText[8:]
key0 = key0[7:]
value = value[8:]
# AdvanceKey
if len(key0) < 7:
key0 = key[len(key0):]
secret = LSA_SECRET_XP(plainText)
return (secret['Secret'])
def encryptSecret(key, value):
# [MS-LSAD] Section 5.1.2
plainText = ''
cipherText = ''
key0 = key
value0 = pack('<LL', 1) + value
for i in range(0, len(value0), 8):
if len(value0) < 8:
value0 = value0 + '\x00'*(8-len(value0))
plainText = value0[:8]
tmpStrKey = key0[:7]
tmpKey = transformKey(tmpStrKey)
Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
cipherText += Crypt1.encrypt(plainText)
plainText = plainText[8:]
key0 = key0[7:]
value0 = value0[8:]
# AdvanceKey
if len(key0) < 7:
key0 = key[len(key0):]
return cipherText
def SamDecryptNTLMHash(encryptedHash, key):
# [MS-SAMR] Section 2.2.11.1.1
Block1 = encryptedHash[:8]
Block2 = encryptedHash[8:]
Key1 = key[:7]
Key1 = transformKey(Key1)
Key2 = key[7:14]
Key2 = transformKey(Key2)
Crypt1 = DES.new(Key1, DES.MODE_ECB)
Crypt2 = DES.new(Key2, DES.MODE_ECB)
plain1 = Crypt1.decrypt(Block1)
plain2 = Crypt2.decrypt(Block2)
return plain1 + plain2
def SamEncryptNTLMHash(encryptedHash, DES.MODE_ECB)
plain1 = Crypt1.encrypt(Block1)
plain2 = Crypt2.encrypt(Block2)
return plain1 + plain2
def encrypt(s):
secret = ran(8)
key = PBKDF2(secret,salt,count=100000)
cipher = AES.new(key + padding(key))
pad = padding(s)
return [cipher.encrypt(s + pad), secret + chr(len(pad) + 97)]
#given an encrypted string and a key,returns a string
def decrypt(s,k):
pl = (ord(k[-1]) - 97)
key = PBKDF2(k[:-1],count=100000)
cipher = AES.new(key + padding(key))
raw = cipher.decrypt(s)
return raw[:-pl]
#encrypts data,saves it to a path and returns a key
def encrypt(raw, aes_key=secret):
iv = Random.new().read( AES.block_size )
cipher = AES.new(aes_key, iv )
return (base64.b64encode( iv + cipher.encrypt( raw ) ) )
def decrypt(enc, aes_key=secret):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(aes_key, iv )
return cipher.decrypt( enc[16:] )
def encrypt(raw):
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(KEY, iv)
return base64.b64encode( iv + cipher.encrypt(raw) )
def decrypt(enc):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(KEY, iv )
return unpad(cipher.decrypt(enc[16:]))
def encrypt(raw):
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(KEY, iv)
return base64.b64encode( iv + cipher.encrypt(raw) )
def decrypt(enc):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(KEY, iv )
return unpad(cipher.decrypt(enc[16:]))
def encrypt(text):
"""text (string)"""
aes = AES.new(settings.CRYPT_KEY, settings.CRYPT_IV)
return base64.b64encode(aes.encrypt(text.encode())).decode()
def decrypt(text):
"""Returns original string"""
text = base64.b64decode(text.encode())
aes = AES.new(settings.CRYPT_KEY, settings.CRYPT_IV)
return aes.decrypt(text).decode()
def hmacsha256(data, key):
return hmac.new(key, data, digestmod=hashlib.sha256).digest()
def encrypt(plain, iv):
#padding
padnum = 16 - (len(plain) % 16)
padded = plain + chr(padnum)*padnum
#encrypting
crypto = AES.new(key, iv)
encryptedBytes = crypto.encrypt(padded)
return encryptedBytes
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。