PyCrypto AES-CTR mode get different output - python-3.x

I use PyCrypto to encrypt my data, but why theirs output is different?
from Crypto.Cipher import AES
from Crypto.Util import Counter
data = b'\x02\x01\xf2\xca\x04\x03\x02P\x02\x02\x01\x80\xd0\x0f\x80\xd0\x0f'
key = b'random 16 string'
nonce = b'string 16 rand\x00\x01'
cipher = AES.new(key, AES.MODE_CTR, counter=lambda: nonce)
data_encrypted = cipher.encrypt(data)
print(data_encrypted)
# output is: b'_M\xed(\t4\xc4\x94\x80\x83K\x94qL\x15+R'
counter = Counter.new(2 * 8, prefix=b'string 16 rand', initial_value=1)
cipher = AES.new(key, AES.MODE_CTR, counter=counter)
data_encrypted = cipher.encrypt(data)
print(data_encrypted)
# output is: b'_M\xed(\t4\xc4\x94\x80\x83K\x94qL\x15+\xce'
Both methods will cause a memory leak. How to use pycryptodome to achieve the first effect

Related

AES encryption throws ValueError: Input strings must be a multiple of 16 in length

I want to encrypt data using AES.But I got a ValueError like below:
Traceback (most recent call last):
File "/home/a/AES/aes.py", line 14, in <module>
msg =cipher.encrypt(plaintext)
File "/home/a/anaconda3/envs/AES/lib/python3.9/site-packages/Crypto/Cipher/blockalgo.py", line 244, in encrypt
return self._cipher.encrypt(plaintext)
ValueError: Input strings must be a multiple of 16 in length
Code:
from Crypto.Cipher import AES
key = 'qwertyui87654388'
plaintext = "vgfcomo#456"
cipher = AES.new(key, AES.MODE_ECB)
msg =cipher.encrypt(plaintext)
print(msg.hex())
I want to implement below items in the code :
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Mode = CipherMode.ECB; // Noncompliant
aes.Padding = PaddingMode.PKCS7;
Can anyone suggest a solution to solve the issue and implement padding , BlockSize and KeySize in the python code?
AES has by definition a blocksize of 16 bytes. Allowed keysizes are 16, 24 and 32 bytes. With PyCryptodome, none of these need to be set. The keysize is implicitly set with the key, whose length must have one of the values allowed for AES.
Unlike many other libraries, PyCryptodome does not apply padding by default, which is the cause of the error message. However, PyCryptodome supports padding with a dedicated module, Crypto.Util.Padding, where PKCS#7 is the default.
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
key = 'qwertyui87654388'
plaintext = "vgfcomo#456"
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg =cipher.encrypt(pad(plaintext.encode('utf8'), 16))
print(msg.hex()) # 65e44255a2564a4861fcf65801dd6af7
Note that ECB is an insecure mode.
Edit - Regarding the question in your comment, decryption is done with:
from Crypto.Util.Padding import unpad
...
plaintext = unpad(cipher.decrypt(msg), 16)
...

Python 3 write encrypted string of bytes to file

I encrypt string:
def encrypt(self, message):
obj = AES.new('This is a key123'.encode("utf8"), AES.MODE_CFB, 'This is an IV456'.encode("utf8"))
encrypted = obj.encrypt(message.encode("utf8"))
return encrypted
How can I store encrypted in a file and read to decrypt using:
def decrypt(self, encrypted):
obj = AES.new('This is a key123'.encode("utf8"), AES.MODE_CFB, 'This is an IV456'.encode("utf8"))
decrypted=obj.decrypt(encrypted)
return decrypted
THe library "pycryptodome" has a full running example for AES encryption to a file and vice versa.
I know that the example runs another mode and stores additional data but that might be helpfull to you as the usage of a static IV is UNSECURE: https://pycryptodome.readthedocs.io/en/latest/src/examples.html
The following code generates a new AES128 key and encrypts a piece of data into a file. We use the EAX mode because it allows the receiver to detect any unauthorized modification (similarly, we could have used other authenticated encryption modes like GCM, CCM or SIV).
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)
file_out = open("encrypted.bin", "wb")
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
file_out.close()
At the other end, the receiver can securely load the piece of data back (if they know the key!). Note that the code generates a ValueError exception when tampering is detected.
from Crypto.Cipher import AES
file_in = open("encrypted.bin", "rb")
nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ]
# let's assume that the key is somehow available again
cipher = AES.new(key, AES.MODE_EAX, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)

