I am studying Cryptography for the first time, I am looking at the 3DES cipher and I have to program it with the help of any library, in this case I use PyCryptodome, the point is that I have to show the keys that I will use to encrypt, and if I don't get it wrong, they must be 3 of 56 bits
In python I am using this code
from email import message
from Crypto.Cipher import DES3
from Crypto.Random import get_random_bytes
import base64
while True:
try:
key = DES3.adjust_key_parity(get_random_bytes(24))
print(key)
archivo = open("key.txt","w")
message = str(key)
message_bytes = message.encode('ascii')
b64_bytes = base64.b64encode(message_bytes)
b64_k = b64_bytes.decode('ascii')
archivo.write(b64_k)
archivo.close()
break
except ValueError:
pass
Code that is in the documentation but modified to return the key in base64, but it returns a single string, how can I print the 3 keys, is there something I am not understanding? And when it creates the key I don't understand why it asks for 24 bytes, also when I print the key or count the number of characters sometimes they are more and sometimes they are less, why is this? Can I print the strings separately to analyze them? If someone can enlighten me, it would help me a lot to understand more and of course to fulfill my duties, thank you very much..!! good morning :D
Here is the execution of the program 3 times and strings of different sizes are clearly seen. I'm a bit lost really
I don't understand the crypto part, but your code doesn't fit what you need.
The biggest problem is that you open the file with option "w" on each iteration of the
while
. That means the file is recreated on every pass, and will never have more than one key.The solution is to create the file outside of the iteration.
You should also change the iteration. If you want to generate three keys, better use a
for llave in range(3)
.With that the code is:
The keys are always 24 bytes long, as you can see. They seem to be of different lengths because you are looking at their encoded representation .
The point is that the key can contain any binary value, and in order to store/transmit it losslessly, it needs to be encoded in some format. This transformation can create a longer representation than the original, but when you need to use it, you just have to decode it.