I have this piece of code
import hashlib
from Cryptodome.Cipher import AES
decryption_key = hashlib.sha256(b"050746" + b"\x00\x00\x00\x03").digest()
iv = 16 * b '\x00'
aes = AES.new(decryption_key, AES.MODE_CBC, iv)
decrypted_nonce = aes.decrypt(encrypted_nonce)
I need help in understanding what this code is doing
I would be grateful for your help
Related
Basically, i am trying to encrypt 3 files in a folder with hybrid encryption, AES CBC. Successfully encrypted all the files, but having issues decrypting. The requirements for the task is:
2 seperate files, one for encrypting and one for decrypting
IV is 24 characters
IV can be hardcoded ,all files can use the same IV in or randomised (i randomised mine)
So far, only the last file is decrypted properly, the first 2 is giving me a ValueError error. However when i printed out the IV, it seems to be correct. Can someone advise me on this?
Encryption code
`#!/usr/bin/env python3
from base64 import b64encode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import glob
for item in glob.glob("*.txt"):
skey = get_random_bytes(16)
recipent_key = RSA.import_key(open("receiver.pem").read())
file_out = open("encrypted_key.bin", "wb")
cipher_rsa = PKCS1_OAEP.new(recipent_key)
enc_data = cipher_rsa.encrypt(skey)
file_out.write(enc_data)
file_out.close()
data_in = open(item, 'rb')
data = data_in.read()
data_in.close()
cipher = AES.new(skey, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(data, AES.block_size))
iv = b64encode(cipher.iv).decode('utf-8')
ct = b64encode(ct_bytes).decode('utf-8')
skey = b64encode(skey).decode('utf-8')
print(iv, ct, skey)
datain = (iv, ct)
Fileout = open(item,'w')
Fileout.writelines(datain)
Fileout.close()
`
Decryption code
`#!/usr/bin/env python3
from base64 import b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import os
import glob
for item in glob.glob("*.txt"):
file_in = open("encrypted_key.bin", "rb")
private_key = RSA.import_key(open("private.pem").read())
enc_data = file_in.read(private_key.size_in_bytes())
cipher_rsa = PKCS1_OAEP.new(private_key)
skey = cipher_rsa.decrypt(enc_data)
file_in.close()
in_file = open(item, "r")
data = in_file.read()
in_file.close()
print(data[0:24])
try:
iv = b64decode(data[0:24])
ct = b64decode(data[24:])
cipher = AES.new(skey, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), AES.block_size)
output = str(pt, 'utf-8')
print("the message was: ", output)
Fileout = open(item,'w')
Fileout.writelines(output)
Fileout.close()
except ValueError:
print("Incorrect decryption")
except KeyError:
print("incorrect key")
`
please send help :"")
EDIT: i realised, every round my loop goes, my key also randomise. that's the problem, i solved it :")
I am fairly new to AES en/decrypting so bare with me.
Using the Crypto (Cryptodome) Library, I am trying to decrypt a message with a known key and a known iv as String.
from base64 import b64decode
from Crypto.Cipher import AES
from Crypto.Util import Padding
key = "some_key_as_string" #
key = base64.b64decode(key)
key = key.rjust(16, "0")
iv = "some_iv_as_string"
iv = b64decode(iv)
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = b'Test_ciphertext'
ct = ct.ljust(16, "0")
message = Padding.unpad(cipher.decrypt(ct), AES.block_size)
However this gives me an Error called 'Padding not correct' which I am not able to remove by myself.
The keysize should be 256 bit, not sure if I included this with the encoding.
Can you tell me what I am missing here?
Edit: I should add that rjust only worked for me when I encoded the "0".
So instead of
key = key.rjust(16, "0")
I used
r = str.encode("0")
key = key.rjust(16, r)
as well for the ct
I'm struggling to find the issue within the code:
I've txt file on my desktop that i want to encrypt, then decrypt.
I'm using AES CBC as my encryption method.
Assume the file contain the following string:
bla bla top secret!!
I'm able to encrypt it successfully with the following line: modify(r"C:\Users\XXXXX\Desktop\TEST.txt", encrypt_file) output: W¢ìPY#Šÿb[l®«fì]ßQzýµá˺cØäûE
Then I'm trying to decrypt it with the following line modify(r"C:\Users\XXXXX\Desktop\TEST.txt", decrypt_file)
I'm getting the following exception: ValueError: Padding is incorrect.
If I remove the unpad function i can see the text is partical unencrypted as follow: bla bla top secrv€\Èu¢Þ#xH‹AÄ
I can't find whats wrong here.
Any help will be appreciated.
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
HARD_CODED_KEY = b"SOME KEY"
iv = b'1234567812345678'
def encrypt_file(file, key, blocksize=16):
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(file, blocksize))
return ciphertext
def decrypt_file(file, key, blocksize=16):
cipher = AES.new(key, AES.MODE_CBC, iv)
cleartext = unpad(cipher.decrypt(file), blocksize)
return cleartext
def modify(file, crypt, blocksize=16):
with open(file, "r+b") as f:
plaintext = f.read(blocksize)
while plaintext:
ciphertext = crypt(plaintext, HARD_CODED_KEY, blocksize)
f.seek(-len(plaintext), 1) # go back to the same point before the read
f.write(ciphertext)
plaintext = f.read(blocksize)
I have a video file which I am trying decrypt . The key is stored in a file. For some reasons it's not working and giving me this error "TypeError: Object type <class 'str'> cannot be passed to C code"
DecryptFile function I wrote takes 3 parameters
input file name ("input.ts")
output file name ("output.ts")
key for decryption ("k.kjs").
What I want it to do is decrypt the file with the key provided and save it with output name I gave . I am using Python 3.7.1
from Crypto.Cipher import AES
import os
def DecryptFile(infile,outfile,keyfile):
data = open(infile,"rb").read()
key = open(keyfile,"rb").read()
print(type(data))
iv = '\x00'*15 + chr(1)
aes_crypter = AES.new(key, AES.MODE_CBC, iv)
a = aes_crypter.decrypt(data)
with open(outfile, 'wb') as out_file:
out_file.write(a)
DecryptFile("input.ts","output.ts","k.kjs")
According to [ReadTheDocs.PyCryptodome]: AES - Crypto.Cipher.AES.new(key, mode, *args, **kwargs), iv should be:
Of type bytes
A kwarg
To get past this error, modify 2 lines of your code:
# ...
iv = b'\x00' * 15 + b'\x01'
aes_crypter = AES.new(key, AES.MODE_CBC, iv=iv)
# ...
Using https://core.telegram.org/passport#decrypting-data, I've come up with the following function:
import hashlib
from base64 import b64decode
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
def decode_credentials(credentials):
data_encrypted = b64decode(credentials['data'])
credentials_hash = b64decode(credentials['hash'])
secret_encrypted = b64decode(credentials['secret'])
with open(f"private.key", "r") as f:
private_key = RSA.importKey(f.read())
secret_decrypted = private_key.decrypt(secret_encrypted)
secret_hash = hashlib.sha512(secret_decrypted + credentials_hash).digest()
aes_key = secret_hash[:32]
aes_iv = secret_hash[32:48]
aes = AES.new(aes_key, AES.MODE_CBC, aes_iv)
data_decrypted = aes.decrypt(data_encrypted)
data_decrypted_hash = hashlib.sha256(data_decrypted).digest()
if data_decrypted_hash != credentials_hash:
raise Exception("HASH MISMATCH")
return data_decrypted[data_decrypted[0]:]
Following code always raises HASH MISMATCH for me, hence the question: What's wrong with the code?
Has anybody come up with the working solution that they can share?
The problem was in this lines:
with open(f"private.key", "r") as f:
private_key = RSA.importKey(f.read())
secret_decrypted = private_key.decrypt(secret_encrypted)
I don't know the difference, but the correct is:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.hashes import SHA1
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP
with open(f"private.key", "rb") as f:
private_key = serialization.load_pem_private_key(
f.read(),
password=None,
backend=default_backend(),
)
secret_decrypted = private_key.decrypt(
secret_encrypted,
OAEP(
mgf=MGF1(algorithm=SHA1(), ),
algorithm=SHA1(),
label=None,
)
)
Found the solution at https://github.com/python-telegram-bot/python-telegram-bot/commit/a09394b218d3ae05dc1a1f74e782c701283fb82b#diff-eaefd62d25b87433b035868713d3437aR39.
Still would appreciate if someone would have explained me my mistake.