How to verify a signature using M2Crypto 0.16 - signature

After some goggling I found some usual answers for this question, like:
How to load an RSA key from a PEM file and use it in python-crypto
some code:
x509 = X509.load_cert_string(certificate)
pubkey = x509.get_pubkey()
pubkey.reset_context(md=sha1)
pubkey.verify_init()
pubkey.verify_update(content)
decoded_signature = signature.decode('base64')
if pubkey.verify_final(decoded_signature)==0:
print 'error'
sys.exit(1)
and the code presented above works fine in M2Crypto 0.20.
But I need to do exactly the same think using the M2Crypto 0.16 (the official package in RHEL5), and I have problems using the pubkey.verify_final method because in this particular version the signature parameter doesn't exist.
So how can I do it? using the M2Crypto 0.16
Thanks.

Lucky for you, the OpenSSL function you need is available in M2Crypto 0.16, it is just the Python method that is not providing the extra argument you need. This is easy to work around. Where you would call pubkey.verify_final(decoded_signature), call pubkey_verify_final(pubkey, decoded_signature), which you will define in your code as:
from M2Crypto import m2
def pubkey_verify_final(pubkey, decoded_signature):
return m2.verify_final(pubkey.ctx, decoded_signature, pubkey.pkey)
(Note, I did not actually test that, just compared the source between 0.16 and 0.20.)

Related

ValueError: Comments are not supported by the python backend

The ijson module has a documented option allow_comments=True, but when I include it,
an error message is produced:
ValueError: Comments are not supported by the python backend
Below is a transcript using the file test.py:
import ijson
for o in ijson.items(open(0), 'item'):
print(o)
Please note that I have no problem with a similar documented option, multiple_values=True.
Transcript
$ python3 --version
Python 3.10.9
$ python3 test.py <<< [1,2]
1
2
# Now change the call to: ijson.items(open(0), 'item', allow_comments=True)
$ python3 test.py <<< [1,2]
Traceback (most recent call last):
File "/Users/user/test.py", line 5, in <module>
for o in ijson.items(open(0), 'item', allow_comments=True):
File "/usr/local/lib/python3.10/site-packages/ijson/utils.py", line 51, in coros2gen
f = chain(events, *coro_pipeline)
File "/usr/local/lib/python3.10/site-packages/ijson/utils.py", line 29, in chain
f = coro_func(f, *coro_args, **coro_kwargs)
File "/usr/local/lib/python3.10/site-packages/ijson/backends/python.py", line 284, in basic_parse_basecoro
raise ValueError("Comments are not supported by the python backend")
ValueError: Comments are not supported by the python backend
$
Take a look at the Backends section of the documentation, which says:
Ijson provides several implementations of the actual parsing in the form of backends located in ijson/backends:
yajl2_c: a C extension using YAJL 2.x. This is the fastest, but might require a compiler and the YAJL development files to be present when installing this package. Binary wheel distributions exist for major platforms/architectures to spare users from having to compile the package.
yajl2_cffi: wrapper around YAJL 2.x using CFFI.
yajl2: wrapper around YAJL 2.x using ctypes, for when you can’t use CFFI for some reason.
yajl: deprecated YAJL 1.x + ctypes wrapper, for even older systems.
python: pure Python parser, good to use with PyPy
And later on in the FAQ it says:
Q: Are there any differences between the backends?
...
The python backend doesn’t support allow_comments=True It also internally works with str objects, not bytes, but this is an internal detail that users shouldn’t need to worry about, and might change in the future.
If you want support for allow_comments=True, you need to be using one of the yajl based backends. According to the docs:
Importing the top level library as import ijson uses the first available backend in the same order of the list above, and its name is recorded under ijson.backend. If the IJSON_BACKEND environment variable is set its value takes precedence and is used to select the default backend.
You'll need the necessary libraries, etc, installed on your system in order for this to work.

Not able to find number of pages of PDF using Python 3.X: DependencyError: PyCryptodome is required for AES algorithm

