def decrypt_file(file, key): from crypto.cipher.aes import AES from crypto.cipher.base import noPadding cipher = AES(key, keySize=len(key), padding=noPadding()) data = '' with open(file, "rb") as f: data = f.read() with open(file, "wb") as f: offset = 0 while True: for enc in [True, False]: if enc: chunk = data[offset:offset + len(key)] offset += len(key) else: chunk = data[offset:offset + len(key) * 1000] offset += len(key) * 1000 if len(chunk) == len(key): chunk = cipher.decrypt(chunk) f.write(chunk) if not chunk: break f.close()
def CCMtestVector(testCase, macSize, key, nonce, addAuth, pt, kct): """ CCM test vectors using AES algorithm """ print '%s %s %s' % ('=' * ((54 - len(testCase)) / 2), testCase, '=' * ((54 - len(testCase)) / 2)) key, nonce, pt, addAuth, kct = a2b_p(key), a2b_p(nonce), a2b_p( pt), a2b_p(addAuth), a2b_p(kct) alg = CCM(AES(key, keySize=len(key)), macSize=macSize, nonceSize=len(nonce)) print 'alg=%s%skeySize=%3d blockSize=%3d M=%2d L=%2d' % ( alg.baseCipher.name, ' ' * (10 - len(alg.baseCipher.name)), alg.keySize, alg.blockSize, alg.M, alg.L) print 'key: %s' % b2a_p(key)[9:] print 'nonce: %s' % b2a_p(nonce)[9:] print 'addAuth:%s' % b2a_p(addAuth)[9:] print 'pt: %s' % b2a_p(pt)[9:] ct = alg.encrypt(pt, nonce=nonce, addAuthData=addAuth) print 'ct: %s' % b2a_p(ct)[9:] print 'kct: %s' % b2a_p(kct)[9:] print '========================================================' self.assertEqual(ct, kct) dct = alg.decrypt(ct, nonce=nonce, addAuthData=addAuth) self.assertEqual(dct, pt)
def CBCtestVector(key, iv, pt, kct): """ CBC test vectors using AES algorithm """ key, iv, pt, kct = a2b_p(key), a2b_p(iv), a2b_p(pt), a2b_p(kct) alg = CBC(AES(key), padding=noPadding()) self.assertEqual(alg.encrypt(pt, iv=iv), kct) self.assertEqual(alg.decrypt(iv + kct), pt)
def generate_mic(data): ''' \brief Generate a Message Integrity Code (MIC) over some given data. \param[in] data The data to calculate the MIC over, a binary string. \returns The 32-bit MIC, an integer. ''' #alg = AES_CBC(key=OTAP_KEY, keySize=len(OTAP_KEY), padding=padWithZeros()) #outdata = alg.encrypt(data, iv=OTAP_NONCE) alg = CCM(AES(OTAP_KEY), macSize=OTAP_MIC_LEN) outdata = alg.encrypt('', OTAP_NONCE, addAuthData=data) # the 32-bit MIC is the first 4 bytes of the CBC-MAC result (per CCM spec) #return struct.unpack('!L', outdata[-16:-12])[0] return struct.unpack('!L', outdata[-OTAP_MIC_LEN:])[0]
def __init__(self, key=None, padding=padWithPadLen(), keySize=16): CBC.__init__(self, AES(key, noPadding(), keySize), padding) self.name = 'AES_CBC'
def test(self): aes_cbc = CBC(AES()) aes_cbc.setKey('aaaaaaaaaaaaaaaa') ct1 = aes_cbc.encrypt('test') ct2 = aes_cbc.encrypt( 'test') # note - auto iv, reslt is different ths time