this decryption code use already-given encrypted private key to decrypt the AES (session) key. an error occurred

code looks something like this:
from Crypto.Cipher import AES
import os
import base64
def decryption(encryptedString):
PADDING ='{'
DecodeAES=lambda c, e:c.decrypt(base64.b64decode(e)).rstrip(PADDING)
a = open('private_key0.pem','rb')
key = a.read()
print(key)
cipher = AES.new(key)
decoded = DecodeAES(cipher,encryptedString)
print (decoded)
a.close()
s = open('session_key0.eaes','rb')
cipher_text = s.read()
print(cipher_text)
s.close()
decryption(cipher_text)
error is in line cipher = AES.new(key) and decryption(cipher_text) saying missing mode.Do i need to encrypt the already excrypted files or what?

Implementing RSA/pkcs1_padding in Python 3.X

I'm trying to move my code from Python 2.7 to Python 3.5
Below is the current implementation in Python 2.7 which uses M2Crypto
import M2Crypto
import hashlib
from binascii import hexlify
# Generates the signature of payload
def getSign(payload_xml):
# SHA-1 digest of the payload
dig = myDigest(payload_xml)
# Loading the privateKey PEM file
private_key = M2Crypto.RSA.load_key('privatekey')
# Generating base 16 and encoding
signature = hexlify(private_key.private_encrypt(dig, M2Crypto.RSA.pkcs1_padding))
return signature
# To generate sha-1 digest of payload
def myDigest(payload):
# This will give base 16 of SHA-1 digest
digest_1 = hashlib.sha1(payload).hexdigest()
return digest_1
sign = getSign(<mypayload_xml>)
And this is the new implementation in Python 3.5 using pycryptodome
from Crypto.PublicKey import RSA
import hashlib
from Crypto.Cipher import PKCS1_v1_5
from binascii import hexlify
def myDigest(payload):
# This will give base 16 of SHA-1 digest
digest_1 = hashlib.sha1(payload.encode('utf-8')).hexdigest()
return digest_1
def getSign(payload_xml):
# SHA-1 digest of the payload
dig = myDigest(payload_xml)
with open('privatekey', 'r') as pvt_key:
miPvt = pvt_key.read()
rsa_key_obj = RSA.importKey(miPvt)
cipher = PKCS1_v1_5.new(rsa_key_obj)
cipher_text = cipher.encrypt(dig.encode())
base_16_new = hexlify(cipher_text)
return base_16_new
new_sign = getSign(<mypayload_xml>)
However, for same payload, signatures are different. Can someone help
with the proper solution?
As already mentioned in my comment, encrypt and decrypt of PyCryptodome can only be used to encrypt with the public key and decrypt with the private key. PyCryptodome has no 1:1-counterpart to private_encrypt or public_decrypt of M2Crypto, which allows the encryption with the private key and the decryption with the public key. Instead PyCryptodome uses sign and verify, which however work differently in detail, so that private_encrypt and sign don't generate the same signature (for the same key and message):
sign implements RSASSA-PKCS1-V1_5 padding described in RFC 8017, chapter 8.2. The hash value H of the message is padded as follows:
0x00 || 0x01 || PS || 0x00 || ID || H
ID identifies the digest and is for SHA1 (see here for other digests):
(0x)30 21 30 09 06 05 2b 0e 03 02 1a 05 00 04 14
PS are 0xFF fill bytes, so that the padded message has the length of the modulus.
The padding of private_encrypt differs from RSASSA-PKCS1-V1_5 padding in such a way that ID is not added automatically. So that sign and private_encrypt generate the same signature, ID must be added manually in the context of private_encrypt, e.g:
import M2Crypto
import hashlib
from binascii import hexlify, unhexlify
key = """-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----"""
def getSign(payload_xml):
dig = myDigest(payload_xml)
private_key = M2Crypto.RSA.load_key_string(key)
signature = hexlify(private_key.private_encrypt(unhexlify('3021300906052b0e03021a05000414' + dig.hexdigest()), M2Crypto.RSA.pkcs1_padding))
return signature
def myDigest(payload_xml):
digest_1 = hashlib.sha1(payload_xml)
return digest_1
sign = getSign(b"Hello world")
print("M2Crypto: " + sign)
As a site note, there is a bug in the original code: private_encrypt expects the data in binary format and not as hexadecimal string.
The corresponding PyCryptodome code could be e.g.:
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA1
from Crypto.PublicKey import RSA
key = """-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----"""
def getSign(payload_xml):
dig = myDigest(payload_xml)
private_key = RSA.import_key(key)
signature = pkcs1_15.new(private_key).sign(dig)
return signature
def myDigest(payload_xml):
digest_1 = SHA1.new(payload_xml)
return digest_1
sign = getSign(b'Hello world')
print("PyCryptodome: " + sign.hex())
With the following test key (for simplicity a 512 bit key):
key = """-----BEGIN PRIVATE KEY-----
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA2gdsVIRmg5IH0rG3
u3w+gHCZq5o4OMQIeomC1NTeHgxbkrfznv7TgWVzrHpr3HHK8IpLlG04/aBo6U5W
2umHQQIDAQABAkEAu7wulGvZFat1Xv+19BMcgl3yhCdsB70Mi+7CH98XTwjACk4T
+IYv4N53j16gce7U5fJxmGkdq83+xAyeyw8U0QIhAPIMhbtXlRS7XpkB66l5DvN1
XrKRWeB3RtvcUSf30RyFAiEA5ph7eWXbXWpIhdWMoe50yffF7pW+C5z07tzAIH6D
Ko0CIQCyveSTr917bdIxk2V/xNHxnx7LJuMEC5DcExorNanKMQIgUxHRQU1hNgjI
sXXZoKgfaHaa1jUZbmOPlNDvYYVRyS0CIB9ZZee2zubyRla4qN8PQxCJb7DiICmH
7nWP7CIvcQwB
-----END PRIVATE KEY-----"""
both codes provide for the following message:
payload_xml = b'The quick brown fox jumps over the lazy dog'
the following signature:
8324a560e6934fa1d1421b9ae37641c3b50a5c3872beecea808fbfed94151747aad69d5e083a23aa0b134d9e8c65e3a9201bb22ec28f459e605692e53965ad3b
Conclusion: It is possible to modify the M2Crypto code so that the result corresponds to the PyCryptodome code by simply adding ID. The other way around, however, it doesn't seem to be possible, because the PyCryptodome implementation adds ID automatically and this apparently can't be prevented.
In the second snippet, you are encrypting the SHA-1 digest using the PKCS#1 1.5 algorithm (Crypto.Cipher.PKCS1_v1_5 module). That is not a signature.
Instead, you should use the Crypto.Signature.pkcs1_15 module of pycryptodome. For instance, see the example taken from here:
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
message = 'To be signed'
key = RSA.import_key(open('private_key.der').read())
h = SHA256.new(message)
signature = pkcs1_15.new(key).sign(h)

Why the hex value is different in python and Javascript (Node Js)

I have been trying to encrypt something in Node JS and decrypt it in Python.
When I give the key(Secret key, base64 decoded) to Fernet.js, it forms a hex string which is equal to:
f790b0a226bc96a92de49b5e9c05e1ee
But when I give the same key in Python and try to convert into hex, the value is:
730ff4c7af3d46923e8ed451ee813c87f790b0a226bc96a92de49b5e9c05e1ee
Why there is a difference?
code sample for NodeJS:
let s = 'cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4='
new Buffer(s)).toString('hex')
Python:
be = base64.urlsafe_b64decode('cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=')
be.hex()
import base64 , binascii
key = "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4="
key = base64.urlsafe_b64decode(key)
# 32 bytes
f = binascii.hexlify(key)
# first 16
SigningKey = key[:16]
# next 16
EncKey = key[16:]
print (binascii.hexlify(SigningKey)) # 730ff4c7af3d46923e8ed451ee813c87
print (binascii.hexlify(EncKey)) # f790b0a226bc96a92de49b5e9c05e1ee

Resources