# Cryptography

---

# Using Cryptography from Rust

_Peios / Developing for Peios / Cryptography_

> Generate keys, sign and verify, and protect a private key at rest with the peios-crypto crate.

Use the `peios-crypto` crate whenever Peios-authored Rust code needs
cryptography. It offers keys, signatures, passphrase sealing for keys at
rest, and the building blocks of random bytes, SHA-2 digests and HMAC.

The crate's choices are deliberately limited. You pick from a short list of
key types and signature schemes rather than supplying parameters, so a
weak or mismatched combination can't be expressed. Secret bytes are wiped
from memory when dropped and never appear in `Debug` output.

## Before you start

- Add `peios-crypto` from the peios-rs repository to your `Cargo.toml`.
- Handle `Error::PolicyRejected`. Peios crypto policy can refuse an
  algorithm on a particular machine. peios-crypto 0.1 doesn't enforce the
  policy and never returns this error; versions that enforce it keep the
  same API.

## Generate a key and sign

1. Generate a key with one of the `KeyAlgorithm` choices:

   ```rust
   use peios_crypto::{KeyAlgorithm, PrivateKey, Signer};

   let key = PrivateKey::generate(KeyAlgorithm::EcdsaP256)?;
   ```

2. Sign with the key's default scheme. Each key type has one that suits
   it, so you don't need to choose a hash or padding:

   ```rust
   let scheme = key.algorithm().default_signature_scheme();
   let signature = key.sign(scheme, b"message")?;
   ```

3. Give the public key to whoever verifies, as a DER
   `SubjectPublicKeyInfo`:

   ```rust
   let spki = key.public_key().spki();
   ```

Write code that signs against the `Signer` trait rather than `PrivateKey`.
A key held in hardware implements the same trait, so the code works
unchanged when the key moves out of process memory.

## Verify a signature

Load the public key and verify with the scheme the signer used:

```rust
use peios_crypto::{PublicKey, SignatureScheme};

let public = PublicKey::from_spki(&spki)?;
public.verify(SignatureScheme::EcdsaSha256, b"message", &signature)?;
```

`PublicKey::from_spki` accepts only the canonical DER encoding of a key
type Peios offers. A bare RSA key, a raw EC point or a compressed point is
refused with `Error::InvalidKey`.

## Verify a signature made by other software

Signatures from other software, such as the signature on a certificate
request, come in more combinations than Peios makes itself. OpenSSL, for
example, signs with SHA-256 whatever the curve. Use `VerifyingKey` for
these:

```rust
use peios_crypto::digest::Algorithm as Hash;
use peios_crypto::{VerificationAlgorithm, VerifyingKey};

let key = VerifyingKey::from_spki(&spki)?;
key.verify(VerificationAlgorithm::Ecdsa(Hash::Sha256), message, &signature)?;
```

`VerifyingKey` accepts ECDSA P-256 and P-384 keys, with compressed points,
and RSA keys from 2048 to 8192 bits. Any SHA-2 hash can be used with
either curve. RSA-PSS signatures verify only when their salt is as long as
their hash. SHA-1 isn't offered.

A `VerifyingKey` can only verify. To sign, use a `PrivateKey`.

## Protect a private key at rest

Seal the key's PKCS #8 encoding under a passphrase, and store the result:

```rust
use peios_crypto::{open_with_passphrase, seal_with_passphrase};

let pkcs8 = key.to_pkcs8()?;
let sealed = seal_with_passphrase(pkcs8.expose(), passphrase.expose())?;
```

To use the key again, open the blob and load it:

```rust
let pkcs8 = open_with_passphrase(&sealed, passphrase.expose())?;
let key = PrivateKey::from_pkcs8(pkcs8.expose())?;
```

Sealing derives a key from the passphrase with Argon2id, using 64 MiB of
memory, and encrypts with AES-256-GCM. The work makes each guess of the
passphrase expensive, but it can't make a weak passphrase strong. The
crate sets no minimum, so check the passphrase's strength in your program
before sealing anything valuable, such as a certificate authority's key.

Keep passphrases in a `Secret` too, as these examples do, so that they're
wiped from memory when you're finished with them.

