SSL/TLS: Difference between revisions

Jump to navigation Jump to search
1,752 bytes added ,  8 years ago
[unchecked revision][unchecked revision]
No edit summary
Line 195:
* Encrypt the final plaintext using the client/server_write_key and this IV
* The ciphertext is the concatenation of IV + ciphertext
 
<source lang="python">
from Crypto.Hash import *
from Crypto.Cipher import AES
 
def to_bytes(n):
h = '%x' % n
s = ('0'*(len(h) % 2) + h).decode('hex')
return s
 
def nb_to_hex(nb, size):
s = to_bytes(nb)
return '\x00' * (size - len(s)) + s
 
def encrypt(plaintext, iv, key_AES, key_MAC, seq_num, content_type):
hmac = HMAC.new(key_MAC, digestmod=SHA)
plaintext_to_mac = nb_to_hex(seq_num, 8) + nb_to_hex(content_type, 1) + '\x03\x03' + nb_to_hex(len(plaintext), 2) + plaintext
hmac.update(plaintext_to_mac)
mac_computed = hmac.digest()
 
cipher = AES.new(key_AES, AES.MODE_CBC, iv)
plaintext += mac_computed
padding_length = 16 - (len(plaintext) % 16)
if padding_length == 0:
padding_length = 16
 
padding = chr(padding_length - 1) * padding_length
ciphertext = cipher.encrypt(plaintext + padding)
 
return ciphertext
 
def decrypt(message, key_AES, key_MAC, seq_num, content_type, debug=False):
iv = message[0:16]
cipher = AES.new(key_AES, AES.MODE_CBC, iv)
decoded = cipher.decrypt(message[16:])
 
padding = to_int(decoded[-1:]) + 1
plaintext = decoded[0:-padding-20]
mac_decrypted = decoded[-padding-20:-padding]
 
hmac = HMAC.new(key_MAC, digestmod=SHA)
plaintext_to_mac = nb_to_hex(seq_num, 8) + nb_to_hex(content_type, 1) + '\x03\x03' + nb_to_hex(len(plaintext), 2) + plaintext
hmac.update(plaintext_to_mac)
mac_computed = hmac.digest()
 
if debug:
print('Decrypted: [' + decoded.encode('hex') + ']')
print('Plaintext: [' + plaintext.encode('hex') + ']')
print('MAC (decrypted): ' + to_hex(mac_decrypted))
print('MAC (computed): ' + to_hex(mac_computed))
print('')
 
return plaintext
</source>
 
[[Category:Network Protocols]]
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

Navigation menu