Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature crypto backend2 #202

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ on:

jobs:
build:
name: test-${{ matrix.python }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
Expand Down
17 changes: 17 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
Changelog
=========

This PR
----------
* Deprecated pyOpenSSL in favor of Cryptography.
* Deprecated the following for removal in the next scheduled release:
`josepy.util.ComparableX509`
* The following functions now accept a `josepy.util.ComparableX509` OR a
`cryptography.x509.Certificate`:
- `josepy.json_util.encode_cert`
* The following functions now accept a `josepy.util.ComparableX509` OR a
`cryptography.x509.CertificateSigningRequest`:
- `josepy.json_util.encode_csr`
* Added the following functions:
- `josepy.json_util.decode_cert_cryptography`
- `josepy.json_util.decode_csr_cryptography`
* x5c headers are now raw Cryptography objects


1.15.0 (master)
---------------
* Added support for Python 3.13.
Expand Down
4 changes: 2 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ python = "^3.8"
# load_pem_private/public_key (>=0.6)
# rsa_recover_prime_factors (>=0.8)
# add sign() and verify() to asymetric keys (RSA >=1.4, ECDSA >=1.5)
cryptography = ">=1.5"
# add not_valid_after_utc() in (>=42.0.0)
cryptography = ">=42.0.0"
# Connection.set_tlsext_host_name (>=0.13)
pyopenssl = ">=0.13"
# incompatibilities with cryptography; X509_V_FLAG_NOTIFY_POLICY removed (>=23.2.0)
pyopenssl = ">=23.2.0"
# >=4.3.0 is needed for Python 3.10 support
sphinx = {version = ">=4.3.0", optional = true}
sphinx-rtd-theme = {version = ">=1.0", optional = true}
Expand Down
2 changes: 2 additions & 0 deletions src/josepy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@
TypedJSONObjectWithFields,
decode_b64jose,
decode_cert,
decode_cert_cryptography,
decode_csr,
decode_csr_cryptography,
decode_hex16,
encode_b64jose,
encode_cert,
Expand Down
89 changes: 68 additions & 21 deletions src/josepy/json_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@
Optional,
Type,
TypeVar,
Union,
)

from OpenSSL import crypto
from cryptography import x509
from cryptography.hazmat.primitives.serialization import Encoding

from josepy import b64, errors, interfaces, util

Expand Down Expand Up @@ -426,59 +428,104 @@ def decode_hex16(value: str, size: Optional[int] = None, minimum: bool = False)
raise errors.DeserializationError(error)


def encode_cert(cert: util.ComparableX509) -> str:
def encode_cert(cert: Union[util.ComparableX509, x509.Certificate]) -> str:
"""Encode certificate as JOSE Base-64 DER.

:type cert: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`
:type cert: `cryptography.x509.Certificate`
:rtype: unicode

"""
if isinstance(cert.wrapped, crypto.X509Req):
if isinstance(cert, util.ComparableX509):
# DEPRECATED; remove in next release
util.warn_deprecated(
"""`josepy.json_util.encode_cert` has deprecated support for"""
"""util.ComparableX509 objects. Please use """
"""`cryptography.x509.Certificate` objects instead."""
)
if isinstance(cert.wrapped_new, x509.CertificateSigningRequest):
raise ValueError("Error input is actually a certificate request.")
return encode_b64jose(cert.wrapped_new.public_bytes(Encoding.DER))
if isinstance(cert, x509.CertificateSigningRequest):
raise ValueError("Error input is actually a certificate request.")

return encode_b64jose(crypto.dump_certificate(crypto.FILETYPE_ASN1, cert.wrapped))
return encode_b64jose(cert.public_bytes(Encoding.DER))


def decode_cert(b64der: str) -> util.ComparableX509:
"""Decode JOSE Base-64 DER-encoded certificate.

:param unicode b64der:
:rtype: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`
:rtype: `cryptography.x509.Certificate` wrapped in `.ComparableX509`

"""
util.warn_deprecated(
"""`josepy.json_util.decode_cert` has been deprecated and will be removed"""
"""in a future release. please use `josepy.json_util.decode_cert_cryptography`"""
"""instead."""
)
try:
return util.ComparableX509(
crypto.load_certificate(crypto.FILETYPE_ASN1, decode_b64jose(b64der))
)
except crypto.Error as error:
return util.ComparableX509(x509.load_der_x509_certificate(decode_b64jose(b64der)))
except Exception as error:
raise errors.DeserializationError(error)


