Sockets And Message Encryption/Decryption Between Client and Server
suggest changeIntroduction
Cryptography is used for security purposes. There are not so many examples of Encryption/Decryption in Python using IDEA encryption MODE CTR. Aim of this documentation :
Extend and implement the RSA digital-signature scheme in station-to-station communication. Use hashing for integrity of the message, that is SHA-1. Produce a simple key-transport protocol. Encrypt the key with IDEA. The block-cipher mode is counter mode. The steps below compare SHA-1 digests; they do not build an RSA signature. SHA-1 is not collision-resistant, and a 1024-bit RSA key is too small.
Remarks
Library Used:
*PyCrypto (Download Link: https://pypi.python.org/pypi/pycrypto )
*PyCryptoPlus (Download Link: https://github.com/doegox/python-cryptoplus )
Library Installation:
PyCrypto: Unzip the file. Go to the directory and open a terminal on Linux (Ctrl+Alt+T) and CMD (Shift+right click, then select Command Prompt) on Windows. After that run python setup.py install (make sure the Python environment is set properly on Windows). PyCrypto is unmaintained and was not installed here.
PyCryptoPlus: Same as the last library.
Tasks Implementation: The task is separated into two parts. One is handshake process and another one is communication process. Socket Setup:
- After creating the public and private keys and hashing the public key, set up the socket. Import it with
import socket, thenconnect(client) orbind(server) the address and port taken from the user.
socket.AF_INET, socket.SOCK_STREAM is TCP and provides accept(). socket.AF_INET, socket.SOCK_DGRAM is UDP and has no accept(). setblocking is a separate socket option, not a substitute for that choice.
Handshake Process:
- (CLIENT)The first task is to create public and private key. To create the private and public key, we have to import some modules. They are : from Crypto import Random and from Crypto.PublicKey import RSA. To create the keys, we have to write few simple lines of codes:
random_generator = Random.new().read
key = RSA.generate(1024,random_generator)
public = key.publickey().exportKey()
random_generator is derived from “from Crypto import Random” module. Key is derived from “from Crypto.PublicKey import RSA” which will create a private key, size of 1024 by generating random characters. Public is exporting public key from previously generated private key.
- (CLIENT) After creating the public and private key, we have to hash the public key to send over to the server using SHA-1. To use SHA-1 we need to import another module by writing
import hashlib. To hash the public key we have to write two lines of code:
hash_object = hashlib.sha1(public)
hex_digest = hash_object.hexdigest()
Here hash_object and hex_digest are our variables. After this, the client will send hex_digest and public to the server and the server will verify them by comparing the hash from the client with a new hash of the public key. If the new hash and the hash from the client match, it will move to the next procedure. hashlib.sha1 requires a bytes-like object. On Python 3, a str raises TypeError. To turn the exported public key back into an RSA key, the text uses server_public_key = RSA.importKey(getpbk). getpbk is the public key from the client, and it is not defined in these fragments.
- (SERVER) The next step is to create a session key. The text uses the
osmodule,key = os.urandom(16), which is 16 bytes (128 bits), not 16 bits. The snippet then encrypts withAES.MODE_CTR, not IDEA, and hashes the result with SHA-1.key_128is not defined in the snippet:
#encrypt CTR MODE session key
en = AES.new(key_128,AES.MODE_CTR,counter = lambda:key_128)
encrypto = en.encrypt(key_128)
#hashing sha1
en_object = hashlib.sha1(encrypto)
en_digest = en_object.hexdigest()
The lambda returns the same value on every call, so the counter does not change. en_digest is the 40-character SHA-1 hex digest of that ciphertext, not the 16-byte session key. The two statements had been jammed onto one line, which is a syntax error; they are split above.
- (SERVER) The final part of the handshake encrypts the session material with the client's public key.
#encrypting session key and public key
E = server_public_key.encrypt(encrypto,16)
After encrypting, the server will send the key to the client as a string. In PyCrypto, RSA.encrypt(plaintext, K) takes a random integer K, not a length. The literal 16 is not a suitable K. server_public_key is not defined in this fragment.
- (CLIENT) After getting the encrypted string from the server, the client decrypts it with the private key created earlier. The text turns that string back into a value with
eval().evalexecutes the string as Python, so a message can do more than represent a key. If decryption is done, the text treats the handshake as complete because both sides confirm that they are using the same keys. To decrypt:
en = eval(msg)
decrypt = key.decrypt(en)
# hashing sha1
en_object = hashlib.sha1(decrypt)
en_digest = en_object.hexdigest()
msg and key are not defined in this fragment. The hash lines had been jammed together, which is a syntax error; they are split above.
I have used the SHA-1 here so that it will be readable in the output.
Communication Process:
For the communication process, both sides use the session key as the key for IDEA in counter mode. Both sides encrypt and decrypt messages with IDEA.MODE_CTR and that session key.
- (Encryption) IDEA needs a 16-byte (128-bit) key, and the counter must be callable. A counter is mandatory in
MODE_CTR. The SHA-1 hex digest is 40 characters, which is not a 16-byte IDEA key, so the text shortens it with slicing,key[:16]. That slice is string notation, not a function namedstring.key[16:]is the other end of the string, not another 16-byte key.IDEA.new()takes the key, the mode (IDEA.MODE_CTR), andcounter. The lambda below returns the same value every time, so the counter does not increment. The callable that generates a counter in PyCrypto isCrypto.Util.Counter, notCounter.Util. The code is:
ideaEncrypt = IDEA.new(key, IDEA.MODE_CTR, counter=lambda : key)
Once defining the “ideaEncrypt” as our IDEA encryption variable, we can use the built in encrypt function to encrypt any message.
encrypted_message = ideaEncrypt.encrypt(whole)
hex_message = encrypted_message.hex().upper()
In this code segment, whole is the message to encrypt, encrypted_message contains the resulting bytes, and hex_message is their uppercase hexadecimal representation. The hexadecimal string can then be sent to the other endpoint for decryption. whole and key are not defined in this fragment. bytes.hex exists, but this call was not run.
- (Decryption)
To decrypt the encrypted messages, we will need to create another encryption variable by using the same arguments and same key but this time the variable will decrypt the encrypted messages. The code for this is the same as the last time. However, before decrypting the messages, we need to decode the message from hexadecimal because in our encryption part, we encoded the encrypted message in hexadecimal to make it readable. Hence, the whole code will be:
encrypted_message = bytes.fromhex(hex_message)
ideaDecrypt = IDEA.new(key, IDEA.MODE_CTR, counter=lambda: key)
decrypted_message = ideaDecrypt.decrypt(encrypted_message)
hex_message and key are not defined in this fragment. The lambda returns the same value on every call, so the counter does not increment. bytes.fromhex exists, but this call was not run. These processes will be done on both the server and the client side for encrypting and decrypting.