0
SHA = hashlib.sha1()
Eh = SHA.update(chunk)
HRSA.signSHA(Eh,RSAprivatekey)

RSAprivatekey is read in HRSA module and passed as argument to this function:

RSAprivatekey = RSA.importKey(infile.read())

infile points to the 'privatekey.txt' which contained only the RSAprivatekey.

HRSA is a module I've created which basically does this:

def signSHA(hash, key):
    signer = PKCS1_v1_5.new(key)
    D = signer.sign(hash)
    return D

I'm being shown the following error:

File "D:\Study\Sem V\Hybrid Encryption\Phase 2\HRSA.py", line 57, in signSHA
    D = signer.sign(hash)
  File "C:\Python33\lib\site-packages\Crypto\Signature\PKCS1_v1_5.py", line 110, in sign
    em = EMSA_PKCS1_V1_5_ENCODE(mhash, k)
  File "C:\Python33\lib\site-packages\Crypto\Signature\PKCS1_v1_5.py", line 211, in EMSA_PKCS1_V1_5_ENCODE
    digestAlgo  = DerSequence([hash.oid, DerNull().encode()])
AttributeError: 'NoneType' object has no attribute 'oid'

How could I fix this since it's a bug with the PyCrypto code?

  • 1
    Are you sure you have something in `hash`, Can you debug / print to verify? Also rename `hash` to `hash_` since you are shadowing the build in variable `hash` – Kobi K Oct 25 '15 at 12:54
  • Did that, 'NoneType' object has become 'bytes' object. Printed and checked, there's binary data present in hash. – Pranav Singhania Oct 25 '15 at 14:33

3 Answers3

1

hashfunc.update(arg) doesn't return anything. It's there to update the internal state of the hashing function with new input data. If you want to convert the internal state into a hash, then you need to call either hashfunc.digest() or hashfunc.hexdigest().

It would look like this:

Eh = hashlib.sha1(chunk).digest()
HRSA.signSHA(Eh, RSAprivatekey)
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
1

You must use the PyCrypto module for SHA1, so:

from Crypto.Hash import SHA1
sha_obj = SHA1.new()
sha_obj.update(chunk)
HRSA.signSHA(sha_obj,RSAprivatekey)

The reason is that the PKCS#1v1.5 signature embeds the ASN.1 Object ID of the hash, but the SHA-1 object obtained from the standard library does not include/know it.

0

As mentioned, hashlib does not work well with PyCryptodome. To provide a little more detailed example:

from Crypto.Hash import SHA256
from Crypto.Signature import pkcs1_15
from Crypto.PublicKey import RSA


# Generate a new RSA key pair with the specified key length
key_length = 1024
key = RSA.generate(key_length)

# Get the RSA keys
private_key = key.export_key()
public_key = key.publickey().export_key()

msg = b"The aliens are coming!"
hash = SHA256.new(msg)

# Generate the signature
signer = pkcs1_15.new(RSA.import_key(private_key))
signature = signer.sign(hash)

verifier = pkcs1_15.new(RSA.import_key(public_key))

#Exception will be thrown if verification fails
verifier.verify(hash, signature)