I have server written in python and client in C . Their job is to send a secret message from server to client which is encrypted with RSA private key. I am using openssl/rsa.h library, that is I initialize a rsa object with a private key and encrypte a message with RSA_public_encrypt(length_of_message, "Secret Message", to, rsa, RSA_PKCS1_PADDING) . Then I send this encrypted message to python server and try to decrypt it with same private key using from Crypto.PublicKey import RSA library. Problem is that it does not decrypt it properly. It always outputs 128-bit length message where the secret message is randomly placed in it (e.g. '\x23\xa3x\43...Secret Message\xef\x4a'), where it should normally return just Secret Message.
The problem was about the padding. Python's rsa module decrypts result with PKCS1 padding and does not removes padding. With the function below which I have taken from here problem was solved:
def pkcs1_unpad(text):
if len(text) > 0 and text[0] == '\x02':
# Find end of padding marked by nul
pos = text.find('\x00')
if pos > 0:
return text[pos+1:]
return None
Is it possible to create a same pair of RSA key in Python and C . please find the code below and let me know if any modification needed to get it worked.
Code in python
key = RSA.generate(2048)
file_out_pub = open("pubkey.der", "wb")
file_out_pub.write(key.publickey().exportKey())
file_out_pub.close()
file_out_pub = open("pubkey.der", "`enter code here`r")
public_key = RSA.importKey(file_out_pub.read())
cipher = PKCS1_OAEP.new(public_key)
password = pw
ciphertext = cipher.encrypt(password)
Code in C
int clen = 0, num, ret;
clen = strnlen_s(req->pw,2048);
unsigned char ptext[2048];
RSA *rsa = RSA_new();
BIGNUM *e = BN_new();
ret = RSA_generate_key_ex(rsa, 2048, e, NULL );
num = RSA_private_decrypt(clen, req->pw , ptext, rsa, RSA_PKCS1_OAEP_PADDING);
// Start authentication process
strncpy(req->pw,ptext,MAX_PASSWORD_STR);
Related
I'm trying to implement Mixnet in Python. Consider the example in the linked wiki page — A encrypts a message with A's public key and then encrypts the resulting ciphertext along with B's address with M's public key.
When I run my code which attempts to do the above, I get ValueError: Plaintext is too long. that's because I'm not appending the address B the right way and I'm exceeding the 1024 size of RSA. How do I accomplish this with RSA?
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto import Random
def create_rsa():
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
return key, publickey
def encrypt(message, key):
ciphertext = PKCS1_OAEP.new(key)
return ciphertext.encrypt(message)
message = "chocolate milk"
prA, A = create_rsa()
prB, B = create_rsa()
prM, M = create_rsa()
# A sealing stuff
Kb = encrypt(message, B)
KbAddress = Kb + "B"
Km = encrypt(KbAddress, M)
tl;dr How do I do with RSA?
Is it possible to encrypt a message with a private key in python using pycryptodome or any other library? I know that you are not supposed to encrypt with the private key and decrypt with the public key, but my purpose is to encrypt with the private one so the receiver could be sure that the message was send by the real author. More than secure encryption I'm looking for some kind of obfuscation. I want to do an app where the message is public but it can only be seen if you have the public key.
I've tried to do this:
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64
def generate_keys():
modulus_lenght = 256 * 4
private_key = RSA.generate(modulus_lenght, Random.new().read)
public_key = private_key.publickey()
return private_key, public_key
def encrypt_private_key(a_message, private_key):
encryptor = PKCS1_OAEP.new(private_key)
encrypted_msg = encryptor.encrypt(a_message)
encoded_encrypted_msg = base64.b64encode(encrypted_msg)
return encoded_encrypted_msg
def decrypt_public_key(encoded_encrypted_msg, public_key):
encryptor = PKCS1_OAEP.new(public_key)
decoded_encrypted_msg = base64.b64decode(encoded_encrypted_msg)
decoded_decrypted_msg = encryptor.decrypt(decoded_encrypted_msg)
return decoded_decrypted_msg
private_key, public_key = generate_keys()
message = "Hello world"
encoded = encrypt_private_key(message, private_key)
decoded = decrypt_public_key(encoded, public_key)
print decoded
But it raises the next error: TypeError: This is not a private key.
Short answer
the code that you are using doesn't allow you to do that for security reasons
alternative code below
Long answer
I was curious about your problem and then I started to try to code
After a while I realized that if you run this snippet you will see that it correctly works:
#!/usr/bin/env python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64
def generate_keys():
modulus_length = 1024
key = RSA.generate(modulus_length)
#print (key.exportKey())
pub_key = key.publickey()
#print (pub_key.exportKey())
return key, pub_key
def encrypt_private_key(a_message, private_key):
encryptor = PKCS1_OAEP.new(private_key)
encrypted_msg = encryptor.encrypt(a_message)
print(encrypted_msg)
encoded_encrypted_msg = base64.b64encode(encrypted_msg)
print(encoded_encrypted_msg)
return encoded_encrypted_msg
def decrypt_public_key(encoded_encrypted_msg, public_key):
encryptor = PKCS1_OAEP.new(public_key)
decoded_encrypted_msg = base64.b64decode(encoded_encrypted_msg)
print(decoded_encrypted_msg)
decoded_decrypted_msg = encryptor.decrypt(decoded_encrypted_msg)
print(decoded_decrypted_msg)
#return decoded_decrypted_msg
def main():
private, public = generate_keys()
print (private)
message = b'Hello world'
encoded = encrypt_private_key(message, public)
decrypt_public_key(encoded, private)
if __name__== "__main__":
main()
but if you now change two of the final lines [i.e. the role of the keys] into:
encoded = encrypt_private_key(message, private)
decrypt_public_key(encoded, public)
and rerun the program you will get the TypeError: No private key
Let me quote from this great answer:
"As it turns out, PyCrypto is only trying to prevent you from mistaking one for the other here, OpenSSL or Ruby OpenSSL allow you for example to do both: public_encrypt/public_decrypt and private_encrypt/private_decrypt
[...]
Additional things need to be taken care of to make the result usable in practice. And that's why there is a dedicated signature package in PyCrypto - this effectively does what you described, but also additionally takes care of the things I mentioned"
Adapting this link I came to the following code that should solve your question:
# RSA helper class for pycrypto
# Copyright (c) Dennis Lee
# Date 21 Mar 2017
# Description:
# Python helper class to perform RSA encryption, decryption,
# signing, verifying signatures & keys generation
# Dependencies Packages:
# pycrypto
# Documentation:
# https://www.dlitz.net/software/pycrypto/api/2.6/
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
import rsa
hash = "SHA-256"
def newkeys(keysize):
random_generator = Random.new().read
key = RSA.generate(keysize, random_generator)
private, public = key, key.publickey()
return public, private
def importKey(externKey):
return RSA.importKey(externKey)
def getpublickey(priv_key):
return priv_key.publickey()
def encrypt(message, pub_key):
#RSA encryption protocol according to PKCS#1 OAEP
cipher = PKCS1_OAEP.new(pub_key)
return cipher.encrypt(message)
def decrypt(ciphertext, priv_key):
#RSA encryption protocol according to PKCS#1 OAEP
cipher = PKCS1_OAEP.new(priv_key)
return cipher.decrypt(ciphertext)
def sign(message, priv_key, hashAlg="SHA-256"):
global hash
hash = hashAlg
signer = PKCS1_v1_5.new(priv_key)
if (hash == "SHA-512"):
digest = SHA512.new()
elif (hash == "SHA-384"):
digest = SHA384.new()
elif (hash == "SHA-256"):
digest = SHA256.new()
elif (hash == "SHA-1"):
digest = SHA.new()
else:
digest = MD5.new()
digest.update(message)
return signer.sign(digest)
def verify(message, signature, pub_key):
signer = PKCS1_v1_5.new(pub_key)
if (hash == "SHA-512"):
digest = SHA512.new()
elif (hash == "SHA-384"):
digest = SHA384.new()
elif (hash == "SHA-256"):
digest = SHA256.new()
elif (hash == "SHA-1"):
digest = SHA.new()
else:
digest = MD5.new()
digest.update(message)
return signer.verify(digest, signature)
def main():
msg1 = b"Hello Tony, I am Jarvis!"
msg2 = b"Hello Toni, I am Jarvis!"
keysize = 2048
(public, private) = rsa.newkeys(keysize)
# https://docs.python.org/3/library/base64.html
# encodes the bytes-like object s
# returns bytes
encrypted = b64encode(rsa.encrypt(msg1, private))
# decodes the Base64 encoded bytes-like object or ASCII string s
# returns the decoded bytes
decrypted = rsa.decrypt(b64decode(encrypted), private)
signature = b64encode(rsa.sign(msg1, private, "SHA-512"))
verify = rsa.verify(msg1, b64decode(signature), public)
#print(private.exportKey('PEM'))
#print(public.exportKey('PEM'))
print("Encrypted: " + encrypted.decode('ascii'))
print("Decrypted: '%s'" % (decrypted))
print("Signature: " + signature.decode('ascii'))
print("Verify: %s" % verify)
rsa.verify(msg2, b64decode(signature), public)
if __name__== "__main__":
main()
Final notes:
the last prints have ascii because as stated here "In case of base64 however, all characters are valid ASCII characters"
in this case we are using the same key - the private one - both for encrypting and decrypting, so yes: we would end up to be symmetric but...
but - as stated here - "The public key is PUBLIC - it's something you would readily share and thus would be easily disseminated. There's no added value in that case compared to using a symmetric cipher and a shared key" plus "Conceptually, "encrypting" with the private key is more useful for signing a message whereas the "decryption" using the public key is used for verifying the message"
the same identical last principle is expressed in this answer - "Typically [...] we say sign with the private key and verify with the public key"
Looks like pycrypto has not been under active development since 2014 and support ended at python 3.3. cryptography seems like the standard now.
Using cryptography:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
password = b'thepassword'
key = rsa.generate_private_key(
backend=default_backend(),
public_exponent=65537,
key_size=2048
)
private_key = key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.BestAvailableEncryption(password)
)
public_key = key.public_key().public_bytes(
serialization.Encoding.OpenSSH,
serialization.PublicFormat.OpenSSH
)
What you are describing is called message signing and it uses private/public keys to verify that the message did come from the claimed sender and that it has not been tampered with en route. You don't have to "invent" these methods ...
https://medium.com/#securegns/implementing-asymmetric-encryption-to-secure-your-project-35368049cb5f
i try to encrypt the text with python and then i execute my code i get an error :
import base64
import boto3
from Crypto.Cipher import AES
PAD = lambda s: s + (32 - len(s) % 32) * ' '
def get_arn(aws_data):
return 'arn:aws:kms:{region}:{account_number}:key/{key_id}'.format(**aws_data)
def encrypt_data(aws_data, plaintext_message):
kms_client = boto3.client(
'kms',
region_name=aws_data['region'])
data_key = kms_client.generate_data_key(
KeyId=aws_data['key_id'],
KeySpec='AES_256')
cipher_text_blob = data_key.get('CiphertextBlob')
plaintext_key = data_key.get('Plaintext')
# Note, does not use IV or specify mode... for demo purposes only.
cypher = AES.new(plaintext_key, AES.MODE_ECB)
encrypted_data = base64.b64encode(cypher.encrypt(PAD(plaintext_message)))
# Need to preserve both of these data elements
return encrypted_data, cipher_text_blob
def main():
# Add your account number / region / KMS Key ID here.
aws_data = {
'region': 'eu-west-1',
'account_number': '701177775058',
'key_id': 'd67e033d-83ac-4b5e-93d4-aa6cdc3e292e',
}
# And your super secret message to envelope encrypt...
plaintext = PAD('Hello, World!')
# Store encrypted_data & cipher_text_blob in your persistent storage. You will need them both later.
encrypted_data, cipher_text_blob = encrypt_data(aws_data, plaintext)
print(encrypted_data)
if __name__ == '__main__':
main()
i Get : raise TypeError("Only byte strings can be passed to C code")
TypeError: Only byte strings can be passed to C code
Maybe whom know why? and how can i fix it ? please suggest!
Writing #Jeronimo's comment as an answer here, I was stuck with this same problem too and this helped.
Append a .encode("utf-8") to whatever you are passing to cypher.encrypt() function.
cypher.encrypt(PAD(plaintext_message).encode("utf-8"))
Note: this seems to be for python 3.x. For 2.x this same solution may not work.
In node i am using the following code to get proper decrypted message:
//npm install --save-dev crypto-js
var CryptoJS = require("crypto-js");
var esp8266_msg = 'IqszviDrXw5juapvVrQ2Eh/H3TqBsPkSOYY25hOQzJck+ZWIg2QsgBqYQv6lWHcdOclvVLOSOouk3PmGfIXv//cURM8UBJkKF83fPawwuxg=';
var esp8266_iv = 'Cqkbb7OxPGoXhk70DjGYjw==';
// The AES encryption/decryption key to be used.
var AESKey = '2B7E151628AED2A6ABF7158809CF4F3C';
var plain_iv = new Buffer( esp8266_iv , 'base64').toString('hex');
var iv = CryptoJS.enc.Hex.parse( plain_iv );
var key= CryptoJS.enc.Hex.parse( AESKey );
console.log("Let's ");
// Decrypt
var bytes = CryptoJS.AES.decrypt( esp8266_msg, key , { iv: iv} );
var plaintext = bytes.toString(CryptoJS.enc.Base64);
var decoded_b64msg = new Buffer(plaintext , 'base64').toString('ascii');
var decoded_msg = new Buffer( decoded_b64msg , 'base64').toString('ascii');
console.log("Decryptedage: ", decoded_msg);
But when i try to decrypt it in python i am not getting the proper decoded message.
esp8266_msg = 'IqszviDrXw5juapvVrQ2Eh/H3TqBsPkSOYY25hOQzJck+ZWIg2QsgBqYQv6lWHcdOclvVLOSOouk3PmGfIXv//cURM8UBJkKF83fPawwuxg='
esp8266_iv = 'Cqkbb7OxPGoXhk70DjGYjw=='
key = '2B7E151628AED2A6ABF7158809CF4F3C'
iv = base64.b64decode(esp8266_iv)
message = base64.b64decode(esp8266_msg)
dec = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
value = dec.decrypt(message)
print(value)
I am getting the decoded message:
"ルᄊ+#ÊZûᆪᄃn*ÿÒá×G1ᄄᄋì;$-#f゚ãᄚk-ìØܳã-トȒ~ヌ8ヘヘ_ᄂ ン?ᄂÑ:ÇäYムü'hユô<`
So i hope someone can show how it is done in python.
You forgot to decode the key from Hex and remove the padding.
Full code:
from Crypto.Cipher import AES
import base64
unpad = lambda s : s[:-ord(s[len(s)-1:])]
esp8266_msg = 'IqszviDrXw5juapvVrQ2Eh/H3TqBsPkSOYY25hOQzJck+ZWIg2QsgBqYQv6lWHcdOclvVLOSOouk3PmGfIXv//cURM8UBJkKF83fPawwuxg='
esp8266_iv = 'Cqkbb7OxPGoXhk70DjGYjw=='
key = '2B7E151628AED2A6ABF7158809CF4F3C'
iv = base64.b64decode(esp8266_iv)
message = base64.b64decode(esp8266_msg)
key = key.decode("hex")
dec = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
value = unpad(dec.decrypt(message))
print(value)
if len(value) % 4 is not 0:
value += (4 - len(value) % 4) * "="
value = base64.b64decode(value)
print(value)
Output:
eyJkYXRhIjp7InZhbHVlIjozMDB9LCAiU0VRTiI6NzAwICwgIm1zZyI6IklUIFdPUktTISEiIH0
'{"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!!" }'
Security considerations
The IV must be unpredictable (read: random). Don't use a static IV, because that makes the cipher deterministic and therefore not semantically secure. An attacker who observes ciphertexts can determine when the same message prefix was sent before. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.
It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.
So, in C# I have the following code:
public static void Main (string[] args)
{
publicKeyXml = "<Modulus>mFCubVhPGG+euHuVQbNObqod/Ji0kRe+oh2OCFR7aV09xYiOklqFQ8jgIgAHvyCcM1JowqfFeJ5jV9up0Lh0eIiv3FPRu14aQS35kMdBLMebSW2DNBkfVsOF3l498WWQS9/THIqIaxbqwRDUxba5btBLTN0/A2y6WWiXl05Xu1c=</Modulus><Exponent>AQAB</Exponent>";
RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider ();
rSACryptoServiceProvider.FromXmlString (publicKeyXml);
Console.WriteLine(Convert.ToBase64String (rSACryptoServiceProvider.Encrypt (Encoding.ASCII.GetBytes(args[0]), false)));
}
Which when I use to encrypt a message, it works just fine on a remote server (to which I have no source code for). However, when trying to do a similar thing in Python with PyCrypto, the remote server cannot decrypt.
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
KEY = RSA.importKey(open('login.key').read()) # Converted to standard format
KEY_CIPHER = PKCS1_v1_5.new(KEY)
testmsg = KEY_CIPHER.encrypt("test msg").encode('base64').replace('\n', '')
# send testmsg down a socket
# Response: {"info":"java.lang.IllegalArgumentException: Could not decrypt.","msg":"Fail"}
Any thoughts as to why this would be the case?
OK, in my case it was rather odd. The server side was expecting my stuff backwards. To solve, I simply did this:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
KEY = RSA.importKey(open('login.key').read()) # Converted to standard format
KEY_CIPHER = PKCS1_v1_5.new(KEY)
testmsg = KEY_CIPHER.encrypt("test msg").encode('base64').replace('\n', '')
testmsg = "".join(reversed([testmsg[i:i+2] for i in range(0, len(testmsg), 2)]))
Modulus = "mFCubVhPGG+euHuVQbNObqod/Ji0kRe+oh2OCFR7aV09xYiOklqFQ8jgIgAHvyCcM1JowqfFeJ5jV9up0Lh0eIiv3FPRu14aQS35kMdBLMebSW2DNBkfVsOF3l498WWQS9/THIqIaxbqwRDUxba5btBLTN0/A2y6WWiXl05Xu1c="
Exponent = "AQAB"
mod_raw = b64decode(Modulus)
exp_raw = b64decode(Exponent)
mod = int(mod_raw.encode('hex'), 16)
exp = int(exp_raw.encode('hex'), 16)
seq = asn1.DerSequence()
seq.append(mod)
seq.append(exp)
der = seq.encode()
keyPub = RSA.importKey(der)
print base64.b64encode(keyPub.encrypt('test msg', 0)[0])