## Export a key with its certificates

To hand a key and its certificate chain to other software, such as a
phone or a Windows machine, write them as a PKCS #12 file:

```rust
use peios_crypto::pkcs12;

let p12 = pkcs12::write(&key, &certificate, &[&issuer], Some("Jack's iPhone"), passphrase)?;
```

The file uses the format OpenSSL 3 writes by default: AES-256 encryption
under keys derived with PBKDF2-HMAC-SHA256, and an HMAC-SHA256 check over
the whole file. Current OpenSSL, Windows 10 version 1709 and later,
Firefox, iOS 18 and later, and macOS 15 and later can import it. Older
Apple systems need a weaker legacy format, which peios-crypto doesn't
write.

The certificate has to be the key's own, and the passphrase can't be
empty; otherwise `pkcs12::write` returns `Error::InvalidInput`.

## Check the result

Opening a sealed blob with the wrong passphrase fails with
`Error::WrongPassphraseOrDamaged`. That error also covers a blob that was
altered or damaged, deliberately: distinguishing the two would help someone
guessing passphrases more than it helps you.

## See also

- [Using the SDK from Rust](/peios/developing-for-peios/sdk-basics/using-the-sdk-from-rust.md)

---

# Using the OpenSSL-Compatible Libraries

_Peios / Developing for Peios / Cryptography_

> Build C programs and aws-lc-rs crates against libpcrypto and libpssl, the Peios libraries with OpenSSL's API.

Peios provides cryptography and TLS through two libraries with OpenSSL's
API: libpcrypto, for cryptography, and libpssl, for TLS. Software written
for OpenSSL builds against them with its source unchanged, and Rust
crates built on aws-lc-rs, such as rustls, can use them in place of a copy
of their own.

Both libraries are built from AWS-LC, Amazon's cryptography library, and
provide the API AWS-LC does. They link AWS-LC in and export each function
under its OpenSSL name, so that every call a program makes passes through
one place where Peios can apply its crypto policy.

For new Rust code written for Peios, use the `peios-crypto` crate instead;
see [Using Cryptography from Rust](/peios/developing-for-peios/cryptography/using-cryptography-from-rust.md).

## Before you start

- Build libpcrypto and libpssl from the peios-crypto repository with
  `pekit build pcrypto`, and install the tree it gives under `/usr`. Peios
  doesn't ship them as a package yet.
- Install libpeios, which libpcrypto loads to read the machine's crypto
  policy. A static link needs `-lpeios`, which pkg-config's `--static`
  gives. A cross linker needs `-Wl,-rpath-link` to the directory holding
  `libpeios.so.0`.
- Install a C compiler and pkg-config.
- Expect Peios crypto policy to apply to these libraries' callers. The
  current libraries apply it when a program computes a digest or a MAC
  (HMAC, CMAC, Poly1305, or SipHash), starts or keys a cipher or an AEAD,
  derives a key, encrypts or decrypts a private key, PEM file, PKCS #12
  file or PKCS #7 message, generates or uses a public key, verifies a
  signature in a certificate, OCSP response or PKCS #7 message, or
  finishes a TLS handshake. Data that names its own algorithm, such as an
  encrypted PKCS #12 file, is checked as it's read, before it's
  decrypted. Each process applies the machine's crypto policy, which it
  reads once, at its first call: its floor, which no machine can loosen,
  its thresholds, and the exceptions granted to the program. See
  [How Crypto Policy Works](/peios/using-peios/crypto-policy/overview.md).
  Two calls still go straight to AWS-LC: `EVP_CIPHER_CTX_set_key_length`
  and `EVP_CIPHER_CTX_ctrl`, which can change a cipher's key length or
  parameters after the cipher was checked.
- Expect TLS to be checked once each handshake has negotiated, before any
  data is sent or received on it: its version, cipher suite, key-exchange
  group, keys, signatures, and the peer's certificate chain. If policy
  refuses any of them, the connection fails with an `insufficient_security`
  alert, as if the handshake itself had failed, and every later call on it
  fails too. A call such as `SSL_write` that runs the handshake itself
  checks it before sending anything. TLS 1.3's early data isn't checked: a
  client sends it before the handshake negotiates anything, using a
  session that an earlier handshake negotiated.

