Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def from_jwk(jwk):
if not isinstance(jwk, JsonWebKey):
raise TypeError('The specified jwk must be a JsonWebKey')
if jwk.kty != 'RSA' and jwk.kty != 'RSA-HSM':
raise ValueError('The specified jwk must have a key type of "RSA" or "RSA-HSM"')
if not jwk.n or not jwk.e:
raise ValueError('Invalid RSA jwk, both n and e must be have values')
rsa_key = RsaKey()
rsa_key.kid = jwk.kid
rsa_key.kty = jwk.kty
rsa_key.key_ops = jwk.key_ops
pub = RSAPublicNumbers(n=_bytes_to_int(jwk.n), e=_bytes_to_int(jwk.e))
# if the private key values are specified construct a private key
# only the secret primes and private exponent are needed as other fields can be calculated
if jwk.p and jwk.q and jwk.d:
# convert the values of p, q, and d from bytes to int
p = _bytes_to_int(jwk.p)
q = _bytes_to_int(jwk.q)
d = _bytes_to_int(jwk.d)
# convert or compute the remaining private key numbers
dmp1 = _bytes_to_int(jwk.dp) if jwk.dp else rsa_crt_dmp1(private_exponent=d, p=p)
def generate(kid=None, kty='RSA', size=2048, e=65537):
key = RsaKey()
key.kid = kid or str(uuid.uuid4())
key.kty = kty
key.key_ops = RsaKey.PRIVATE_KEY_DEFAULT_OPS
key._rsa_impl = generate_private_key(public_exponent=e, key_size=size, backend=cryptography.hazmat.backends.default_backend())
# set the appropriate callbacks for retrieving the public and private key material
key._private_key_material = key._rsa_impl.private_numbers
key._public_key_material = key._rsa_impl.public_key().public_numbers
return key
def to_jwk(self, include_private=False):
jwk = JsonWebKey(kid=self.kid,
kty=self.kty,
key_ops=self.key_ops if include_private else RsaKey.PUBLIC_KEY_DEFAULT_OPS,
n=self.n,
e=self.e)
if include_private:
jwk.q = self.q
jwk.p = self.p
jwk.d = self.d
jwk.dq = self.dq
jwk.dp = self.dp
jwk.qi = self.qi
return jwk
def generate(kid=None, kty='RSA', size=2048, e=65537):
key = RsaKey()
key.kid = kid or str(uuid.uuid4())
key.kty = kty
key.key_ops = RsaKey.PRIVATE_KEY_DEFAULT_OPS
key._rsa_impl = generate_private_key(public_exponent=e, key_size=size, backend=cryptography.hazmat.backends.default_backend())
# set the appropriate callbacks for retrieving the public and private key material
key._private_key_material = key._rsa_impl.private_numbers
key._public_key_material = key._rsa_impl.public_key().public_numbers
return key
def from_jwk_str(s):
jwk_dict = json.loads(s)
jwk = JsonWebKey.from_dict(jwk_dict)
return RsaKey.from_jwk(jwk)