Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23390

Python RSA Encryption - Using Private Key to Encrypt and Public to Decrypt

$
0
0

I am working on creating a license key validation server that unlocks a piece of software. The C++ framework I am using, for the client, has built in functionality that allows the server to send back a POST response with an RSA encrypted message containing data that states the license key is valid for the machine sending the POST.

The way the framework handles response encryption is by housing the public key in the client software and the private key on the server doing a reverse version of typical RSA encryption. I understand that this is not necessarily secure but for this use case it does not matter. I have also read that this may be called signing rather than encrypting but I am unsure.

I am writing the server in python and am therefore wanting to do reverse RSA encyption using python libraries.

I have tried a couple different things, mainly using the pycryptodome library but have been unable to get a successful run. Below I have an encrypt and decrypt function I found but it throws an incorrect padding error when attempting to use b64decode. I tried researching how to fix the padding but was unsuccesful.

I have provided sample private and public keys, as well as a testMsg that the framework spit out when encrypting with the private key.

from http.server import BaseHTTPRequestHandler, HTTPServerimport timeimport sqlite3from random import choicefrom string import ascii_uppercase, digitsfrom Crypto.PublicKey import RSAfrom Crypto.Cipher import PKCS1_OAEPimport base64hostName = "localhost"serverPort = 8080serverVersion = "v0.2.3"privateRSAKey = "279808e40cef4350640026c8739e7201826d002cec7e260f3d16d0cf786842f1,602815978d207ee7ce4982c23d5c39729da90af57b850863165936256e3b7227"publick = "11,602815978d207ee7ce4982c23d5c39729da90af57b850863165936256e3b7227"testMsg = "#62a29db7f09c76d2b28a2313911cbaad1a89b235ab52d05f704a9110c517b1db90d824d88188d08cb2b9002ba2f64e0bdf78a393a7cfc3f2bbad0e43f8167184975183357c2a73e1537fb0fe47e74586d553bc68e0e4e03d6b1ef67d03e57ea794f0029db1d6b2ef048db4e6b019d198e2876e925dc3036bbcca85369f67435884a9ff60a28a3e6131056805b58f804e74a8a224453b5099f831c57a16f87e"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_msgdef 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)def verify_product(product):    if product == "Test":        return True    else:        return Falsedef verify_email(email):    if email == "test@email.com":        return True    else:        return Falsedef verify_license_key(licenseKey):    sql_connection = sqlite3.connect("SynergyLicenseKey.db");    cur = sql_connection.cursor()    data = cur.execute(f"SELECT * FROM LICENSEKEYS WHERE LicenseKey = '{licenseKey}'")    # if rows return it is a valid license key    for row in data:        sql_connection.close()        return True    sql_connection.close()    return Falsedef generate_license_key():    # Using random.choice to select characters from uppercase letters and digits    key = ''.join([choice(ascii_uppercase + digits) for _ in range(7)]) +'-'+ \''.join([choice(ascii_uppercase + digits) for _ in range(7)]) +'-'+ \''.join([choice(ascii_uppercase + digits) for _ in range(7)])    return keyclass testServer(BaseHTTPRequestHandler):    def do_GET(self):        self.send_response(200)    def do_POST(self):        content_length = int(self.headers['Content-Length'])        post_data = self.rfile.read(content_length)        request_data = post_data.decode('utf-8').split('&')        print(request_data)        if verify_product(request_data[0][8:]) and verify_email(request_data[1][6:]):            response = bytes(f'<MESSAGE message="Success! Valid License Key"><KEY>{test}</KEY></MESSAGE>', "utf-8")        else:            response = bytes('<ERROR error="Invalid License Key"></ERROR>', "utf-8")        self.send_response(200)        self.send_header("Content-Length", str(len(response)))        self.end_headers()        self.wfile.write(response)if __name__ == "__main__":            webServer = HTTPServer((hostName, serverPort), testServer)    print("Server - " + serverVersion +" - http://%s:%s" % (hostName, serverPort))    decrypt_public_key(testMsg, publick)    try:        webServer.serve_forever()    except KeyboardInterrupt:        pass    webServer.server_close()    print("Server stopped.")

Viewing all articles
Browse latest Browse all 23390

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>