Skip to content

Commit

Permalink
Add support for AES-GCM-SIV using OpenSSL>=3.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
facutuesca committed Nov 27, 2023
1 parent 0626884 commit e3d316f
Show file tree
Hide file tree
Showing 7 changed files with 361 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ Changelog
* In the next release (43.0.0) of cryptography, loading an X.509 certificate
with a negative serial number will raise an exception. This has been
deprecated since 36.0.0.
* Added support for
:class:`~cryptography.hazmat.primitives.ciphers.aead.AESGCMSIV` when using
OpenSSL 3.2.0+.

.. _v41-0-5:

Expand Down
73 changes: 73 additions & 0 deletions docs/hazmat/primitives/aead.rst
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,79 @@ also support providing integrity for associated data which is not encrypted.
when the ciphertext has been changed, but will also occur when the
key, nonce, or associated data are wrong.

.. class:: AESGCMSIV(key)

.. versionadded:: 42.0.0

The AES-GCM-SIV construction is defined in :rfc:`8452` and is composed of
the :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES` block
cipher utilizing Galois Counter Mode (GCM) and a synthetic initialization
vector (SIV).

:param key: A 128, 192, or 256-bit key. This **must** be kept secret.
:type key: :term:`bytes-like`

:raises cryptography.exceptions.UnsupportedAlgorithm: If the version of
OpenSSL does not support AES-GCM-SIV.

.. doctest::

>>> import os
>>> from cryptography.hazmat.primitives.ciphers.aead import AESGCMSIV
>>> data = b"a secret message"
>>> aad = b"authenticated but unencrypted data"
>>> key = AESGCMSIV.generate_key(bit_length=128)
>>> aesgcmsiv = AESGCMSIV(key)
>>> nonce = os.urandom(12)
>>> ct = aesgcmsiv.encrypt(nonce, data, aad)
>>> aesgcmsiv.decrypt(nonce, ct, aad)
b'a secret message'

.. classmethod:: generate_key(bit_length)

Securely generates a random AES-GCM-SIV key.

:param bit_length: The bit length of the key to generate. Must be
128, 192, or 256.

:returns bytes: The generated key.

.. method:: encrypt(nonce, data, associated_data)

Encrypts and authenticates the ``data`` provided as well as
authenticating the ``associated_data``. The output of this can be
passed directly to the ``decrypt`` method.

:param nonce: A 12-byte value.
:type nonce: :term:`bytes-like`
:param data: The data to encrypt.
:type data: :term:`bytes-like`
:param associated_data: Additional data that should be
authenticated with the key, but is not encrypted. Can be ``None``.
:type associated_data: :term:`bytes-like`
:returns bytes: The ciphertext bytes with the 16 byte tag appended.
:raises OverflowError: If ``data`` or ``associated_data`` is larger
than 2\ :sup:`32` - 1 bytes.

.. method:: decrypt(nonce, data, associated_data)

Decrypts the ``data`` and authenticates the ``associated_data``. If you
called encrypt with ``associated_data`` you must pass the same
``associated_data`` in decrypt or the integrity check will fail.

:param nonce: A 12-byte value.
:type nonce: :term:`bytes-like`
:param data: The data to decrypt (with tag appended).
:type data: :term:`bytes-like`
:param associated_data: Additional data to authenticate. Can be
``None`` if none was passed during encryption.
:type associated_data: :term:`bytes-like`
:returns bytes: The original plaintext.
:raises cryptography.exceptions.InvalidTag: If the authentication tag
doesn't validate this exception will be raised. This will occur
when the ciphertext has been changed, but will also occur when the
key, nonce, or associated data are wrong.

.. class:: AESOCB3(key)

.. versionadded:: 36.0.0
Expand Down
17 changes: 17 additions & 0 deletions src/cryptography/hazmat/bindings/_rust/openssl/aead.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,20 @@ class AESOCB3:
data: bytes,
associated_data: bytes | None,
) -> bytes: ...

class AESGCMSIV:
def __init__(self, key: bytes) -> None: ...
@staticmethod
def generate_key(key_size: int) -> bytes: ...
def encrypt(
self,
nonce: bytes,
data: bytes,
associated_data: bytes | None,
) -> bytes: ...
def decrypt(
self,
nonce: bytes,
data: bytes,
associated_data: bytes | None,
) -> bytes: ...
2 changes: 2 additions & 0 deletions src/cryptography/hazmat/primitives/ciphers/aead.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@
"ChaCha20Poly1305",
"AESCCM",
"AESGCM",
"AESGCMSIV",
"AESOCB3",
"AESSIV",
]

AESSIV = rust_openssl.aead.AESSIV
AESOCB3 = rust_openssl.aead.AESOCB3
AESGCMSIV = rust_openssl.aead.AESGCMSIV


class ChaCha20Poly1305:
Expand Down
3 changes: 3 additions & 0 deletions src/rust/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ fn main() {
if version >= 0x3_00_00_00_0 {
println!("cargo:rustc-cfg=CRYPTOGRAPHY_OPENSSL_300_OR_GREATER");
}
if version >= 0x3_02_00_00_0 {
println!("cargo:rustc-cfg=CRYPTOGRAPHY_OPENSSL_320_OR_GREATER");
}
}

if let Ok(version) = env::var("DEP_OPENSSL_LIBRESSL_VERSION_NUMBER") {
Expand Down
110 changes: 110 additions & 0 deletions src/rust/src/backend/aead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,11 +410,121 @@ impl AesOcb3 {
}
}

#[pyo3::prelude::pyclass(
frozen,
module = "cryptography.hazmat.bindings._rust.openssl.aead",
name = "AESGCMSIV"
)]
struct AesGcmSiv {
ctx: EvpCipherAead,
}

#[pyo3::prelude::pymethods]
impl AesGcmSiv {
#[new]
fn new(py: pyo3::Python<'_>, key: pyo3::Py<pyo3::PyAny>) -> CryptographyResult<AesGcmSiv> {
let key_buf = key.extract::<CffiBuf<'_>>(py)?;
let cipher_name = match key_buf.as_bytes().len() {
16 => "aes-128-gcm-siv",
24 => "aes-192-gcm-siv",
32 => "aes-256-gcm-siv",
_ => {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err(
"AES-GCM-SIV key must be 128, 192 or 256 bits.",
),
))
}
};

cfg_if::cfg_if! {
if #[cfg(not(CRYPTOGRAPHY_OPENSSL_320_OR_GREATER))] {
let _ = cipher_name;
Err(CryptographyError::from(
exceptions::UnsupportedAlgorithm::new_err((
"AES-GCM-SIV is not supported by this version of OpenSSL",
exceptions::Reasons::UNSUPPORTED_CIPHER,
)),
))
} else {
if cryptography_openssl::fips::is_enabled() {
return Err(CryptographyError::from(
exceptions::UnsupportedAlgorithm::new_err((
"AES-GCM-SIV is not supported by this version of OpenSSL",
exceptions::Reasons::UNSUPPORTED_CIPHER,
)),
));
}
let cipher = openssl::cipher::Cipher::fetch(None, cipher_name, None)?;
Ok(AesGcmSiv {
ctx: EvpCipherAead::new(&cipher, key_buf.as_bytes(), 16, false)?,
})
}
}
}

#[staticmethod]
fn generate_key(py: pyo3::Python<'_>, bit_length: usize) -> CryptographyResult<&pyo3::PyAny> {
if bit_length != 128 && bit_length != 192 && bit_length != 256 {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err("bit_length must be 128, 192, or 256"),
));
}

Ok(types::OS_URANDOM.get(py)?.call1((bit_length / 8,))?)
}

#[pyo3(signature = (nonce, data, associated_data))]
fn encrypt<'p>(
&self,
py: pyo3::Python<'p>,
nonce: CffiBuf<'_>,
data: CffiBuf<'_>,
associated_data: Option<CffiBuf<'_>>,
) -> CryptographyResult<&'p pyo3::types::PyBytes> {
let nonce_bytes = nonce.as_bytes();
let data_bytes = data.as_bytes();
let aad = associated_data.map(Aad::Single);

if data_bytes.is_empty() {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err("data must not be zero length"),
));
};
if nonce_bytes.len() != 12 {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err("Nonce must be 12 bytes long"),
));
}
self.ctx.encrypt(py, data_bytes, aad, Some(nonce_bytes))
}

#[pyo3(signature = (nonce, data, associated_data))]
fn decrypt<'p>(
&self,
py: pyo3::Python<'p>,
nonce: CffiBuf<'_>,
data: CffiBuf<'_>,
associated_data: Option<CffiBuf<'_>>,
) -> CryptographyResult<&'p pyo3::types::PyBytes> {
let nonce_bytes = nonce.as_bytes();
let aad = associated_data.map(Aad::Single);
if nonce_bytes.len() != 12 {
return Err(CryptographyError::from(
pyo3::exceptions::PyValueError::new_err("Nonce must be 12 bytes long"),
));
}
self.ctx
.decrypt(py, data.as_bytes(), aad, Some(nonce_bytes))
}
}

pub(crate) fn create_module(py: pyo3::Python<'_>) -> pyo3::PyResult<&pyo3::prelude::PyModule> {
let m = pyo3::prelude::PyModule::new(py, "aead")?;

m.add_class::<AesSiv>()?;
m.add_class::<AesOcb3>()?;
m.add_class::<AesGcmSiv>()?;

Ok(m)
}
Loading

0 comments on commit e3d316f

Please sign in to comment.