I am having troubling encrypting a Python list element by element. Each element is this list is a string. Here is my code:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
#### Generate the public and private keys ####
key = RSA.generate(1024, e=65537)
priv_key = key.exportKey("PEM")
public_key = key.publickey().exportKey("PEM")
#Let's get some information!!
firstName = input("Enter your First Name: ")
lastName = input("Enter your Last Name: ")
id = input("Enter your Personal ID: ")
#list = [first_name, last_name, id]
list = ['Bob', 'Dylan', '15898']
listEncrypted = []
#Now let's encrypt the list with a public key
list_length = len(list)
for index in range(list_length-1):
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(list[index])
listEncrypted.append(ciphertext)
The Error I am getting is:
File "C:\Users\moo\.spyder-py3\RSA.py", line 122, in <module>
ciphertext = cipher.encrypt(list[index])
File "C:\Users\moo\anaconda3\lib\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 107, in encrypt
modBits = Crypto.Util.number.size(self._key.n)
AttributeError: 'bytes' object has no attribute 'n'
How do I encrypt the list using the user's input? Please help...
Cryptographic keys are usually generated once and saved to files in one of several formats. Its also common for the private key to be further protected with a password or stored in a secure place in your file system.
To encrypt with the public key you normally get the key from some external source, but for this test code we use the test key we generated.
I'm not sure about Crypto versions, but mine uses camelCase for method names, although lower_case is used in other examples.
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
#### Generate the public and private keys for test ####
key = RSA.generate(1024, e=65537)
priv_key = key.exportKey("PEM")
public_key = key.publickey().exportKey("PEM")
text = "This is secret"
#Now let's encrypt the list with a public key
key = RSA.importKey(public_key)
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(text.encode("utf-8"))
print(text, ciphertext)
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
Writing a Python script, I would like to know if it is possible to bind to an LDAP server without writing the password in plaintext, like in this example:
import ldap
l = ldap.open("myserver")
username = "cn=Manager, o=mydomain.com"
## I don't want to write the password here in plaintext
password = "secret"
l.simple_bind(username, password)
Example Function for decrypting a file called '.credentials'. This would of course have a seporate script to encrypt the credentials to a file in the first place prior to trying to use it.
So you would call this function:
username, password = decrypt()
l.simple_bind(username, password)
from Crypto.Cipher import AES
import base64
from local_logging import info
def decrypt(dir_path):
#Read '.credentials' file and return unencrypted credentials (user_decoded, pass_decoded)
lines = [line.rstrip('\n') for line in open(dir_path + '/.credentials')]
user_encoded = lines[0]
user_secret = lines[1]
pass_encoded = lines[2]
pass_secret = lines[3]
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length. This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
# create a cipher object using the random secret
user_cipher = AES.new(user_secret)
pass_cipher = AES.new(pass_secret)
# decode the encoded string
user_decoded = DecodeAES(user_cipher, user_encoded)
pass_decoded = DecodeAES(pass_cipher, pass_encoded)
return (user_decoded, pass_decoded)
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);
I've generated a public and private key with pycrypto, and I save them to a file using export key:
from Crypto.PublicKey import RSA
bits=2048
new_key = RSA.generate(bits, e=65537)
prv = open('keymac.pem','w')
prv.write(new_key.exportKey('PEM'))
prv.close()
pub = open('pubmac.pem', 'w')
pub.write(new_key.publickey().exportKey('PEM'))
pub.close()
I use the public key to encrypt a file (following http://insiderattack.blogspot.com/2014/07/encrypted-file-transfer-utility-in.html#comment-form)
When I read the file to decrypt it, I get "Ciphertext with incorrect length."
I added a try-except block around the decryption code on Deepal Jayasekara example:
try:
encryptedonetimekey = filetodecrypt.read(512)
privatekey = open("keymac.pem", 'r').read()
rsaofprivatekey = RSA.importKey(privatekey)
pkcs1ofprivatekey = PKCS1_OAEP.new(rsaofprivatekey)
aesonetimekey = pkcs1ofprivatekey.decrypt(encryptedonetimekey)
except Exception as decrypprivkeyerr:
print "Decryption of the one time key using the private key failed!!"
print "Key error == %s" %decrypprivkeyerr
raise Exception("Decryption using Private key failed error = %s" %decrypprivkeyerr)
Am I missing something? Should I save the private key differently? Am I not reading the private key correctly?
This doesnt answer your question directly but it may give you some clues to the problem. Im using two functions for encrypting content to a file rather than encrypting a file directly. One for encrypting (in my case username and password) to a file then another to decrypt that data to use as needed.
Note the need for the padding
Creat Encrypted Content In File:
from Crypto.Cipher import AES
import base64
import os
import argparse
parser = argparse.ArgumentParser(description='Arguments used to generate new credentials file, Use: -u for username, -p for password')
parser.add_argument('-u', help='Specify username', required=True)
parser.add_argument('-p', help='Specify password', required=True)
parser.add_argument('-b', help='Specify debug', required=False, action='store_true')
args = vars(parser.parse_args())
def encrypt(username, password):
#Encrypt Credentials To '.creds' file, including 'secret' for username and password
dir_path = os.path.dirname(os.path.realpath(__file__))
# the block size for the cipher object; must be 16 per FIPS-197
BLOCK_SIZE = 16
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length. This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'
# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
# generate a random secret key
user_secret = os.urandom(BLOCK_SIZE)
pass_secret = os.urandom(BLOCK_SIZE)
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
# create a cipher object using the random secret
user_cipher = AES.new(user_secret)
pass_cipher = AES.new(pass_secret)
# encode a string
user_encoded = EncodeAES(user_cipher, username)
pass_encoded = EncodeAES(pass_cipher, password)
try:
with open('.creds', 'w') as filename:
filename.write(user_encoded + '\n')
filename.write(user_secret + '\n')
filename.write(pass_encoded + '\n')
filename.write(pass_secret + '\n')
filename.close()
print '\nFile Written To: ', dir_path + '/.creds'
except Exception, e:
print e
if args['b']:
print((user_encoded, user_secret), (pass_encoded, pass_secret))
username = args['u']
password = args['p']
encrypt(username, password)
Decrypt The Data
def decrypt(dir_path, filename):
#Read '.creds' file and return unencrypted credentials (user_decoded, pass_decoded)
lines = [line.rstrip('\n') for line in open(dir_path + filename)]
user_encoded = lines[0]
user_secret = lines[1]
pass_encoded = lines[2]
pass_secret = lines[3]
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length. This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
# create a cipher object using the random secret
user_cipher = AES.new(user_secret)
pass_cipher = AES.new(pass_secret)
# decode the encoded string
user_decoded = DecodeAES(user_cipher, user_encoded)
pass_decoded = DecodeAES(pass_cipher, pass_encoded)
return (user_decoded, pass_decoded)
The error message, "Ciphertext with incorrect length", has told us all. That means,
cipher text exceeded the limit length which can be calculated by (length of key,
1024.2048..)/8. to solve this problem, you can separate the cipher text and decrypt
them within a loop, then assemble all the decrypted byte string. My code in Python 3.6 for reference:
# 1024/8
default_length = 128
encrypt_str = str(data["content"])
sign_str = str(data["sign"])
try:
rsa_private_key = RSA.importKey(private_key)
encrypt_byte = base64.b64decode(encrypt_str.encode())
length = len(encrypt_byte)
cipher = PKCS115_Cipher(rsa_private_key)
if length < default_length:
decrypt_byte = cipher.decrypt(encrypt_byte, 'failure')
else:
offset = 0
res = []
while length - offset > 0:
if length - offset > default_length:
res.append(cipher.decrypt(encrypt_byte[offset: offset +
default_length], 'failure'))
else:
res.append(cipher.decrypt(encrypt_byte[offset:], 'failure'))
offset += default_length
decrypt_byte = b''.join(res)
decrypted = decrypt_byte.decode()