How to achieve C# RSACryptoServiceProvider-like encryption in Python? - python

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])

Related

porting aes encryption function from php to python

we used the following function in PHP to encrypt some data:
function aes_encrypt_turnover($reg_id,$receipt_nr,$data,$key_base64) {
$method = 'AES-256-CTR';
$library = 'OpenSSL';
$tc_bin = pack("J",$data);
$key_bin = base64_decode($key_base64);
$iv_bin = substr(hash('sha256', $reg_id . $receipt_nr, true), 0, 16);
$tc_encrypted_base64 = openssl_encrypt($tc_bin, $method, $key_bin, false, $iv_bin);
return $tc_encrypted_base64;
}
now we try to translate this to python but without success. with same testdata the python Version returns not the same encryption values.
Our python version is als follows:
import base64
import struct
import hashlib
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto.Util.number import bytes_to_long
data = 12345
reg_id = "DEMO_DATA"
receipt_nr = 843234
key_base64 = 'RCsRmHn5tkLQrRpiZq2ucwPpwvHJLiMgLvwrwEImddI='
tc_bin = struct.pack('>I', data)
key_bin = base64.b64decode(key_base64)
hash_string = str(reg_id) + str(receipt_nr)
iv_bin = hashlib.sha256(hash_string.encode()).digest()[:16]
counter = Counter.new(128, initial_value = bytes_to_long(iv_bin))
cipher = AES.new(key_bin, AES.MODE_CTR, counter=counter)
encrypted = cipher.encrypt(tc_bin)
encrypted_b64 = base64.b64encode(encrypted)
maybe anybody can tell whats wrong in our python version

How can I encrypt with a RSA private key in python?

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

Using AES Encrypt get raise TypeError("Only byte strings can be passed to C code")

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.

How to decrypt an RSA encrypted file in Python [duplicate]

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);

Encrypting Datas using python

Below is the code snippet from vb.net. I want to convert it to python. I used hashlib, hmac and also pyDes but none produced the same result as by the vb program. Any Suggestions.? This is my first time dealing with encryption. Please help me sort this problem..
code:
Imports Microsoft.VisualBasic.CompilerServices
Imports System
Imports System.Diagnostics
Imports System.Security.Cryptography
Imports System.Text
Namespace _Cargo
Public Class Crypto
Private Shared DES As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
Private Shared MD5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
<DebuggerNonUserCode()>
Public Sub New()
End Sub
Public Shared Function MD5Hash(value As String) As Byte()
Return Crypto.MD5.ComputeHash(Encoding.ASCII.GetBytes(value))
End Function
Public Shared Function Encrypt(stringToEncrypt As String) As String
Crypto.DES.Key = Crypto.MD5Hash("L6#F&,q2$xLx")
Crypto.DES.Mode = CipherMode.ECB
Dim bytes As Byte() = Encoding.ASCII.GetBytes(stringToEncrypt)
Return Convert.ToBase64String(Crypto.DES.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length))
End Function
Public Shared Function Decrypt(encryptedString As String) As String
Dim result As String
Try
Crypto.DES.Key = Crypto.MD5Hash("L6#F&,q2$xLx")
Crypto.DES.Mode = CipherMode.ECB
Dim array As Byte() = Convert.FromBase64String(encryptedString)
result = Encoding.ASCII.GetString(Crypto.DES.CreateDecryptor().TransformFinalBlock(array, 0, array.Length))
Return result
Catch expr_4D As Exception
ProjectData.SetProjectError(expr_4D)
ProjectData.ClearProjectError()
End Try
result = Nothing
Return result
End Function
End Class
End Namespace
Check out the following code snippet
SIGNATURE OF THE DES
pyDes.des(key, [mode], [IV], [pad], [padmode])
from pyDes import *
data = "Please encrypt my data"
k = des("DESCRYPT", ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
print "Encrypted: %r" % d
print "Decrypted: %r" % k.decrypt(d)
Update
I have converted vb.net code to python and it's working fine
from pyDes import *
import hashlib
import base64
key = hashlib.md5("L6#F&,q2$xLx").digest()
data = "I love security"
k = triple_des(key, ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
base64Encrypted= base64.b64encode(d)
print "Encrypted: %r" % d
base64Decrypted= base64.b64decode(base64Encrypted)
print "Decrypted: %r" % k.decrypt(base64Decrypted)
You can use the Crypto library, very handy for all cryptography related stuff
from Crypto.Cipher import DES
from Crypto.Hash import MD5
from Crypto import Random
def encrypt(string, key):
hash = MD5.new(key).digest()
iv = Random.new().read(DES.block_size)
cipher = DES.new(hash, DES.MODE_ECB, iv)
return iv + cipher.encrypt(string)

Categories

Resources