Decryption issue with private key and passphrase - python

can you people please help with below problem.
I am new t encryption and decryption things in python.
I was provided both pgp private.key and public.key files to do a simple encryption and decryption on a text file.
import gnupg as g
import os
from datetime import datetime
#Home directory
gpg = g.GPG('/key/')
date1 =datetime.today().strftime('%Y%m%d')
file1_combined_faia_csv='test_file.txt'
file1_combined_faia='test_encry.pgp'
key_data = None
print 'pen the public key file.'
with open('priv.key','rb') as f:
Key_data = f.read()
print 'Importing Key data from the keydata'
key = gpg.import_keys(Key_data)
#List the Keys from the data
pub_key = gpg.list_keys()
key_data = pub_key[2]
with open(file1_combined_faia_csv,'rb') as file:
file_data= file.read()
data = gpg.encrypt(file_data,key_data["keyid"])
with open(file1_combined_faia,'w+') as dec:
dec.write(str(data))
print 'for PIC Encryption done!!!'
print 'OK: ' + str(data.ok)
print 'Msg: ' + str(data.status)
print 'Error: ' + str(data.stderr)
Blow is my original string.
Hi this is tharun from data team.
And it encrypted successfully.
Please look below of my decryption code. I was provided passphrase also by my client.
import gnupg as g
import os
from datetime import datetime
#Home directory
gpg = g.GPG('/key/')
date1 =datetime.today().strftime('%Y%m%d')
file1_combined_faia_csv='test_encry.pgp'
file1_combined_faia='test_decryped.txt'
key_data = None
print 'pen the private key file.'
with open('priv.key','rb') as f:
Key_data = f.read()
key = gpg.import_keys(Key_data)
pub_key = gpg.list_keys(True)
key_data = pub_key[0]
file_data = None
print 'for FAIA Encrypting.........'
with open(file1_combined_faia_csv,'rb') as file:
file_data= file.read()
data = gpg.decrypt(str(file_data),passphrase="*************"
with open(file1_combined_faia,'w+') as dec:
dec.write(str(data))
print 'for PIC Decryption done!!!'
print 'OK: ' + str(data.ok)
print 'Msg: ' + str(data.status)
print 'Error: ' + str(data.stderr)
Below is the error message
[GNUPG:] NO_SECKEY D43DA661974C8582
[GNUPG:] BEGIN_DECRYPTION
[GNUPG:] DECRYPTION_FAILED
gpg: decryption failed: No secret key
[GNUPG:] END_DECRYPTION
I am doing above things based on some sample tutorials. I think i am missng some thing while decrypting. I may use both private key and passphrase but not sure how.
can you please help me on the decryption part.
Please let me know if any further info needed.
Thanks

Related

DSA key format not supported

I am trying to do a P2MS script.
For my script, I am saving the keys into a text file with DER format instead of the usual PEM file. Both key and signatures are saved in a text file and hexlify. Below is my code for the P2MS execution.
from Crypto.PublicKey import DSA
from Crypto.Hash import SHA256
from Crypto.Signature import DSS
from binascii import hexlify, unhexlify
import binascii
message = b"helpsmepls"
# Read scriptPubKey and scriptSig from files
with open('scriptPubKey.txt', 'r') as f:
readscriptPubKey = f.read().strip()
with open('scriptSig.txt', 'r') as f:
scriptSig = f.read().strip()
print(type(readscriptPubKey))
tempholder = readscriptPubKey.split()
# Removing the first character and last character
removeend = tempholder[1:-1]
scriptPubKey = []
# Removing front extra headings
for count, x in enumerate(removeend):
w = bytes(removeend[count][1:-1], encoding = 'utf-8')
#print(w)
scriptPubKey.append(w)
# Splitting the Signatures
signatures = scriptSig.split()
hash_obj = SHA256.new(message)
# Going through the pubkeys based on the number of signatures generated
for o, sig in enumerate(signatures):
pub_key = DSA.import_key(bytes.fromhex(scriptPubKey[o].decode("utf-8")))
hash_obj = SHA256.new(message)
verifier = DSS.new(pub_key, 'fips-183-3')
# Verifying if the Public key and signatures match, loop will break if False is encountered
if verifier.verify(hash_obj, sig):
d = True
else:
d = False
break
break
if d == True:
print("The message is authentic.")
else: print("The message is not authentic.")
Unfortunately before my code can reach the verification, it encountered an error.
Full traceback
It seems my DSA key format has an error, but I am not too sure why is it giving me that error.
I have also tried unhexlifying my input from the public key text file, but it also did not work. I have tried to hex decode the input to get the DER format of the input, but my type is still just bytes. I am not so sure how to properly import the key with the appropriate DSA key format from a txt file. I am able to do that with a PEM file but would just like to find out how to execute it with a txt file.
My expected outcome is the DSA key is imported properly and i am able to verify the public key with the signatures.

How does a fernet key work and how to store it safely (Python)?

I am experimenting with Fernet from Cryptography module in Python and encountered certain heavy terms I was not able to understand, despite clear and good documentation of the Cryptography library.
My question is: how does a fernet key works exactly, and how do I use my own passwords as key to fernet class? And how do I store this derived key such that if it is compromised to an attacker, it is hard for the attacker to break it into its original pass phrase?
What I have tried so far :
class Main():
def __init__(self):
print("Running Sequences")
def lock_dir(self, dirc, pwd, zip_name, zip_pwd):#taking directory to lock , the password for fernet , the password for zip and name for the zip
#declaring all arguments in variables
self.dirc = dirc
self.pwd = pwd
self.zip_name = zip_name
self.zip_pwd = zip_pwd
#a separate path for key to be written
self.key_dirc = self.dirc + "\\key.txt"
# generating a key from the password
self.pwd_bytes = self.pwd.encode()
self.salt = os.urandom(16) #generating salt
self.kdf = Scrypt(salt = self.salt, length = 32, n = 2**20, r = 8, p = 1)
self.key = base64.urlsafe_b64encode(self.kdf.derive(self.pwd_bytes))
self.fernet_object = Fernet(self.key)
#traversing through the directory provided by the user
for files in os.listdir(self.dirc):
with open(os.path.join(self.dirc, files), "rb") as file:
self.file_data = file.read()
file.close()
encrypted_data = self.fernet_object.encrypt(self.file_data)
with open(os.path.join(self.dirc, files), "wb") as file:
file.write(encrypted_data)
file.close()
with open(self.key_dirc, "wb") as hash_file:
hash_file.write(self.key)
hash_file.close()
Now , another question is that would the attacker will be able to use this key.txt as a key to directly decrypt the data encrypted through it, compromising all efforts at vain or will this key.txt will be needed to derived again into a key to decrypt the data ?
Thank you

Convert Bitcoin private key from file text

Good afternoon, friends, I just started learning python, I found this code that suits my needs, but on the way out everything is synchronized in one line, help me with this problem.
"
import ecdsa
import hashlib
import base58
with open("my_private_key.txt", "r") as f: #Input file path
for line in f:
#Convert hex private key to bytes
private_key = bytes.fromhex(line)
#Derivation of the private key
signing_key = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()
public_key = bytes.fromhex("04") + verifying_key.to_string()
#Hashes of public key
sha256_1 = hashlib.sha256(public_key)
ripemd160 = hashlib.new("ripemd160")
ripemd160.update(sha256_1.digest())
#Adding prefix to identify Network
hashed_public_key = bytes.fromhex("00") + ripemd160.digest()
#Checksum calculation
checksum_full = hashlib.sha256(hashlib.sha256(hashed_public_key).digest()).digest()
checksum = checksum_full[:4]
#Adding checksum to hashpubkey
bin_addr = hashed_public_key + checksum
#Encoding to address
address = str(base58.b58encode(bin_addr))
final_address = address[2:-1]
print(final_address)
with open("my_addresses.txt", "a") as i:
i.write(final_address)
"
print writes a trailing newline after writing all its arguments. write does not; you have to supply it yourself.
with open("my_addresses.txt", "a") as i:
i.write(final_address + "\n")
Or, you can use print:
with open("my_addresses.txt", "a") as i:
print(final_address, file=i)
Ignoring many of its keyword arguments, print is defined something like
def print(*args, end='\n', sep=' ', file=sys.stdout):
file.write(sep.join(args))
file.write(end)
Also, note that you don't need to repeatedly open your output file. You can open it at the same time as the input and leave it open for the duration of the loop.
with open("my_private_key.txt", "r") as f, \
open("my_addresses.txt", "a") as i:
for line in f:
...
print(final_address, file=i)

python gnupg decryption failing due to bad password on generated keys

I'm trying to use the Python gnupg package from here to do GPG encryption. I wrote some sample code to make sure I was using the API correctly but most of the existing examples of the package use a home directory. I'd like to be able to import/export the keys and interact with the API through that.
My test code is below:
def doEncryptFile(pubKeyFile, inDataFile):
f = open(pubKeyFile,"r")
data = f.read()
f.close()
gpg = gnupg.GPG()
import_result = gpg.import_keys(data)
public_key = gpg.list_keys()[0]
f = open(inDataFile,"r")
decData = f.read()
f.close()
encrypted = gpg.encrypt(decData, public_key['fingerprint'])
print("encrypted?")
print(str(encrypted.ok))
print(str(encrypted.status))
print(str(encrypted))
return str(encrypted)
def doDecryptFile(privKeyFile, inDataFile, privPass):
f = open(privKeyFile,"r")
data = f.read()
f.close()
gpg = gnupg.GPG()
import_result = gpg.import_keys(data)
public_key = gpg.list_keys()[0]
f = open(inDataFile,"rb")
decData = f.read()
f.close()
decrypted_data = gpg.decrypt(decData, passphrase=privPass)
print("decrypted?")
print(str(decrypted_data.ok))
print(str(decrypted_data.status))
gpg = gnupg.GPG()
key = do_key_generation(gpg, "helloWorld")
print(str(type(key)))
private_key = gpg.export_keys(key.fingerprint, True, passphrase="helloWorld")
public_key = gpg.export_keys(key.fingerprint)
with open('sample_public.asc', 'w') as f:
f.write(public_key)
with open('sample_private.asc', 'w') as f:
f.write(private_key)
doEncryptFile(r"sample_public.asc", "sampleDecryptedData.txt")
doDecryptFile(r"sample_private.asc", "sampleEncrypted.txt", privPass="helloWorld")
In the above example I manually copied the encrypted text to sampleEncrypted.txt. The key generation function is taken from here. When using it this way, the encryption works as expected and I get the ASCII-encoded blob.
However when trying to decrypt the file the decryption fails. If I do not provide the passphrase I get a prompt from OpenPGP telling me to enter my password, so it's at least partially working, but the decryption fails and the status message is just "decryption failed". If I try to manually enter the "helloWorld" password in the pinentry-qt GUI the error message is "Bad Passphrase". I've also tried using decrypt_file with input file containing the ASCII blob as described on the python-gnupg page, to the same result.
I'm on Python 3 on a Windows system if that makes a difference. I'll also note that when using gpg through the command line everything works as expected.
You forgot to save the outputs to a file.
I added the output= options to the gpg.encrypt and gpg.decrypt, and of course to your functions.
import gnupg
def do_key_generation(gpg, passphrase = "helloWorld"):
input_data = gpg.gen_key_input(
name_email='me#email.com',
passphrase=passphrase,
)
key = gpg.gen_key(input_data)
print(key)
return key
def doEncryptFile(pubKeyFile, inDataFile, outputDatafile):
f = open(pubKeyFile,"r")
data = f.read()
f.close()
gpg = gnupg.GPG()
import_result = gpg.import_keys(data)
public_key = gpg.list_keys()[0]
f = open(inDataFile,"rb")
decData = f.read()
f.close()
encrypted = gpg.encrypt(decData, public_key['fingerprint'],output=outputDatafile)
print("encrypted?")
print(str(encrypted.ok))
print(str(encrypted.status))
print(str(encrypted))
def doDecryptFile(privKeyFile, inDataFile, privPass,outputDatafile):
f = open(privKeyFile,"r")
data = f.read()
f.close()
gpg = gnupg.GPG()
import_result = gpg.import_keys(data)
public_key = gpg.list_keys()[0]
f = open(inDataFile,"rb")
decData = f.read()
f.close()
decrypted_data = gpg.decrypt(decData, passphrase=privPass,output=outputDatafile)
print("decrypted?")
print(str(decrypted_data.ok))
print(str(decrypted_data.status))
gpg = gnupg.GPG()
key = do_key_generation(gpg, "helloWorld")
print(str(type(key)))
private_key = gpg.export_keys(key.fingerprint, True, passphrase='helloWorld')
public_key = gpg.export_keys(key.fingerprint)
with open('sample_public.asc', 'w') as f:
f.write(public_key)
with open('sample_private.asc', 'w') as f:
f.write(private_key)
doEncryptFile(r"sample_public.asc", "sampleFile.txt","sampleEncrypted.txt")
doDecryptFile(r"sample_private.asc", "sampleEncrypted.txt", privPass="helloWorld", outputDatafile="sampleDecrypted.txt" )

Encrypt data in PostgreSQL and decrypt the data in Python

I have data in my database that I need to encrypt. I will then download the database to csv files. I have a python program that can decrypt the specific columns in a csv file. The problem is that I don't get my data out from the python program.
sql function:
CREATE OR REPLACE FUNCTION AESEncrypt (data TEXT,pass TEXT)
RETURNS TEXT AS $crypted$
declare
crypted TEXT;
key BYTEA;
iv BYTEA;
BEGIN
key := digest(convert_to(pass, 'utf-8'), 'sha256');
iv := digest(convert_to(CONCAT(data , 'salt'), 'utf-8'), 'md5');
crypted := encode(encrypt_iv(convert_to(data, 'utf-8'), key, iv, 'aes'), 'base64');
RETURN crypted;
END;
$crypted$ LANGUAGE plpgsql;
python program:
import csv
import time
import base64
from hashlib import sha256, md5
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
password = 'Password'
inputFile = 'test.txt'
outputFile = 'out.txt'
delimiter = ';'
columns = [0]
backend = default_backend()
key = sha256(password.encode('utf-8')).digest()
iv = md5((password + 'salt').encode('utf-8')).digest()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
def encrypt(input):
input = bytes(input, 'utf-8')
#Padding
length = 16 - (len(input) % 16)
input += bytes([length])*length
#Encrypt
encryptor = cipher.encryptor()
return base64.b64encode(encryptor.update(input) + encryptor.finalize()).decode("utf-8")
def decrypt(input):
input = base64.b64decode(input)
decryptor = cipher.decryptor()
data = decryptor.update(input) + decryptor.finalize()
data = data[:-data[-1]] #Remove padding
print(data)
return data.decode('utf-8')
def main():
start_time = time.time()
with open(inputFile, 'r') as csvfileIn:
with open(outputFile, 'w', newline='') as csvfileOut:
spamreader = csv.reader(csvfileIn, delimiter=delimiter)
spamwriter = csv.writer(csvfileOut, delimiter=delimiter)
firstRow = True
for row in spamreader:
if not firstRow:
for pos in columns:
row[pos] = decrypt(row[pos])
firstRow = False
spamwriter.writerow(row)
print("--- %s seconds ---" % (time.time() - start_time))
main()
If I encrypt the file with the encrypt function written in the python program then I get the correct result if i would decrypt it.
If I would call the sql funcion as AESEncrypt('data', 'Password') then it returns the base64 string Ojq6RKg7NgDx8YFdLzfVhQ==
But after decryption I get the empty string as result and not the string data. If I look at the print statment before the utf-8 decode step in the decryption function it prints out the following on the console b'', so it looks like it could be something wrong with the padding. If I would print before I remove the padding I get b'\x85\x90sz\x0cQS\x9bs\xeefvA\xc63-'. If I will encrypt a long sentence then I will actually see parts of the text in the byte outputs above.
Do anyone know what I have done wrong?

Categories