## Build a C program

1. Include OpenSSL's headers as usual. This program prints the library's
   version and the SHA-256 digest of `abc`:

   ```c
   #include <stdio.h>

   #include <openssl/crypto.h>
   #include <openssl/sha.h>

   int main(void) {
       unsigned char digest[SHA256_DIGEST_LENGTH];
       SHA256((const unsigned char *)"abc", 3, digest);
       printf("%s\n", OpenSSL_version(OPENSSL_VERSION));
       for (size_t i = 0; i < sizeof(digest); i++) {
           printf("%02x", digest[i]);
       }
       printf("\n");
       return 0;
   }
   ```

2. Save it as `digest.c`, and compile it with the flags pkg-config gives
   for `libcrypto`:

   ```sh
   cc -o digest digest.c $(pkg-config --cflags --libs libcrypto)
   ```

   For a program that uses TLS, ask for `openssl` instead, which gives
   both libraries.

A build that links `-lssl -lcrypto` without asking pkg-config works too:
`libssl.so` and `libcrypto.so` lead to libpssl and libpcrypto.

## Check the result

Run the program:

```sh
./digest
```

It prints AWS-LC's version and the digest:

```text
AWS-LC 5.15.0
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
```

## Build a Rust crate that uses aws-lc-rs

aws-lc-rs normally compiles its own copy of AWS-LC. Set
`AWS_LC_SYS_SYSTEM_DIR` when you build, and it uses libpcrypto instead:

```sh
AWS_LC_SYS_SYSTEM_DIR=/usr cargo build
```

aws-lc-rs reads the Rust bindings that libpcrypto installs at
`/usr/share/rust/aws_lc_bindings.rs`, and links `libcrypto.so`. The program
it builds loads libpcrypto when it runs, and contains no AWS-LC of its own.

## Differences from OpenSSL

AWS-LC provides OpenSSL 1.1.1's API, with some of OpenSSL 3's functions,
not all of OpenSSL 3. Expect to change a program that needs:

- **OpenSSL 3's providers, or engines loaded by name.** AWS-LC has no
  providers, and its algorithms are built in. Its `ENGINE` can only stand
  in for RSA and EC key operations, with methods the program supplies.
- **A newer OpenSSL version.** libpcrypto reports version 1.1.1 to
  pkg-config and in `OPENSSL_VERSION_NUMBER`, so a build that insists on
  OpenSSL 3 refuses it.
- **Elliptic curves of your own.** A key on a curve given by its
  parameters is accepted only if the curve is one of the named curves
  AWS-LC provides, such as P-256; any other curve is refused.
- **`PKCS12_create`'s defaults.** AWS-LC encrypts a PKCS #12 file's
  certificates with 40-bit RC2 unless told otherwise, and Peios crypto
  policy refuses it. Pass -1 as `cert_nid` to leave the certificates,
  which are public, unencrypted. Files that other software encrypted
  this way still read.

AWS-LC's porting documents, in its repository's `docs/porting` directory,
list the functions it leaves out and those that behave differently.

A call that Peios crypto policy refuses fails as any failed OpenSSL call
does, and leaves an error on the thread's error queue whose library is
`ERR_LIB_USER` and whose reason is 1000. Reading the policy and reporting
to cryptod leave `errno` as they found it.

A few functions can't report failure, or have callers that never check:
the low-level digest functions, such as `SHA256` and `MD5_Init`, the
low-level cipher keying functions, such as `AES_set_encrypt_key`, and
Poly1305's and SipHash's. When policy refuses one of those, the program
ends with a message naming the function, rather than carry on with a
digest or key that was never computed. Use the `EVP_` functions where a
refusal should be handled.

The libraries export only the API AWS-LC's headers declare. Functions
AWS-LC exports only for its own tests, such as its ML-KEM internals, aren't
available. Use only OpenSSL's names: libpcrypto also exports names
beginning `peios_awslc_`, which libpssl uses internally. They aren't part
of the API, and a program that calls them won't pass Peios crypto policy.
