4

I am attempting to generate a public/private elliptic curve key pair in python using hazmat in cryptography. Below is the current code that I have. When I run, it is generating the error 'NoneType' object has no attribute 'generate_elliptic_curve_private_key'

ecurve = asymmetric.ec.EllipticCurve
ecurve.name = 'secp256r1'
ecurve.key_size = 128
ec_backend = cryptography.hazmat.backends.interfaces.EllipticCurveBackend.generate_elliptic_curve_private_key(cryptography.hazmat.backends.interfaces.EllipticCurveBackend, ecurve)
key = asymmetric.ec.generate_private_key(curve=ecurve, backend=ec_backend)  

Here is the documentation https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ec/#

Tim Welles
  • 43
  • 1
  • 3
  • `EllipticCurveBackend` ... The term "backend" here shouts "do not use" back at me. Even if it runs, it probably crashes on the first rewrite of the EC functionality. – Maarten Bodewes Dec 09 '19 at 13:25

1 Answers1

14

I don't see where generate_elliptic_curve_private_key method is available.

Here is an example of generating a SECP256R1 and serializing the public key into PEM format:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec

private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
public_key = private_key.public_key()
# serializing into PEM
rsa_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)

printing the key

In [14]: print(rsa_pem.decode())
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEilwhueTwySfEbXd9y/inZVsYVG6z
/UJyVbN+cYgtIFd0vLdaP27cME8RGE/enMEcX7/jkb13j2DPnXt2R6teZw==
-----END PUBLIC KEY-----
Alex Gaynor
  • 14,353
  • 9
  • 63
  • 113
salparadise
  • 5,699
  • 1
  • 26
  • 32
  • This does answer the question, however, I was trying to set the size of the key in the original code. Is there any way to do this inside the above? – Tim Welles Dec 09 '19 at 16:33
  • Key sizes are strictly tied to the curve parameters (e.g. a named curve like secp256r1). If you want a larger key size you need to use a different curve. secp256r1 has private keys that are 256-bit because the secret scalar (the private key) is a value less than the curve's order (which is 256-bit). The example provided here is the correct API for key generation (and public point serialization) on a given curve. – Paul Kehrer Dec 10 '19 at 05:35
  • That makes sense. Thank you! – Tim Welles Dec 11 '19 at 01:31