def __rsa_key_exchange(self, data, metadata): if self.check_sid(self.s_sid): # XXX: The fact that the server session ID is in # the dictionary already is a really bad thing. # There should be no client key exchange message # if the client and server agree to resume. raise sslimBadValue("SID found with client key exchange") # XXX: The size of this is dependent upon the cipher suite chosen! # Section 7.4.7.1 of RFC5246 details what these bytes mean for # RSA authentication! if self.ver == self.SSLv3_0: if self.cipher_suite['key_exch'] != 'RSA': raise sslimUnknownCipher("SSLv3 not RSA key exchange") pms = data else: # The first two bytes are the length of the key. pms_len = int(struct.unpack('>H', data[:self.hs_pms_len_size])[0]) data = data[self.hs_pms_len_size:] pms = struct.unpack('%ss' % pms_len, data[:pms_len])[0] metadata['pre_master_secret'] = pms if self.keypair: try: cpms = self.keypair.private_decrypt(pms, RSA.sslv23_padding) except Exception as e: raise sslimCryptoError(str(e)) seed = self.c_rnd + self.s_rnd self.ms = self.__PRF(cpms, "master secret", seed, 48)[:48] metadata['master_secret'] = self.ms # Store the master secret in the sids dictionary self.store_ms(self.s_sid, self.ms) # From the master secret you generate the key material seed = self.s_rnd + self.c_rnd km = self.__key_material(self.cipher_suite['km_len'], self.s_rnd + self.c_rnd, self.ms) keys = self.__split_key_material(km) metadata['keys'] = keys self.cipher_suite['keys'] = keys if self.cipher_suite['cipher'] == 'stream': self.c_cryptobj = RC4.RC4(keys['client_enc_key']) self.s_cryptobj = RC4.RC4(keys['server_enc_key']) elif self.cipher_suite['cipher'] == 'block': self.c_cryptobj = EVP.Cipher(self.cipher_suite['algo'], keys['client_enc_key'], keys['client_iv'], 0, padding=0) self.s_cryptobj = EVP.Cipher(self.cipher_suite['algo'], keys['server_enc_key'], keys['server_iv'], 0, padding=0)
def make_sym_key(self, randomData=None): if not randomData: self.randomData = os.urandom(Globals.SYMMETRIC_KEY_BYTES) else: self.randomData = randomData self.hmacKey = self.randomData self.iv = self.randomData[:IV_LENGTH] self.decryptCipher = EVP.Cipher(self.alg, self.randomData, self.iv, 0) self.encryptCipher = EVP.Cipher(self.alg, self.randomData, self.iv, 1)
def testAes(self): enc = 1 dec = 0 tests = [ # test vectors from rfc 3602 #Case #1: Encrypting 16 bytes (1 block) using AES-CBC with 128-bit key { 'KEY': '06a9214036b8a15b512e03d534120006', 'IV': '3dafba429d9eb430b422da802c9fac41', 'PT': 'Single block msg', 'CT': 'e353779c1079aeb82708942dbe77181a', }, #Case #2: Encrypting 32 bytes (2 blocks) using AES-CBC with 128-bit key { 'KEY': 'c286696d887c9aa0611bbb3e2025a45a', 'IV': '562e17996d093d28ddb3ba695a2e6f58', 'PT': unhexlify('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'), 'CT': 'd296cd94c2cccf8a3a863028b5e1dc0a7586602d253cfff91b8266bea6d61ab1', }, #Case #3: Encrypting 48 bytes (3 blocks) using AES-CBC with 128-bit key { 'KEY': '6c3ea0477630ce21a2ce334aa746c2cd', 'IV': 'c782dc4c098c66cbd9cd27d825682c81', 'PT': 'This is a 48-byte message (exactly 3 AES blocks)', 'CT': 'd0a02b3836451753d493665d33f0e8862dea54cdb293abc7506939276772f8d5021c19216bad525c8579695d83ba2684', }, ] # Test with padding for test in tests: # encrypt (op=enc [1]) k=EVP.Cipher(alg='aes_128_cbc', key=unhexlify(test['KEY']), iv=unhexlify(test['IV']), op=enc) pbuf=cStringIO.StringIO(test['PT']) cbuf=cStringIO.StringIO() ciphertext = hexlify(self.cipher_filter(k, pbuf, cbuf)) cipherpadding = ciphertext[len(test['PT']) * 2:] print ciphertext ciphertext = ciphertext[:len(test['PT']) * 2] # Remove the padding from the end print ciphertext,cipherpadding pbuf.close() cbuf.close() self.assertEqual(ciphertext, test['CT']) # decrypt (op=dec [0]) j=EVP.Cipher(alg='aes_128_cbc', key=unhexlify(test['KEY']), iv=unhexlify(test['IV']), op=dec) pbuf=cStringIO.StringIO() cbuf=cStringIO.StringIO(unhexlify(test['CT'] + cipherpadding)) plaintext=self.cipher_filter(j, cbuf, pbuf) print plaintext pbuf.close() cbuf.close() self.assertEqual(plaintext, test['PT']) print "**"
def test_AES_ctr(self): # noqa # In CTR mode, encrypt and decrypt are actually the same # operation because you encrypt the nonce value, then use the # output of that to XOR the plaintext. So we set operation=0, # even though this setting is ignored by OpenSSL. op = 0 nonce = unhexlify( '4a45a048a1e9f7c1bd17f2908222b964') # CTR nonce value, 16 bytes key = unhexlify( '8410ad66fe53a09addc0d041ae00bc6d70e8038ec17019f27e52eecd3846757e') plaintext_value = b'This is three blocks of text with unicode char \x03' ciphertext_values = { '128': unhexlify( '6098fb2e49b3f7ed34f841f43f825d84cf4834021511594b931c85f04662544bdb4f38232e9d87fda6280ab1ef450e27' ), # noqa '192': unhexlify( '2299b1c5363824cb92b5851dedc73f49f30b23fb23f288492e840c951ce703292a5c6de6fc7f0625c403648f8ca4a582' ), # noqa '256': unhexlify( '713e34bcd2c59affc9185a716c3c6aef5c9bf7b9914337dd96e9d7436344bcb9c35175afb54adb78aab322829ce9cb4a' ), # noqa } for key_size in [128, 192, 256]: alg = 'aes_%s_ctr' % str(key_size) log.info('Testing cipher %s', alg) # Our key for this test is 256 bits in length (32 bytes). # We will trim it to the appopriate length for testing AES-128 # and AES-192 as well (so 16 and 24 bytes, respectively). key_truncated = key[0:(key_size // 8)] # Test encrypt operations cipher = EVP.Cipher(alg=alg, key=key_truncated, iv=nonce, op=op) ciphertext = cipher.update(plaintext_value) ciphertext = ciphertext + cipher.final() self.assertEqual(ciphertext, ciphertext_values[str(key_size)]) # Test decrypt operations cipher = EVP.Cipher(alg=alg, key=key_truncated, iv=nonce, op=op) plaintext = cipher.update(ciphertext_values[str(key_size)]) plaintext = plaintext + cipher.final() # XXX not quite sure this is the actual intention # but for now let's be happy to find the same content even if with # a different type - XXX self.assertEqual(plaintext, plaintext_value)
def test_AES(self, test): # noqa enc = 1 dec = 0 # Test with padding # encrypt k = EVP.Cipher(alg='aes_128_cbc', key=unhexlify(test['KEY']), iv=unhexlify(test['IV']), op=enc) pbuf = io.BytesIO(test['PT']) cbuf = io.BytesIO() ciphertext = hexlify(self.cipher_filter(k, pbuf, cbuf)) cipherpadding = ciphertext[len(test['PT']) * 2:] # Remove the padding from the end ciphertext = ciphertext[:len(test['PT']) * 2] pbuf.close() cbuf.close() self.assertEqual(ciphertext, test['CT']) # decrypt j = EVP.Cipher(alg='aes_128_cbc', key=unhexlify(test['KEY']), iv=unhexlify(test['IV']), op=dec) pbuf = io.BytesIO() cbuf = io.BytesIO(unhexlify(test['CT'] + cipherpadding)) plaintext = self.cipher_filter(j, cbuf, pbuf) pbuf.close() cbuf.close() self.assertEqual(plaintext, test['PT']) # Test without padding # encrypt k = EVP.Cipher(alg='aes_128_cbc', key=unhexlify(test['KEY']), iv=unhexlify(test['IV']), op=enc, padding=False) pbuf = io.BytesIO(test['PT']) cbuf = io.BytesIO() ciphertext = hexlify(self.cipher_filter(k, pbuf, cbuf)) pbuf.close() cbuf.close() self.assertEqual(ciphertext, test['CT']) # decrypt j = EVP.Cipher(alg='aes_128_cbc', key=unhexlify(test['KEY']), iv=unhexlify(test['IV']), op=dec, padding=False) pbuf = io.BytesIO() cbuf = io.BytesIO(unhexlify(test['CT'])) plaintext = self.cipher_filter(j, cbuf, pbuf) pbuf.close() cbuf.close() self.assertEqual(plaintext, test['PT'])
def verify_and_decrypt(pmsg, emsg, sig, senderPubPem, receiverPrivPem, hash = 'sha256', cipher = 'aes_256_cbc', padding = 'pkcs1_oaep'): padding = PADDING[padding] pmsg = binascii.a2b_base64(pmsg) emsg = binascii.a2b_base64(emsg) sig = binascii.a2b_base64(sig) key_len = int(cipher.split("_")[1]) md = EVP.MessageDigest(hash) md.update(pmsg) md.update(emsg) digest = md.digest() skey = RSA.load_pub_key_bio(BIO.MemoryBuffer(senderPubPem)) if not skey.verify(digest, sig, hash): raise Exception("could not verify signature") rkey = RSA.load_key_bio(BIO.MemoryBuffer(receiverPrivPem)) kv = rkey.private_decrypt(emsg, padding) key = kv[0:key_len/8] iv = kv[key_len/8:] c = EVP.Cipher(alg = cipher, key = key, iv = iv, op = m2.decrypt) msg = cipher_filter(c, pmsg) return msg
def encrypt_image(self, file): print 'Encrypting image' enc_file = '%s.part' % file.replace('.tar.gz', '') # get 17 bytes of randomness with top bit a '1'. # convert to a hex string like '0x<34 hex chars>L' # then take the last 32 of the hex digits, giving 32 random hex chars key = hex(BN.rand(17 * 8, top=0))[4:36] if self.euca.debug: print 'Key: %s' % key iv = hex(BN.rand(17 * 8, top=0))[4:36] if self.euca.debug: print 'IV: %s' % iv k = EVP.Cipher(alg='aes_128_cbc', key=unhexlify(key), iv=unhexlify(iv), op=1) in_file = open(file, 'rb') out_file = open(enc_file, 'wb') self.crypt_file(k, in_file, out_file) in_file.close() out_file.close() bundled_size = os.path.getsize(enc_file) return (enc_file, key, iv, bundled_size)
def main(self, configXmls): values = {} i = 0 for configXml in configXmls: f = open(configXml) text = f.read() f.close() w = {} for m in re.finditer(self._pattern, text): if m.group(1) == 'login': w["login"] = m.group(2) elif m.group(1) == "encpassword": w["encpassword"] = m.group(2) ## unhex + correct endianness arr = array.array("B") arr.fromstring(m.group(2).decode('hex')) for i in range(len(arr)): arr[i] = (arr[i] & 0xf) << 4 | (arr[i] >> 4) p = arr.tostring() ## decryption c = EVP.Cipher("des_ecb", (w["login"] + "dummykey")[:8], "", m2.decrypt, 0) c.set_padding(0) w["password"] = c.update(p) + c.final() i += 1 values["user%d" % i] = w w = {} return {self.__class__.__name__: values}
def update(self, chunk): if self._cipher is None: if len(chunk) < 16: raise Exception('Invalid first chunk (Size < 16).') if chunk[0:8] != b"Salted__": raise Exception('Invalid first chunk (expected: Salted__') [key, iv] = self._get_key_iv(self._password, chunk[8:16]) if HAS_M2CRYPTO: self._cipher = EVP.Cipher('des_cbc', key, iv, 0) elif HAS_CRYPTOGRAPHY: self._cipher = Cipher(algorithms.TripleDES(key), modes.CBC(iv), backend=default_backend()).decryptor() else: self._cipher = DES.new(key, DES.MODE_CBC, iv) chunk = chunk[16:] if len(chunk) > 0: if HAS_M2CRYPTO: return self._cipher.update(chunk) elif HAS_CRYPTOGRAPHY: return self._cipher.update(chunk) else: return self._cipher.decrypt(chunk) else: return b""
def encrypt_and_sign(msg, senderPrivPem, receiverPubPem, hash = 'sha256', cipher = 'aes_256_cbc', padding = 'pkcs1_oaep'): padding = PADDING[padding] key_len = int(cipher.split("_")[1]) key = os.urandom(key_len/8) iv = os.urandom(key_len/8) c = EVP.Cipher(alg = cipher, key = key, iv = iv, op = m2.encrypt) pmsg = cipher_filter(c, msg) rkey = RSA.load_pub_key_bio(BIO.MemoryBuffer(receiverPubPem)) emsg = rkey.public_encrypt(key + iv, padding) md = EVP.MessageDigest(hash) md.update(pmsg) md.update(emsg) digest = md.digest() skey = RSA.load_key_bio(BIO.MemoryBuffer(senderPrivPem)) sig = skey.sign(digest, hash) return (binascii.b2a_base64(pmsg).strip(), binascii.b2a_base64(emsg).strip(), binascii.b2a_base64(sig).strip())
def decrypt(self, data): decipher = EVP.Cipher(alg='aes_256_cbc', key=self.key, iv=self.iv, op=0) result = decipher.update(data) result += decipher.final() return result
def encrypt(self, data): encipher = EVP.Cipher(alg='aes_256_cbc', key=self.key, iv=self.iv, op=1) result = encipher.update(data) result += encipher.final() return result
def encrypt_cbc128(cls,src,key,iv ): k=EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=1) # 1 : encrypt pbuf=cStringIO.StringIO(src) cbuf=cStringIO.StringIO() ret= CX.cipher_filter(k, pbuf, cbuf) pbuf.close() cbuf.close() return ret
def dec_check(c): iv = c[:16] ctxt = c[16:] cobj = EVP.Cipher('aes_128_cbc', key, iv, 0, 0) ptxt = '' ptxt = cobj.update(ctxt) ptxt += cobj.final() return ''
def decrypt_cbc128(cls,src,key,iv ): j=EVP.Cipher(alg='aes_128_cbc', key=key,iv=iv,op=0 ) # 0 : decrypt pbuf=cStringIO.StringIO() cbuf=cStringIO.StringIO(src) ret = CX.cipher_filter(j, cbuf, pbuf) pbuf.close() cbuf.close() return ret
def encrypt(data, key, iv='iv', ciph='bf_cbc'): k = EVP.Cipher(alg=ciph, key=key, iv=iv, op=1) pbuf = cStringIO.StringIO(data) cbuf = cStringIO.StringIO() ciphertext = cipher_filter(k, pbuf, cbuf) pbuf.close() cbuf.close() return ciphertext
def decrypt(ciphertext, key, iv, alg='aes_256_cbc'): cipher = EVP.Cipher(alg=alg, key=key, iv=iv, op=0) pbuf = cStringIO.StringIO() cbuf = cStringIO.StringIO(ciphertext) plaintext = _cipherFilter(cipher, cbuf, pbuf) pbuf.close() cbuf.close() return plaintext
def m2_encrypt(plaintext, key, iv, key_as_bytes=False, padding=True): cipher = EVP.Cipher(alg="aes_256_cbc", key=key, iv=iv, key_as_bytes=key_as_bytes, padding=padding, op=1) return cipher.update(plaintext) + cipher.final()
def init_encrypt(self, secret=None): self._ensecret = (secret[:32], secret[32:]) if secret and len(secret) >= 64 else ( rand_string(32), rand_string(32)) self._encipher = EVP.Cipher(self._alg, self.bytes_to_key(self._ensecret[0]), self._ensecret[1], 1, 0) return "".join(self._ensecret)
def decryptData(decKey, essiv, data): # try to decrypt the actual data cipher = EVP.Cipher(alg='aes_128_cbc', key=decKey, iv=essiv, op=0) # 0 is DEC cipher.set_padding(padding=0) decData = cipher.update(data) decData = decData + cipher.final() return decData
def decrypt(data, key, iv='iv', ciph='bf_cbc'): j = EVP.Cipher(alg=ciph, key=key, iv=iv, op=0) pbuf = cStringIO.StringIO() cbuf = cStringIO.StringIO(data) plaintext = cipher_filter(j, cbuf, pbuf) pbuf.close() cbuf.close() return plaintext
def decrypt(self, enc, key, iv): enc = base64.b64decode(enc) cipher = EVP.Cipher('aes_256_cfb', key, iv, 0) output = cStringIO.StringIO() output.write(cipher.update(enc)) output.write(cipher.final()) enc = output.getvalue() output.close() return unpad(enc)
def encrypt(self, raw, key, iv): raw = pad(raw) cipher = EVP.Cipher('aes_256_cfb', key, iv, 1) output = cStringIO.StringIO() output.write(cipher.update(raw)) output.write(cipher.final()) raw = base64.b64encode(output.getvalue()) output.close() return raw
def unpackEncryptedM2(self, machine, payload, alg): m2alg={XFRM_HIP_DES_CBC: ('des_ede3_cbc', 24, 64), XFRM_HIP_Blowfish_CBC: ('bf_cbc', 16, 64) }[alg] iv = payload[:m2alg[2]] cipher=EVP.Cipher(m2alg[0], machine.remotehipkey, iv, dec) plaintext = cipher.update(payload[m2alg[2]:]) plaintext += cipher.final() return plaintext
def packEncryptedM2(self, machine, payload, alg): m2alg={XFRM_HIP_DES_CBC: ('des_ede3_cbc', 24, 64), XFRM_HIP_Blowfish_CBC: ('bf_cbc', 16, 64) }[alg] iv = Rand.rand_bytes(m2alg[2]) cipher=EVP.Cipher(m2alg[0], machine.hipkey, iv, enc) plaintext = cipher.update(payload) plaintext += cipher.final() return '%s%s' % (iv, plaintext)
def m2_AES_decrypt(data, key): key = hashlib.md5(key).digest() iv = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' j = EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=0, padding=True) pbuf = StringIO() cbuf = StringIO(data) plaintext = m2_cipher_filter(j, cbuf, pbuf) pbuf.close() cbuf.close() return plaintext
def m2_AES_encrypt(data, key): key = hashlib.md5(key).digest() iv = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' k = EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=1, padding=True) pbuf = StringIO(data) cbuf = StringIO() ciphertext = m2_cipher_filter(k, pbuf, cbuf) pbuf.close() cbuf.close() return ciphertext
def _set_ciphers(self): """ Create the ciphers for encrypting and decrypting. It's not clear whether we need to have two ciphers or whether we could make do with one. Better safe than sorry. """ self._enc_cipher = EVP.Cipher(alg='aes_256_cbc', key=self._key, iv=self.iv, op=1, padding=0) self._dec_cipher = EVP.Cipher(alg='aes_256_cbc', key=self._key, iv=self.iv, op=0, padding=0)
def decrypt(db,acc): fh = file(db,'rb') edb = fh.read() fh.close() m = hashlib.md5() m.update(acc) md5 = bytearray(m.digest()) for i in xrange(24): key[i] ^= md5[i&0xF] cipher = EVP.Cipher('aes_192_cbc', key=key, iv=iv, op=0) sys.stdout.write(cipher.update(edb)) sys.stdout.write(cipher.final())
def _crypt_py2(cls, op, key, iv, data): cipher = EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=op, padding=False) inf = StringIO(data) outf = StringIO() while True: buf = inf.read() if not buf: break outf.write(cipher.update(buf)) outf.write(cipher.final()) return outf.getvalue()