def decode_cert_cryptography(b64der: str) -> x509.Certificate:
"""Decode JOSE Base-64 DER-encoded certificate.

:param unicode b64der:
:rtype: `cryptography.x509.Certificate`

"""
try:
return x509.load_der_x509_certificate(decode_b64jose(b64der))
except Exception as error:
raise errors.DeserializationError(error)


def encode_csr(csr: util.ComparableX509) -> str:
def encode_csr(csr: Union[util.ComparableX509, x509.CertificateSigningRequest]) -> str:
"""Encode CSR as JOSE Base-64 DER.

:type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`
:type csr: `cryptography.x509.CertificateSigningRequest`
:rtype: unicode

"""
if isinstance(csr.wrapped, crypto.X509):
if isinstance(csr, util.ComparableX509):
# DEPRECATED; remove in next release
util.warn_deprecated(
"""`josepy.json_util.encode_csr` has deprecated support for"""
"""util.ComparableX509 objects. Please use """
"""`cryptography.x509.CertificateSigningRequest` objects instead."""
)
if isinstance(csr.wrapped_new, x509.Certificate):
raise ValueError("Error input is actually a certificate.")
return encode_b64jose(csr.wrapped_new.public_bytes(Encoding.DER))
if isinstance(csr, x509.Certificate):
raise ValueError("Error input is actually a certificate.")

return encode_b64jose(crypto.dump_certificate_request(crypto.FILETYPE_ASN1, csr.wrapped))
return encode_b64jose(csr.public_bytes(Encoding.DER))


def decode_csr(b64der: str) -> util.ComparableX509:
"""Decode JOSE Base-64 DER-encoded CSR.

:param unicode b64der:
:rtype: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`
:rtype: `cryptography.x509.CertificateSigningRequest` wrapped in `.ComparableX509`

"""
try:
return util.ComparableX509(
crypto.load_certificate_request(crypto.FILETYPE_ASN1, decode_b64jose(b64der))
)
except crypto.Error as error:
return util.ComparableX509(x509.load_der_x509_csr(decode_b64jose(b64der)))
except Exception as error:
raise errors.DeserializationError(error)


def decode_csr_cryptography(b64der: str) -> x509.CertificateSigningRequest:
"""Decode JOSE Base-64 DER-encoded CSR.

:param unicode b64der:
:rtype: `cryptography.x509.CertificateSigningRequest`

"""
try:
return x509.load_der_x509_csr(decode_b64jose(b64der))
except Exception as error:
raise errors.DeserializationError(error)


Expand Down
25 changes: 15 additions & 10 deletions src/josepy/jws.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
Optional,
Tuple,
Type,
Union,
cast,
)

from OpenSSL import crypto
from cryptography import x509
from cryptography.hazmat.primitives.serialization import Encoding

import josepy
from josepy import b64, errors, json_util, jwa
Expand Down Expand Up @@ -80,7 +82,10 @@ class Header(json_util.JSONObjectWithFields):
)
kid: Optional[str] = json_util.field("kid", omitempty=True)
x5u: Optional[bytes] = json_util.field("x5u", omitempty=True)
x5c: Tuple[util.ComparableX509, ...] = json_util.field("x5c", omitempty=True, default=())
x5c: Union[
Tuple[util.ComparableX509, ...],
Tuple[x509.Certificate, ...],
] = json_util.field("x5c", omitempty=True, default=())
x5t: Optional[bytes] = json_util.field("x5t", decoder=json_util.decode_b64jose, omitempty=True)
x5tS256: Optional[bytes] = json_util.field(
"x5t#S256", decoder=json_util.decode_b64jose, omitempty=True
Expand Down Expand Up @@ -138,21 +143,21 @@ def crit(unused_value: Any) -> Any:

@x5c.encoder # type: ignore
def x5c(value):
# DEPRECATE `cert.wrapped_new`
return [
base64.b64encode(crypto.dump_certificate(crypto.FILETYPE_ASN1, cert.wrapped))
(
base64.b64encode(cert.wrapped_new.public_bytes(Encoding.DER))
if isinstance(cert, util.ComparableX509)
else base64.b64encode(cert.public_bytes(Encoding.DER))
)
for cert in value
]

@x5c.decoder # type: ignore
def x5c(value):
try:
return tuple(
util.ComparableX509(
crypto.load_certificate(crypto.FILETYPE_ASN1, base64.b64decode(cert))
)
for cert in value
)
except crypto.Error as error:
return tuple(x509.load_der_x509_certificate(base64.b64decode(cert)) for cert in value)
except Exception as error:
raise errors.DeserializationError(error)


Expand Down
Loading
Loading