So I've just started experimenting with Pycrypto and wanted to encrypt and decrypt a message, but this code I put together produced some errors.
Here they are:
enc_data = public_key.encrypt
TypeError: unsupported operand type(s) for pow(): 'str', 'int','int'
ciphertext = cipher.encrypt('Bob')
Traceback (most recent call last):
line 22, in
ciphertext = cipher.encrypt('Bob')
File
"C:\Anaconda3\lib\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 50,
in encrypt
db = lHash + ps + bchr(0x01) + message
TypeError: can't concat bytes to str
The code:
import Crypto
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto import Random
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
public_key = key.publickey()
enc_data = public_key.encrypt('Bob', 32)
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt('Bob')
The two commands which are meant to encrypt 'Bob' produce these errors, and yes I now that the first way isn't very secure.
In Python 3 there is a difference between strings and bytes. PyCrypto works on bytes, so you need to give it bytes, but "Bob" is a string. You can convert a string a to bytes with a.encode(), which uses a default encoding. If you have another encoding in mind, then you need to specify it.
You can also mark a literal string as bytes by prefixing it with a b. Example: b"Bob".
Related
I have a column ID in oracle which was encrypted like this :
select CAST(DBMS_CRYPTO.encrypt(UTL_RAW.CAST_TO_RAW('SECRETSTRING'), 4356 , 'SOMEKEY') AS VARCHAR2(100 char)) as temp from dual;
Now i am reading this table in python using pandas. Now I want to decrypt this in python.
I tried several ways, but I am unable decrypt it
Following are the things which I tried:
1)
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
def decrypty(enc):
unpad = lambda s: s[:-ord(s[-1:])]
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(__key__, AES.MODE_CFB, iv)
return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))
this threw an error :
binascii.Error: Invalid base64-encoded string: number of data characters (1) cannot be 1 more than a multiple of 4
2)
from Crypto.Cipher import AES
from Crypto import Random
def decrypt(key, enc):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16:]), block_size=16)
This threw an error related to padding.
Basically if something is encrypted in DB with a key, using the same key I am unable to decrypt it in python. any pointers ?
If the database did the encryption I for sure would advice to use the database again for the decryption too, if possible at all.
If it is not possible to use the database for both the encryption and decryption, put them both in the python code.
Keep the code for en/de-cryption close and make the use the same bugs. Also: what is the reason for the encryption? Maybe that data is not meant to be readable for your application.
I'm trying to get some help regarding encoding with Triple DES in python.
I want to have 2 functions: encode/decode
and I want it to operate as it does on the site: https://www.devglan.com/online-tools/triple-des-encrypt-decrypt, with the base64 output format.
because when I decode that base64 msg I get some random chars and that's what I want.
I've tried doing that with pycryptodome but it gives me a byte output.
what I've tried:
from Crypto.Cipher import DES3
from Crypto.Random import get_random_bytes
# Avoid Option 3
while True:
try:
key = DES3.adjust_key_parity(get_random_bytes(24))
break
except ValueError:
pass
cipher = DES3.new(key, DES3.MODE_ECB)
plaintext = b'We are no longer the knights who say ni!'
msg = cipher.iv + cipher.encrypt(plaintext)
How would I be able to do that? any help would be appreciated!
Or maybe do you know what most programs use to encrypt their files? for example word.
I have been working on a program that allows you to enter any text you want and it will return the hashed result in sha256. However i am receiving an error on line 4 The whole error message:
Traceback (most recent call last):
File "main.py", line 4, in <module>
hash_object = hashlib.sha256(password_sign_up)
TypeError: Unicode-objects must be encoded before hashing
The code:
import hashlib
password_sign_up = input("Enter your desired password: ")
hash_object = hashlib.sha256(password_sign_up)
hex_dig = hash_object.hexdigest()
print(hex_dig)
You have to use .encode('utf-8') for your password.
In python 2x, the default encoding for any string is unicode. But in 3x, you will have to encode it to your choice of encoding. e.g. utf-32, utf-8 etc.
Try this: hash_object = hashlib.sha256(password_sign_up.encode('utf-8'))
You're taking the result of the input() function (which returns a str object) and putting it directly into sha256(). The sha256() function requires its parameter to be a bytes object.
You can convert a string to a bytes with:
myNewBytesObject = password_sign_up.encode('utf-8')
I am working on a little sideproject in Python 3.
My current problem is around AES-based decryption of a file. The content of the file (text) is symmetrical encrypted with AES.
I have imported PyCrypto: https://www.dlitz.net/software/pycrypto/api/current/
The docs specificy only little regarding the symmetrical key:
key (byte string) - The secret key to use in the symmetric cipher. It must be 16 (AES-128), 24 (AES-192), or 32 (AES-256) bytes long.
I have the key and looks like:
0xB0,0x0D,0xDF,0x9D,... (for security reasons I don't report the complete key here)
Anyway, my first question:
What kind of string is that? It looks like ASCII, but I lack deep knowledge about Encodings. Do I need any kind of transformation / decoding?
I wrote a little program to open a file and decrypt it. But PyCrypto throws an error and I spent now 5 hours with trial and error without any progress:
ValueError: AES key must be either 16, 24, or 32 bytes long
So I tried both:
initializing as string:
key = "0xB0,0x0D,0xDF,0x9D,..."
and 2. as byte-string:
key = b"0xB0,0x0D,0xDF,0x9D,..."
No effect.
Any comments or ideas?
Best Regards,
AFX
What you have is a hex string. For example, if you had this:
0x0F, 0x10, 0x1A
Then this, condensed down to be an actual hex string, is:
0F101A
Which, as raw bytes, is:
15, 16, 26
You just need to convert it to a byte array first. Have a look at binascii.unhexlify.
I wanted to provide the solution that worked out for me:
First, get the basics:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = 'insert-key-here'
Now, I build a method to decrypt:
def decrypt_file(key, in_filename, out_filename=None):
""" Decrypts a file using AES (CBC mode) with the
given key.
"""
backend = default_backend()
with open(in_filename, mode="r+b") as infile:
iv = infile.read(16) #Calling .read() will move the iterator exactly as many positions
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
decryptor = cipher.decryptor()
with open(out_filename, mode="w+b") as outfile:
cipher_text = infile.read() #Only the first 16byte are the iv, the rest is the cipher-text
outfile.write(decryptor.update(cipher_text) + decryptor.finalize())
Here is the key: I had to transform the key to byte-string first
#Transform key to byte-string
key_int = [int(x,0) for x in key.split(',')]
decrypt_byte_key = b''
for x in key_int:
decrypt_byte_key += x.to_bytes(1, 'little')
Finally, you can run it on your file:
decrypt_file(decrypt_byte_key, "input.enc", "output.txt")
Have fun.
I have a function written in c# that you can pass an ascii string as the key, and the encrypted string from a database and decode the data.
I've verified that the code works by writing a simple c# program to decode the data. The code snippet converts the key string to bytes and MD5 hashes it.
C# Code Snippet, omitting some code that converted the byteHash to an ascii string for output in the compiled program
key = "joetest"
byte[] byteHash = cryptoServiceProvider.ComputeHash(Encoding.ASCII.GetBytes(key));
byteHash = "f2fc0f481787cc4cbb15f7ded4412fe4"
I run the following commands and Python3 and get the same byteHash
key = "joetest"
encoded_key = key.encode("ascii")
m = hashlib.md5()
m.update(encoded_key)
hex_key = m.hexdigest()
print(hex_key)
hex_key = "f2fc0f481787cc4cbb15f7ded4412fe4"
I've tried encoding 'hex_key' as binary.
My issue is I'm trying to pass hex_key into 2 different python3 crypto programs. Cryptodome and pyDes. Both tell me that i'm passing in an invalid key.
The C# code that uses byteHash is as follows
tripleDesCryptoServiceProvider.Key = byteHash;
tripleDesCryptoServiceProvider.Mode = CipherMode.ECB;
byte[] byteBuff = Convert.FromBase64String(encryptedString);
string strDecrypted = Encoding.UTF8.GetString(tripleDesCryptoServiceProvider.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
This all works, i was able to decrypt data when i passed in the encrypted string into this function.
Using pyDes i'm using this code
from pyDes import *
import base64
import hashlib
my_data = "fK/jw6/25y0="
#my_data is the word 'test' encrypted with the key of 'joetest'
#This code takes the key string and converts it to an MD5 hash
my_key = "joetest"
encoded_key = my_key.encode("ascii") #Encode the data as binary data
m = hashlib.md5()
m.update(encoded_key)
hex_key = m.hexdigest() #Convert the key to an MD5 hash
encoded_hex_key = hex_key.encode() #Make the MD5 key a binary key
#Convert the Base64 encoded string to the format that the decoder wants
decoded_data = base64.b64decode(my_data)
k = triple_des(encoded_hex_key, ECB, padmode=PAD_PKCS5)
my_out = k.decrypt(decoded_data)
print("my_out")
print(my_out)
exit()
The error i'm getting is:
(3destest) c:\3des-test\3destest>joe3des_test3.py
Traceback (most recent call last):
File "C:\3des-test\3destest\joe3des_test3.py", line 20, in <module>
k = triple_des(encoded_hex_key, ECB, padmode=PAD_PKCS5)
File "c:\3des-test\3destest\lib\site-packages\pyDes.py", line 710, in __init__
self.setKey(key)
File "c:\3des-test\3destest\lib\site-packages\pyDes.py", line 719, in setKey
raise ValueError("Invalid triple DES key size. Key must be either 16 or 24 bytes long")
ValueError: Invalid triple DES key size. Key must be either 16 or 24 bytes long
Using pyCryptodome, i've tried this code
from Cryptodome.Cipher import DES3
import base64
import hashlib
# Converts the key string to an MD5 hash
key = "joetest"
encoded_key = key.encode("ascii")
m = hashlib.md5()
m.update(encoded_key)
hex_key = m.hexdigest()
#Decodes the string to binary digits
encryptedString = base64.b64decode("fK/jw6/25y0=")
#Create the cipher to decrypt the data
cipher = DES3.new(hex_key, DES3.MODE_ECB)
decryptedString = cipher.decrypt(encryptedString)
And i get this error
Traceback (most recent call last):
File "C:\3des-test\3destest\joe3des_test2.py", line 16, in <module>
cipher = DES3.new(hex_key, DES3.MODE_ECB)
File "c:\3des-test\3destest\lib\site-packages\Cryptodome\Cipher\DES3.py", line 174, in new
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
File "c:\3des-test\3destest\lib\site-packages\Cryptodome\Cipher\__init__.py", line 55, in _create_cipher
return modes[mode](factory, **kwargs)
File "c:\3des-test\3destest\lib\site-packages\Cryptodome\Cipher\_mode_ecb.py", line 175, in _create_ecb_cipher
cipher_state = factory._create_base_cipher(kwargs)
File "c:\3des-test\3destest\lib\site-packages\Cryptodome\Cipher\DES3.py", line 99, in _create_base_cipher
key = adjust_key_parity(key_in)
File "c:\3des-test\3destest\lib\site-packages\Cryptodome\Cipher\DES3.py", line 80, in adjust_key_parity
raise ValueError("Not a valid TDES key")
ValueError: Not a valid TDES key
My python MD5 hash is 32 hex characters long. Assuming my math is right, 32 * 4 is 128 bits. And the error is saying it must be 16 or 24 bytes long. 16 * 8 is also 128 bits. So the byte string value i'm passing it should be correct. I think I'm missing something, but can't seem to figure it out.
Update 2-Jan-2018
Based on answer below here's a copy of the code that I used to confirm this will decrypt the data from the DB.
from pyDes import *
import base64
import hashlib
#my_data is the word 'test' encrypted with the key of 'joetest'
my_data = "fK/jw6/25y0="
#This code takes the key string and converts it to an MD5 hash
my_key = "joetest"
encoded_key = my_key.encode("ascii")
m = hashlib.md5()
m.update(encoded_key)
digest_key = m.digest()
#Convert the Base64 encoded string to the format that the decoder wants
decoded_data = base64.b64decode(my_data)
k = triple_des(digest_key, ECB)
my_out = k.decrypt(decoded_data)
print("my_out")
print(my_out.decode("ascii"))
The disconnect here is that pyDes.triple_des() is looking for a binary key, but what you are giving it is an encoded string with the hex representation of that key. Since pyDes doesn't expect the hex string, try just giving it the raw digest instead (i.e. m.digest() instead of m.hexdigest()). No need to .encode() it either.
TripleDES, by definition, is meant to use a 24 byte key, e.g. 192 bits. Implementations that accept less than that actually reuse key data.
In C#, TripleDES with a 128-bit key reuses the first 64 bits to create a key that is 192 bits in length.
With that in mind, try using the following 192-bit key instead:
f2fc0f481787cc4cbb15f7ded4412fe4f2fc0f481787cc4c
If this works, which I expect it will, you'll just need to modify the code to copy the first 64 bits to the end.
The Error
line 80, in adjust_key_parity
raise ValueError("Not a valid TDES key")
Comes from the following code in pyCryptodome:
79 if len(key_in) not in key_size:
80 raise ValueError("Not a valid TDES key")
..
186 # Size of a key (in bytes)
187 key_size = (16, 24)
Your key is 16 bytes long, but in hex form the key you pass have size 32.