OpenSSL.crypto.X509.sign () throws object '' bytes does not have the attribute 'encode' "

Therefore, I am trying to use the OpenSSL cryptographic module to create a new CA certificate using this code:

#warning: this block is background information, probably not 
#where my real problem is

#generate the key pair
key=OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA,2048)

#print the private and public keys as PEMs
print(codecs.decode(OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM,key),'utf8'))
print(codecs.decode(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM,key),'utf8'))

#generate a new x509 certificate
ca=OpenSSL.crypto.X509()

#fill it with goodies
ca.set_version(3)
ca.set_serial_number(1)
ca.get_subject().CN = "CA.test.com"
ca.gmtime_adj_notBefore(0)
ca.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 10)
ca.set_issuer(ca.get_subject())
ca.set_pubkey(key)

#print the new certificate as a PEM
print(codecs.decode(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,ca),'utf8'))

The certificate that prints decodes OK in the SSLShopper decoder , so I feel pretty confident about this part. The problem really starts when I try to sign a certificate using

ca.sign(key, 'sha1')

because I get the "expected type" of bytes, instead of 'str' instead of it 'from the IDE. Check the documentation of OpenSSL.crypto.X509.sign () and make sure that it really expects a byte object, switch to

digestname='sha1'.encode('utf-8')
ca.sign(key, digestname)

AttributeError: 'bytes', 'encode' '. , , OpenSSL._util.byte_string(),

if PY3:
    def byte_string(s):
    return s.encode("charmap")
else:
    def byte_string(s):
    return s

PY3 = True s = {bytes} b'sha1 ', , , .encode.

"" "str". , , , Google- . , , , .

+4
1

, IDE (PyCharm) . ca.sign(key, 'sha1') . , PyCharm , , .

+1

Source: https://habr.com/ru/post/1650249/


All Articles