I am performing data validation on files that I download from a url. One of those validation checks involves checking the number of pages of a PDF. Using PyPDF2 package and PdfFileReader module, this worked until I encountered a PDF with 256-bit AES encryption that has a permissions password but no document open password. I have no access to any passwords since these files are from manufacturer websites so I concluded that for now I can just check to see if the PDF is encrypted, and if it is, skip it for now, but regardless if I try to retrieve the page count or check if the PDF is encrypted, I get this error:
DependencyError: PyCryptodome is required for AES algorithm
This error occurs at line 6, the if statement.
This is despite having pycryptodome installed and the AES module imported. Also, I am using Jupyter Notebook. Here is my code:
! pip install PyPDF2
! pip install pycryptodome
from PyPDF2 import PdfFileReader
from Crypto.Cipher import AES
if PdfFileReader('Media Downloaded Files/spk-10-3144 bro.pdf').isEncrypted:
print('This file is encrypted.')
else:
print(PdfFileReader('Media Downloaded Files/spk-10-3144-bro.pdf').numPages)
Solution:
! pip install pikepdf
from pikepdf import Pdf
pdf = Pdf.open('Media Downloaded Files/spk-10-3144-bro.pdf')
len(pdf.pages)
I had a problem using PyPDF3 (it's a fork from PyPDF2) involving encryptation. I solved replacing it for pikepdf. It has more encryption algorithms implementations. Try it out!

What are Python3 libraries which replace "from scikits.audiolab import Format, Sndfile"

Hope you'll are doing good. I am new to python. I am trying to use audio.scikits library in python3 verion. I have a working code version in 2.7(with audio.scikits) . While I am running with python3 version I am getting the Import Error: No Module Named 'Version' error. I get to know that python3 is not anymore supporting audio.scikits(If I am not wrong). Can anyone suggest me replacing library for audio.scikits where I can use all the functionalities like audio.scikits do OR any other solution which might helps me. Thanks in advance.
2.7 Version Code :
from scikits.audiolab import Format, Sndfile
from scipy.signal import firwin, lfilter
array = np.array(all)
fmt = Format('flac', 'pcm16')
nchannels = 1
cd, FileNameTmp = mkstemp('TmpSpeechFile.wav')
# making the file .flac
afile = Sndfile(FileNameTmp, 'w', fmt, nchannels, RawRate)
#writing in the file
afile.write_frames(array)
SendSpeech(FileNameTmp)
To check entire code please visit :Google Asterisk Reference Code(modifying based on this code)
I want to modify this code with python3 supported libraries. Here I am doing this for Asterisk-Microsoft-Speech To Text SDK.
Firstly the link code you paste is Asterisk-Google-Speech-Recognition, it's not the Microsoft-Speech-To-Text, if you want get a sample about Microsoft-Speech-To-Text you could refer to the official doc:Recognize speech from an audio file.
And about your problem you said, yes it's not completely compatible, in the github issue there is a solution for it, you could refer to this comment.

MD5 Hash, Python 3 . How to Generate In Python

I need advice on how to get the md5 hash for a zip file. I will be constantly downloading files from an ftp using ftplib. As you know ftplib cannot tell if a file has been modified or not.
I want to use the md5 hash of each new file to tell if it has been modified or not by simply comparing the hashes after downloading the new file to tempdir. If the hashes are similar, I remove newly downloaded file. However, if hashes are different, newly downloaded file is kept, old hash is replaced with new hash and the script continues.
Please advice on how to achieve this. Are there any standalone modules for hashing md5 or similar.
Thanks.``
hope this is helpful
import hashlib
m=hashlib.md5();
m.update(open('yourzipfile.zip').read());
a=m.hexdigest()
print (a);
output
sh-4.3$ python3 1.py
f5c6a076bd116efbd4b1ce03c96eaf7a
Very simply, in python 3.8+, I use to keep the code as quick and compact as possible.
import hashlib
file_hash = hashlib.md5(open(old_file_path,'rb').read()).hexdigest()
print(file_hash)

Proper way to cleanup dynamic engines and can they be loaded twice?

I am having problems loading Engine PKCS #11 as a dynamic engine using python and M2Crypto. I am trying to access an Aladdin USB eToken.
Here are the important steps from my python code:
dynamic = Engine.load_dynamic_engine("pkcs11", "/usr/local/ssl/lib/engines/engine_pkcs11.so")
pkcs11 = Engine.Engine("pkcs11")
pkcs11.ctrl_cmd_string("MODULE_PATH", "/usr/lib/libeTPkcs11.so")
pkcs11.engine_init_custom() # initialize engine with custom M2Crypto patch
# next few steps which I deleted pass password and grab key & cert off token
Engine.cleanup()
This works fine the first time this method gets run. The second time, it fails when loading the dynamic engine (see error below).
Traceback (most recent call last):
File "", line 1, in ?
File "/usr/local/lib/python2.4/site-packages/M2Crypto/Engine.py", line 98, in load_dynamic_engine
e.ctrl_cmd_string("LOAD", None)
File "/usr/local/lib/python2.4/site-packages/M2Crypto/Engine.py", line 38, in ctrl_cmd_string
raise EngineError(Err.get_error())
M2Crypto.Engine.EngineError: 4002:error:260B606D:engine routines:DYNAMIC_LOAD:init failed:eng_dyn.c:521:
Is it impossible to load engines twice in a python session? Am I missing some kind of engine cleanup/deletion? The OpenSSL docs talk about engine_finish() but I don't think M2Crypto offers that. Is there a method to tell if the engine is already loaded?
Thanks!
M2Crypto does have ENGINE_finish and ENGINE_free available in the svn trunk version. The Engine class has init, and finish methods, and when an instance gets deleted it will be free'd. Can you give that a try? If you see any issues there is still time to fix them for next release.
My python code displayed nicer than it is in the comment section. The pkcs11.finish() method causes a segmentation fault in M2Crypto revision 723.
dynamic = Engine.load_dynamic_engine("pkcs11", "/usr/local/ssl/lib/engines/engine_pkcs11.so")
pkcs11 = Engine.Engine("pkcs11")
pkcs11.ctrl_cmd_string("MODULE_PATH", "/usr/lib/libeTPkcs11.so")
pkcs11.init()
# next few steps which I deleted pass password and grab key & cert off token
pkcs11.finish()
Engine.cleanup()
Anyone have advice on whether I'm doing something wrong or if there is a problem with the M2Crypto code?

Resources