| Title: | Cryptography Without System Dependencies |
|---|---|
| Description: | Cryptographic functions over raw vectors, including message digests of in-memory data, files and connections, keyed-hash message authentication codes (HMAC), Advanced Encryption Standard (AES) encryption, including authenticated encryption in Galois/Counter Mode (GCM), password-based key derivation (PBKDF2), RSA keys, signatures and encryption, elliptic-curve signatures and key agreement on the curves of the US National Institute of Standards and Technology (NIST) and on X25519, with keys read and written in the Privacy-Enhanced Mail (PEM) and Distinguished Encoding Rules (DER) encodings, constant-time comparison, random bytes from the operating system and hexadecimal encoding, backed by a bundled and pinned copy of the 'Mbed TLS' project's cryptography library, 'TF-PSA-Crypto' (<https://github.com/Mbed-TLS/TF-PSA-Crypto>). No system cryptographic library, 'Java' or 'Python' is required at install or run time. Algorithm names are matched exactly, and failures are reported as structured conditions. The same primitives, and secure erasure of native buffers, are published to other packages as a static archive and as a registered C interface, so that a package can call them from C without going through R. |
| Authors: | Pedro Baltazar [aut, cre, cph], The Mbed TLS Contributors [cph] (TF-PSA-Crypto, bundled in src/vendor/tf-psa-crypto), Adriaan de Jong [ctb, cph] (author of TF-PSA-Crypto's cipher and message-digest layers), Daniel King [ctb, cph] (author of TF-PSA-Crypto's ChaCha20, Poly1305 and ChaCha20-Poly1305 headers), Simon Tatham [ctb, cph] (author of the Arm-accelerated SHA-512 code, from PuTTY) |
| Maintainer: | Pedro Baltazar <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.1 |
| Built: | 2026-12-01 11:38:17 UTC |
| Source: | https://github.com/pedrobtz/zucrypt |
These functions provide confidentiality only. They do not authenticate anything. Ciphertext produced here can be altered by anyone who can reach it, and decryption will return the altered plaintext without complaint. Detecting that is your job, or use an authenticated format. If you must authenticate CBC yourself, the minimum is encrypt-then-MAC, done in full:
compute crypt_hmac() over the IV and the ciphertext,
c(iv, ciphertext). A MAC over the ciphertext alone lets anyone change
the IV, and with it the first plaintext block, without the tag noticing;
use a MAC key independent of the encryption key;
verify the tag with crypt_equal() before decrypting, and do not
decrypt at all if it fails.
They also add and strip no padding. The input length must already be a multiple of 16 bytes.
These are interoperability tools, for reading and writing formats that specify unauthenticated CBC – the Office encryption profiles are the reason they exist. They are not a general-purpose way to encrypt something of your own; that needs an authenticated construction, a nonce policy and a key derivation step, none of which this package provides.
crypt_aes_cbc_encrypt_nopad(data, key, iv) crypt_aes_cbc_decrypt_nopad(data, key, iv)crypt_aes_cbc_encrypt_nopad(data, key, iv) crypt_aes_cbc_decrypt_nopad(data, key, iv)
data |
A raw vector whose length is a multiple of 16 bytes. |
key |
A raw vector of exactly 16, 24 or 32 bytes, selecting AES-128, AES-192 or AES-256. This is a key, not a password. |
iv |
A raw vector of exactly 16 bytes, the initialisation vector. For encryption it must be unpredictable and must not be reused with the same key; for decryption it is whatever the format says it is. |
A raw vector the same length as data. data itself is never
modified.
AES runs on the CPU's AES instructions where it has them – AES-NI on x86,
the Cryptography Extension on 64-bit Arm under Linux and macOS – chosen
at run time, and falls back to a software implementation where it does
not. On Arm under other systems, where the extension cannot be detected,
the software implementation is the one built. crypt_info() says
which one this machine uses, in build_flags$aes_implementation.
The software fallback reads lookup tables at addresses that depend on the
key and the data. The backend's own security policy warns that an attacker
who can observe cache timing – another process on the same machine, or,
with enough precision, the network – can recover the key from that. If
aes_implementation is "software" and such an attacker is in your
threat model, do not use these functions for secrets that matter. Every
implementation produces the same bytes; only this exposure differs.
Each call starts from iv and treats data as one continuous CBC stream.
A format that restarts the chaining at segment boundaries – which is what
the Office Agile profiles do – is expressed as one call per segment, each
with that segment's own IV. The C interface exposes the running chaining
state directly for consumers that need finer control; see zucrypt_c_api.
key <- as.raw(rep(0x2b, 16)) iv <- as.raw(seq.int(0, 15)) plaintext <- charToRaw("sixteen bytes!! and sixteen more") ciphertext <- crypt_aes_cbc_encrypt_nopad(plaintext, key, iv) ciphertext identical(crypt_aes_cbc_decrypt_nopad(ciphertext, key, iv), plaintext) # Authentication is separate, and is not optional. The tag covers the IV # as well as the ciphertext, under a key of its own. mac_key <- as.raw(rep(0x5c, 32)) tag <- crypt_hmac(c(iv, ciphertext), mac_key) # The receiver checks the tag first, and decrypts only if it matches. crypt_equal(tag, crypt_hmac(c(iv, ciphertext), mac_key)) # A changed IV would alter the first plaintext block. Because the tag # covers the IV, the change is caught before anything is decrypted. tampered_iv <- iv tampered_iv[1] <- xor(tampered_iv[1], as.raw(1)) crypt_equal(tag, crypt_hmac(c(tampered_iv, ciphertext), mac_key))key <- as.raw(rep(0x2b, 16)) iv <- as.raw(seq.int(0, 15)) plaintext <- charToRaw("sixteen bytes!! and sixteen more") ciphertext <- crypt_aes_cbc_encrypt_nopad(plaintext, key, iv) ciphertext identical(crypt_aes_cbc_decrypt_nopad(ciphertext, key, iv), plaintext) # Authentication is separate, and is not optional. The tag covers the IV # as well as the ciphertext, under a key of its own. mac_key <- as.raw(rep(0x5c, 32)) tag <- crypt_hmac(c(iv, ciphertext), mac_key) # The receiver checks the tag first, and decrypts only if it matches. crypt_equal(tag, crypt_hmac(c(iv, ciphertext), mac_key)) # A changed IV would alter the first plaintext block. Because the tag # covers the IV, the change is caught before anything is decrypted. tampered_iv <- iv tampered_iv[1] <- xor(tampered_iv[1], as.raw(1)) crypt_equal(tag, crypt_hmac(c(tampered_iv, ciphertext), mac_key))
crypt_aes_gcm_encrypt() encrypts and authenticates data, and
crypt_aes_gcm_decrypt() checks the authentication tag before it returns
anything. This is AES in Galois/Counter Mode (NIST SP 800-38D) with RFC
5116's contract: a 12-byte nonce, a 16-byte tag, and optional associated
data that is authenticated but not encrypted.
Decryption either returns the plaintext of an untouched message or signals
zucrypt_auth_error and returns nothing. A changed ciphertext, tag, nonce
or associated data, a truncated tag and a wrong key all fail the same way.
crypt_aes_gcm_encrypt(data, key, iv = crypt_rand_bytes(12), aad = NULL) crypt_aes_gcm_decrypt( data, key, iv = attr(data, "iv"), tag = attr(data, "tag"), aad = NULL )crypt_aes_gcm_encrypt(data, key, iv = crypt_rand_bytes(12), aad = NULL) crypt_aes_gcm_decrypt( data, key, iv = attr(data, "iv"), tag = attr(data, "tag"), aad = NULL )
data |
A raw vector: the plaintext to encrypt, or the ciphertext to decrypt. Character input is not accepted. |
key |
A raw vector of exactly 16, 24 or 32 bytes, selecting AES-128,
AES-192 or AES-256. This is a key, not a password; |
iv |
The nonce: a raw vector of exactly 12 bytes. Encryption draws a
fresh one with |
aad |
Additional authenticated data, as a raw vector, or |
tag |
The 16-byte authentication tag. Decryption reads it from the
ciphertext's |
crypt_aes_gcm_encrypt() returns the ciphertext, a raw vector the
length of data, with attributes iv (the nonce) and tag (the
authentication tag). Store or send all three. crypt_aes_gcm_decrypt()
returns the plaintext as a plain raw vector.
Two messages encrypted under one key with one nonce disclose the XOR of their plaintexts. They also let anyone who sees both forge tags for that key. The default nonce is 12 random bytes, which is safe for up to about 2^32 messages per key. Pass your own only when a protocol specifies it, and then make sure it never repeats.
An authentication failure signals zucrypt_auth_error and returns no
plaintext. A key or nonce of the wrong length is zucrypt_bad_length, and
a missing or non-raw argument is zucrypt_invalid_argument.
The names and argument order follow openssl::aes_gcm_encrypt() and
openssl::aes_gcm_decrypt(), and the ciphertext bytes are the same. The
behaviour differs on purpose. openssl's encryption returns no tag, and
its decryption returns altered plaintext without an error. Here the tag
is returned, and decryption fails on any alteration, so these functions
are not drop-in replacements.
AES runs on the CPU's AES instructions where it has them, and on a
table-based software fallback otherwise; crypt_info() reports which, in
build_flags$aes_implementation. On the fallback both AES and GHASH, the
authentication half of GCM, read tables at addresses that depend on the
key. See crypt_aes_cbc_nopad for what that exposes.
crypt_rand_bytes() for keys and nonces, crypt_pbkdf2() to
derive a key from a password.
key <- crypt_rand_bytes(32) sealed <- crypt_aes_gcm_encrypt(charToRaw("attack at dawn"), key) sealed rawToChar(crypt_aes_gcm_decrypt(sealed, key)) # Associated data is authenticated, not encrypted. header <- charToRaw("message 7") sealed <- crypt_aes_gcm_encrypt(charToRaw("hi"), key, aad = header) rawToChar(crypt_aes_gcm_decrypt(sealed, key, aad = header)) # Any change is caught, and nothing is decrypted. sealed[1] <- xor(sealed[1], as.raw(1)) try(crypt_aes_gcm_decrypt(sealed, key, aad = header))key <- crypt_rand_bytes(32) sealed <- crypt_aes_gcm_encrypt(charToRaw("attack at dawn"), key) sealed rawToChar(crypt_aes_gcm_decrypt(sealed, key)) # Associated data is authenticated, not encrypted. header <- charToRaw("message 7") sealed <- crypt_aes_gcm_encrypt(charToRaw("hi"), key, aad = header) rawToChar(crypt_aes_gcm_decrypt(sealed, key, aad = header)) # Any change is caught, and nothing is decrypted. sealed[1] <- xor(sealed[1], as.raw(1)) try(crypt_aes_gcm_decrypt(sealed, key, aad = header))
Generate, build and use keys on the NIST curves P-256, P-384 and P-521
and on Curve25519, with openssl's names and arguments under a crypt_
prefix.
crypt_ec_keygen() generates a key on a NIST curve, for ECDSA
signatures with crypt_signature_create() and for key agreement with
crypt_ec_dh().
crypt_ec_key() builds one from its coordinates, as a JSON Web Key
carries them, and as.list() takes one apart again.
crypt_x25519_keygen(), crypt_read_x25519_key() and
crypt_read_x25519_pubkey() make X25519 keys (RFC 7748), and
crypt_x25519_diffie_hellman() computes their shared secret.
crypt_ecdsa_parse() and crypt_ecdsa_write() convert an ECDSA
signature between DER, as crypt_signature_create() returns it, and its
integers r and s.
Keys of these types are read and written by crypt_read_key(),
crypt_write_pem() and the other key functions, as for RSA.
A Diffie-Hellman result is a shared secret, not a key: derive keys from it with a key-derivation function. A peer key on another curve, a point that is not on the curve, and an X25519 peer that yields an all-zero secret are refused.
crypt_ec_keygen(curve = c("P-256", "P-384", "P-521")) crypt_ec_key(curve, x, y, d = NULL) crypt_ec_dh(key, peerkey, password = NULL) crypt_x25519_keygen() crypt_read_x25519_key(x) crypt_read_x25519_pubkey(x) crypt_x25519_diffie_hellman(key, pubkey) crypt_ecdsa_parse(sig) crypt_ecdsa_write(r, s)crypt_ec_keygen(curve = c("P-256", "P-384", "P-521")) crypt_ec_key(curve, x, y, d = NULL) crypt_ec_dh(key, peerkey, password = NULL) crypt_x25519_keygen() crypt_read_x25519_key(x) crypt_read_x25519_pubkey(x) crypt_x25519_diffie_hellman(key, pubkey) crypt_ecdsa_parse(sig) crypt_ecdsa_write(r, s)
curve |
|
x, y
|
The public point's coordinates, as raw big-endian integers.
For an X25519 key, |
d |
The private scalar, as a raw big-endian integer, or |
key |
A private key. |
peerkey, pubkey
|
The other party's public key, or a private key whose public half is used. |
password |
Not supported; must be |
sig |
An ECDSA signature in DER. |
r, s
|
The signature's integers, as raw big-endian vectors. |
crypt_ec_keygen(), crypt_x25519_keygen(),
crypt_read_x25519_key() and crypt_ec_key() with d return a key of
class c("crypt_key", "crypt_ecdsa") or c("crypt_key", "crypt_x25519"); the public forms are class crypt_pubkey. The
Diffie-Hellman functions return the shared secret as a raw vector: 32,
48 or 66 bytes for the NIST curves, 32 for X25519. crypt_ecdsa_parse()
returns list(r, s) and crypt_ecdsa_write() the DER signature.
as.list() on an EC key gives data with curve, x, y and, for a
private key, secret; on an X25519 key, x and, private, d.
crypt_ecdsa_parse() returns raw vectors rather than bignums, and
as.list() gives coordinates as raw vectors. crypt_ecdsa_parse() reads
strict DER: it refuses bytes after the signature's SEQUENCE, which
openssl::ecdsa_parse() ignores, as well as the negative, non-minimal
and truncated encodings both refuse. There is no Ed25519: the
bundled library has no EdDSA. There is no default key.
alice <- crypt_ec_keygen("P-256") bob <- crypt_ec_keygen("P-256") identical(crypt_ec_dh(alice, bob$pubkey), crypt_ec_dh(bob, alice$pubkey)) sig <- crypt_signature_create(charToRaw("hi"), crypt_sha256, alice) crypt_signature_verify(charToRaw("hi"), sig, crypt_sha256, alice$pubkey) str(crypt_ecdsa_parse(sig)) a <- crypt_x25519_keygen() b <- crypt_x25519_keygen() identical(crypt_x25519_diffie_hellman(a, b$pubkey), crypt_x25519_diffie_hellman(b, a$pubkey))alice <- crypt_ec_keygen("P-256") bob <- crypt_ec_keygen("P-256") identical(crypt_ec_dh(alice, bob$pubkey), crypt_ec_dh(bob, alice$pubkey)) sig <- crypt_signature_create(charToRaw("hi"), crypt_sha256, alice) crypt_signature_verify(charToRaw("hi"), sig, crypt_sha256, alice$pubkey) str(crypt_ecdsa_parse(sig)) a <- crypt_x25519_keygen() b <- crypt_x25519_keygen() identical(crypt_x25519_diffie_hellman(a, b$pubkey), crypt_x25519_diffie_hellman(b, a$pubkey))
Compares in time that does not depend on the contents of the buffers. Use it whenever one side is a secret: an authentication tag, a password verifier, a derived key.
crypt_equal(x, y)crypt_equal(x, y)
x, y
|
Raw vectors. |
TRUE if the vectors have the same length and the same contents,
otherwise FALSE.
Vectors of different lengths return FALSE immediately, without comparing
anything. Hiding a length difference is not something a comparison function
can do, and pretending otherwise would be worse than saying so: if the
length of your secret is itself secret, compare digests of the values
rather than the values.
a <- crypt_hash(charToRaw("message")) b <- crypt_hash(charToRaw("message")) crypt_equal(a, b) crypt_equal(a, crypt_hash(charToRaw("different"))) # Different lengths are simply not equal. crypt_equal(a, raw(0))a <- crypt_hash(charToRaw("message")) b <- crypt_hash(charToRaw("message")) crypt_equal(a, b) crypt_equal(a, crypt_hash(charToRaw("different"))) # Different lengths are simply not equal. crypt_equal(a, raw(0))
Hashes a raw vector, or everything a connection yields, with one of the digest algorithms this build provides.
crypt_hash(data, algorithm = "sha256")crypt_hash(data, algorithm = "sha256")
data |
A raw vector, or a connection to read to its end (see
"Files and connections" below). Character input is never accepted: this
package does not guess a text encoding and never treats a string as a
file name. Convert deliberately with |
algorithm |
A single algorithm name: one of |
A raw vector of the digest, 20 bytes for "sha1" and 32, 48 or 64
for the SHA-2 family. Hex formatting is an explicit step at the call
site, with crypt_hex(); see the examples.
"sha256" is the default and the right answer unless something external
requires otherwise. "sha1" is available because document formats specify
it – notably the Office encryption profiles this package exists to
support – and it is not collision resistant. Do not select it for
anything new.
A connection is read in 1 MiB chunks, so a file of any size is hashed
without being held in memory, and the call can be interrupted. Pass an
unopened connection, such as file(path), and it is opened in binary mode
("rb") and closed again afterwards; pass one you have already opened and
it is read from where it stands to its end, and left open.
An open connection must be in binary mode. A text-mode connection can
re-encode or translate line endings before the bytes arrive, which would
hash something other than the file, so it is refused with
zucrypt_invalid_argument. A connection that cannot be opened signals
zucrypt_connection_error, as does a non-blocking connection that runs out
of data before its end, which is refused rather than hashed short. An
error while reading is R's own.
What is hashed is what the connection yields: gzfile() gives the
decompressed bytes, file() the bytes on disk, and url() the body as
it downloads, so a remote file is hashed without being saved first.
crypt_hmac() for a keyed digest, crypt_equal() for comparing
digests without leaking timing information, crypt_hex() for hex.
digest <- crypt_hash(charToRaw("the quick brown fox")) digest # Hex, when you need it, is an explicit conversion. crypt_hex(digest) # The digest of empty input is well defined. crypt_hash(raw(0)) crypt_hash(charToRaw("abc"), "sha512") # A file, read in chunks rather than all at once. path <- tempfile() writeBin(charToRaw("abc"), path) identical(crypt_hash(file(path)), crypt_hash(charToRaw("abc"))) unlink(path)digest <- crypt_hash(charToRaw("the quick brown fox")) digest # Hex, when you need it, is an explicit conversion. crypt_hex(digest) # The digest of empty input is well defined. crypt_hash(raw(0)) crypt_hash(charToRaw("abc"), "sha512") # A file, read in chunks rather than all at once. path <- tempfile() writeBin(charToRaw("abc"), path) identical(crypt_hash(file(path)), crypt_hash(charToRaw("abc"))) unlink(path)
Converts a raw vector to one lower-case hexadecimal string, two digits per
byte, with no separators and no prefix: the form sha256sum prints and
most formats store. The conversion runs in C, so for a short digest it
costs far less than the hash itself.
crypt_hex(x)crypt_hex(x)
x |
A raw vector, at most 2^30 - 1 bytes long (a longer result would exceed R's limit on the length of a single string). |
Hex is an explicit step at the call site rather than an option on
crypt_hash() and crypt_hmac(), so the digest functions return one type
and a caller who wants text says so. It works on any bytes: a digest, a
MAC, a key you need to print for a test.
A character vector of length one, 2 * length(x) characters long.
crypt_hex(raw(0)) is "".
crypt_hash() and crypt_hmac(), whose results this is usually
applied to.
crypt_hex(crypt_hash(charToRaw("abc"))) crypt_hex(as.raw(c(0x00, 0x0f, 0xa0, 0xff))) crypt_hex(raw(0))crypt_hex(crypt_hash(charToRaw("abc"))) crypt_hex(as.raw(c(0x00, 0x0f, 0xa0, 0xff))) crypt_hex(raw(0))
Computes a keyed message authentication code (RFC 2104) over a raw vector, or over everything a connection yields.
crypt_hmac(data, key, algorithm = "sha256")crypt_hmac(data, key, algorithm = "sha256")
data |
A raw vector, or a connection to read to its end (see
"Files and connections" below). Character input is never accepted: this
package does not guess a text encoding and never treats a string as a
file name. Convert deliberately with |
key |
A raw vector holding the key. Any length is accepted, including zero, as the standard specifies. This is a key, not a password: deriving a key from a password is the caller's responsibility and is not something this package does for you. |
algorithm |
A single algorithm name: one of |
A raw vector the length of the underlying digest.
data may be a connection, read in chunks exactly as for crypt_hash();
see "Files and connections" there. The key is always a raw vector.
Compare with crypt_equal(), never with identical() or ==. An ordinary
comparison stops at the first differing byte, and the time it takes is
therefore a measurement of how much of the expected value an attacker has
guessed.
key <- as.raw(rep(0x0b, 20)) tag <- crypt_hmac(charToRaw("Hi There"), key) tag # Verification, done properly. crypt_equal(tag, crypt_hmac(charToRaw("Hi There"), key))key <- as.raw(rep(0x0b, 20)) tag <- crypt_hmac(charToRaw("Hi There"), key) tag # Verification, done properly. crypt_equal(tag, crypt_hmac(charToRaw("Hi There"), key))
Describes the installed package: its version, the C ABI it publishes, the algorithms it provides, and the vendored cryptographic backend it was compiled against.
crypt_info()crypt_info()
Everything here is read from the compiled library, never from
tools/vendor/manifest.tsv. The manifest is maintainer tooling and is not
installed, so it could only describe the tree a build was made from –
which is the one thing a user holding a binary package cannot check.
A list with elements:
versionthe zucrypt package version, as a package_version.
abi_versionthe C ABI version published to LinkingTo
consumers, as an integer: 1. The archive's ABI is frozen as ABI 1
from 0.1.0; see zucrypt_c_api.
algorithmsthe digest algorithms this build provides, which
is exactly the set crypt_hash() and crypt_hmac() accept.
vendoreda data frame with one row per vendored source, giving
its source name and the version the compiled library reports.
build_flagsa named list: random_backend, the
operating-system random source compiled in; aes_implementation,
which AES this machine runs – "aesni" or "aesce" on a CPU with
AES instructions, "software" otherwise, decided at run time; and
hardware_acceleration, TRUE when that is a hardware path. See
the "Side channels" section of crypt_aes_cbc_nopad for why it
matters.
info <- crypt_info() info$version info$algorithms info$vendoredinfo <- crypt_info() info$version info$algorithms info$vendored
crypt_pbkdf2() stretches a password into a key with PBKDF2 (RFC 8018,
section 5.2), using HMAC with the chosen digest as the pseudorandom
function.
crypt_pbkdf2(password, salt, iterations, length = 32, algorithm = "sha256")crypt_pbkdf2(password, salt, iterations, length = 32, algorithm = "sha256")
password |
The password, as a raw vector. A string is not accepted,
because its bytes depend on an encoding: convert deliberately, for
example with |
salt |
The salt, as a raw vector. Use at least 16 random bytes from
|
iterations |
The iteration count, a whole number from 1 to
4294967295. It has no default, because the right value depends on the
digest, the hardware and the time you can afford. OWASP recommended
600,000 for |
length |
The number of bytes to derive, a whole number of at least 1. 32 gives an AES-256 key. |
algorithm |
The digest for the HMAC: |
PBKDF2 derives a key. It is not an encryption format and not a password storage format. The salt, the iteration count and the digest are yours to choose, store beside what the key protects, and supply again to derive the same key.
A raw vector of length bytes.
The time is proportional to iterations times the number of digest-sized
blocks in length, and the call cannot be interrupted. Bound
iterations before passing a value that came from untrusted input, such
as a file header.
An invalid argument is zucrypt_invalid_argument, and an unknown digest
is zucrypt_unsupported_algorithm.
crypt_aes_gcm_encrypt(), which takes the key this derives.
salt <- crypt_rand_bytes(16) key <- crypt_pbkdf2(charToRaw("correct horse"), salt, iterations = 10000) key # RFC 6070, test case 2. crypt_hex(crypt_pbkdf2(charToRaw("password"), charToRaw("salt"), iterations = 2, length = 20, algorithm = "sha1"))salt <- crypt_rand_bytes(16) key <- crypt_pbkdf2(charToRaw("correct horse"), salt, iterations = 10000) key # RFC 6070, test case 2. crypt_hex(crypt_pbkdf2(charToRaw("password"), charToRaw("salt"), iterations = 2, length = 20, algorithm = "sha1"))
Draws n bytes from the operating system's cryptographic random source:
rand_s on Windows, arc4random_buf on macOS and the BSDs, getrandom on
Linux with glibc 2.25 or later, and /dev/urandom elsewhere. Where the
kernel or a seccomp filter refuses getrandom (a kernel before 3.17), it
reads /dev/urandom instead. crypt_info() names the source in use, in
build_flags$random_backend. Use these bytes for keys, initialisation
vectors, nonces and salts.
crypt_rand_bytes(n = 1)crypt_rand_bytes(n = 1)
n |
The number of bytes: a single non-negative whole number. |
R's random number generator is never involved. set.seed() has no
effect on these bytes and they do not change .Random.seed, so drawing
them does not disturb a reproducible simulation running beside them. That
is deliberate: R's generator is seeded from the session and reproducible on
purpose, which is exactly what a key must not be.
The name, argument and default mirror openssl::rand_bytes(), so code
moving from openssl changes only the prefix.
A raw vector of length n.
A failure of the operating-system source raises an error of class
zucrypt_entropy_error. It never returns fewer bytes than asked for, and
never returns bytes from a source that reported failure. An invalid n is
zucrypt_invalid_argument.
crypt_aes_cbc_encrypt_nopad(), whose iv for encryption must be
unpredictable: crypt_rand_bytes(16) is one.
crypt_rand_bytes(16) # A 256-bit key, printed as hex. crypt_hex(crypt_rand_bytes(32)) # set.seed() does not repeat it. set.seed(1) a <- crypt_rand_bytes(8) set.seed(1) b <- crypt_rand_bytes(8) identical(a, b)crypt_rand_bytes(16) # A 256-bit key, printed as hex. crypt_hex(crypt_rand_bytes(32)) # set.seed() does not repeat it. set.seed(1) a <- crypt_rand_bytes(8) set.seed(1) b <- crypt_rand_bytes(8) identical(a, b)
crypt_signature_create() signs data with a private RSA or EC key, and
crypt_signature_verify() checks the signature with the public key.
crypt_rsa_encrypt() encrypts a short message to a public key, and
crypt_rsa_decrypt() decrypts it with the private key. The names,
arguments and defaults follow openssl, with pss and oaep_hash added.
A signature covers a digest: hash is applied to data and the digest is
signed, so hash = crypt_sha256 gives an RSA-SHA256 signature. With
hash = NULL, data must already be a SHA-1 or SHA-2 digest. PKCS#1
v1.5 signatures are deterministic. PSS signatures (pss = TRUE, RFC 8017
section 8.1) are randomised and use MGF1 with the same digest. The salt is
as long as the digest, or as long as fits when the key is too small for
that (a 1024-bit key with SHA-512 takes 62 bytes). Verification requires
that same length: a PSS signature with any other salt, such as the
longest that fits (PSS.MAX_LENGTH in Python's cryptography), is
refused.
With a key on P-256, P-384 or P-521 the signature is ECDSA, encoded in DER
as openssl encodes it; crypt_ecdsa_parse() gives its r and s.
ECDSA signatures are randomised unless deterministic = TRUE, which
derives the nonce from the key and digest as RFC 6979 specifies.
Verification accepts only the canonical DER encoding.
RSA encryption is for short secrets such as keys: a 2048-bit key with
OAEP over SHA-1 takes at most 214 bytes. OAEP (oaep = TRUE, RFC 8017
section 7.1) is the padding to use. oaep_hash picks the digest for both
its label hash and MGF1: "sha1", as openssl uses, or "sha256",
"sha384" or "sha512". PKCS#1 v1.5 padding (oaep = FALSE, the
openssl default) is legacy: a decryptor that reveals whether padding was
valid can be attacked to decrypt messages (Bleichenbacher, 1998). It is
here for formats that specify it.
crypt_signature_create( data, hash = crypt_sha1, key, password = NULL, pss = FALSE, deterministic = FALSE ) crypt_signature_verify(data, sig, hash = crypt_sha1, pubkey, pss = FALSE) crypt_rsa_encrypt(data, pubkey, oaep = FALSE, oaep_hash = "sha1") crypt_rsa_decrypt(data, key, password = NULL, oaep = FALSE, oaep_hash = "sha1")crypt_signature_create( data, hash = crypt_sha1, key, password = NULL, pss = FALSE, deterministic = FALSE ) crypt_signature_verify(data, sig, hash = crypt_sha1, pubkey, pss = FALSE) crypt_rsa_encrypt(data, pubkey, oaep = FALSE, oaep_hash = "sha1") crypt_rsa_decrypt(data, key, password = NULL, oaep = FALSE, oaep_hash = "sha1")
data |
A raw vector, or a path or connection to read one from. For
|
hash |
A digest function such as |
key |
A private key from |
password |
Not supported yet; must be |
pss |
|
deterministic |
|
sig |
The signature, a raw vector. |
pubkey |
A public key from |
oaep |
|
oaep_hash |
The OAEP digest: |
crypt_signature_create() returns the signature, a raw vector:
as long as the modulus for RSA, and DER of varying length for ECDSA.
crypt_signature_verify() returns TRUE, or
signals zucrypt_auth_error. crypt_rsa_encrypt() returns the
ciphertext and crypt_rsa_decrypt() the plaintext, as raw vectors.
A signature that does not verify, and a ciphertext that does not decrypt,
are zucrypt_auth_error, whatever the reason. A message too long for the
key is zucrypt_bad_length.
pss, deterministic and oaep_hash are additions. There is no default
key: openssl reads ~/.ssh. PKCS#1 v1.5 decryption of an invalid
ciphertext is an error here; OpenSSL 3 returns random bytes instead
(implicit rejection).
key <- crypt_rsa_keygen(2048) msg <- charToRaw("hello") sig <- crypt_signature_create(msg, crypt_sha256, key) crypt_signature_verify(msg, sig, crypt_sha256, key$pubkey) sig <- crypt_signature_create(msg, crypt_sha256, key, pss = TRUE) crypt_signature_verify(msg, sig, crypt_sha256, key$pubkey, pss = TRUE) secret <- crypt_rand_bytes(32) ct <- crypt_rsa_encrypt(secret, key$pubkey, oaep = TRUE, oaep_hash = "sha256") identical(crypt_rsa_decrypt(ct, key, oaep = TRUE, oaep_hash = "sha256"), secret)key <- crypt_rsa_keygen(2048) msg <- charToRaw("hello") sig <- crypt_signature_create(msg, crypt_sha256, key) crypt_signature_verify(msg, sig, crypt_sha256, key$pubkey) sig <- crypt_signature_create(msg, crypt_sha256, key, pss = TRUE) crypt_signature_verify(msg, sig, crypt_sha256, key$pubkey, pss = TRUE) secret <- crypt_rand_bytes(32) ct <- crypt_rsa_encrypt(secret, key$pubkey, oaep = TRUE, oaep_hash = "sha256") identical(crypt_rsa_decrypt(ct, key, oaep = TRUE, oaep_hash = "sha256"), secret)
Read, write, generate and take apart RSA keys. The names, arguments and
defaults follow the openssl package with a crypt_ prefix, and the
encodings interoperate: a key one package writes, the other reads.
crypt_read_key() reads a private key and crypt_read_pubkey() a
public key, from PEM or DER: PKCS#1, PKCS#8 or SubjectPublicKeyInfo.
crypt_read_pubkey() also accepts a private key and keeps its public
half.
crypt_write_pem() writes PKCS#8 (PRIVATE KEY) or
SubjectPublicKeyInfo (PUBLIC KEY) PEM; crypt_write_pkcs1() writes
PKCS#1 PEM (RSA PRIVATE KEY, RSA PUBLIC KEY); crypt_write_der()
writes a private key as PKCS#1 DER and a public key as
SubjectPublicKeyInfo DER, as openssl::write_der() does.
crypt_rsa_keygen() generates a key pair from the operating system's
random source.
crypt_rsa_key() builds a key from its integers, as a JSON Web Key
carries them, and as.list() takes one apart again.
A key object is an external pointer to key material held in C, and the material of a private key is wiped when the object is garbage collected.
crypt_read_key(file, password = NULL, der = is.raw(file)) crypt_read_pubkey(file, der = is.raw(file)) crypt_rsa_keygen(bits = 2048) crypt_write_pem(x, path = NULL, password = NULL) crypt_write_der(x, path = NULL) crypt_write_pkcs1(x, path = NULL, password = NULL) crypt_rsa_key( n, e, d = NULL, p = NULL, q = NULL, dp = NULL, dq = NULL, qi = NULL )crypt_read_key(file, password = NULL, der = is.raw(file)) crypt_read_pubkey(file, der = is.raw(file)) crypt_rsa_keygen(bits = 2048) crypt_write_pem(x, path = NULL, password = NULL) crypt_write_der(x, path = NULL) crypt_write_pkcs1(x, path = NULL, password = NULL) crypt_rsa_key( n, e, d = NULL, p = NULL, q = NULL, dp = NULL, dq = NULL, qi = NULL )
file |
The key: a raw vector of DER or PEM bytes, a single string of PEM text, a path to a file holding either, or a connection. |
password |
Not supported yet: password-protected keys arrive in a
later version. Must be |
der |
Accepted for compatibility with |
bits |
The modulus size, a multiple of 8 from 1024 to 4096. 2048 is the minimum for new keys; use 3072 or more for keys meant to last. |
x |
A key from |
path |
|
n, e
|
The modulus and the public exponent, as raw big-endian unsigned integers. |
d, p, q, dp, dq, qi
|
The private exponent, the primes and the CRT parameters, as raw big-endian unsigned integers. Give all six for a private key, or none for a public key. |
crypt_read_key(), crypt_rsa_keygen() and crypt_rsa_key()
with the private members return a key of class c("crypt_key", "crypt_rsa"); crypt_read_pubkey() and crypt_rsa_key() without them
return one of class c("crypt_pubkey", "crypt_rsa"). crypt_write_pem()
and crypt_write_pkcs1() return a string, and crypt_write_der() a raw
vector, or with path write it and return path invisibly. as.list()
returns type, size, for a private key pubkey, and data: the
integers as raw vectors, e, n and for a private key p, q, d,
dp, dq and qi.
Input that is not a readable key is zucrypt_invalid_argument, and so
is a public key object given where a private key is needed. A
well-formed key this version cannot use (an RSA key outside the size
rule, a curve other than P-256, P-384 and P-521, or an encrypted key) is
zucrypt_unsupported_algorithm. A condition about a key carries the
key's type in its algorithm field ("rsa", "p256", "p384",
"p521" or "x25519"), and NA when the input is not a key.
A key object refers to key material held outside R, so a copy is the same
key, not a new one: changing the attributes of k2 <- k changes k
too. Key objects do not survive saveRDS(); save the output of
crypt_write_pem() instead.
RSA keys are read only if the modulus is 1024 to 4096 bits, a whole
number of bytes; openssl also reads smaller keys, which are weak, and
larger ones. EC keys on P-256, P-384 and P-521, and X25519 keys, are read
as openssl writes them. Encrypted keys, SSH formats and fingerprints
come later. as.list() gives the integers as raw vectors rather than
bignums. There is no default key:
openssl reads ~/.ssh/id_rsa, and this package never reads your files
unless you name them.
key <- crypt_rsa_keygen(2048) key pem <- crypt_write_pem(key$pubkey) cat(pem) pub <- crypt_read_pubkey(pem) # The integers a JSON Web Key carries, and back. parts <- as.list(pub)$data identical(crypt_write_der(crypt_rsa_key(parts$n, parts$e)), crypt_write_der(pub))key <- crypt_rsa_keygen(2048) key pem <- crypt_write_pem(key$pubkey) cat(pem) pub <- crypt_read_pubkey(pem) # The integers a JSON Web Key carries, and back. parts <- as.list(pub)$data identical(crypt_write_der(crypt_rsa_key(parts$n, parts$e)), crypt_write_der(pub))
crypt_sha1(), crypt_sha256(), crypt_sha384() and crypt_sha512()
mirror openssl::sha1() and its siblings for raw input: the digest, or
with key the HMAC, as a raw vector of class c("hash", "<algorithm>"),
and "hmac" after them for an HMAC.
They exist first so that crypt_signature_create() can take hash = crypt_sha256 as openssl::signature_create() takes hash = sha256.
This version accepts raw vectors only. openssl also hashes character vectors element-wise and reads connections; that typing, and the other digests, arrive with the rest of the openssl-shaped layer.
crypt_sha1() is for formats that specify SHA-1. It is not collision
resistant; use crypt_sha256() for anything new.
crypt_sha1(x, key = NULL) crypt_sha256(x, key = NULL) crypt_sha384(x, key = NULL) crypt_sha512(x, key = NULL)crypt_sha1(x, key = NULL) crypt_sha256(x, key = NULL) crypt_sha384(x, key = NULL) crypt_sha512(x, key = NULL)
x |
A raw vector. |
key |
|
A raw vector of class c("hash", "<algorithm>"): 20, 32, 48 or 64
bytes.
crypt_hash() and crypt_hmac(), the core functions these
wrap.
crypt_sha256(charToRaw("abc")) crypt_sha256(charToRaw("abc"), key = charToRaw("secret"))crypt_sha256(charToRaw("abc")) crypt_sha256(charToRaw("abc"), key = charToRaw("secret"))
zucrypt publishes its primitives to other packages twice, because the
zu* family consumes siblings in two different ways. Both deliver the
same library; they differ in what the consumer has to carry, and in how
stable they are: the static archive is the primary shape, and the
registered table is experimental. See the Stability section.
For a package that can carry an Imports:. Nothing is linked: R's
registered C-callable mechanism hands over a single versioned table of
function pointers.
# DESCRIPTION Imports: zucrypt LinkingTo: zucrypt
# NAMESPACE -- a real import, not just the Imports: field importFrom(zucrypt, crypt_info)
#include <zucrypt-r.h>
const zucrypt_api_v1 *api = zucrypt_api();
if (api == NULL) {
/* zucrypt does not implement the ABI version this was built against */
}
uint8_t out[ZUC_MAX_DIGEST_SIZE];
size_t n;
zuc_status st = api->hash_compute(ZUC_ALG_SHA256, data, len,
out, sizeof out, &n);
LinkingTo: alone is not enough, and neither is Imports: alone.
LinkingTo: supplies the headers and links nothing. Imports: without a
real importFrom() in NAMESPACE does not load zucrypt's namespace, and
an unloaded namespace has no registered callable to find. zucrypt_api()
resolves lazily on first use rather than from your R_init_, which
sidesteps the remaining ordering problem, but the import directive is
still required.
NULL means a version mismatch, and nothing else. When zucrypt is not
installed or not loaded, R_GetCCallable() does not return NULL: it
raises an R error, which longjmps out of your C code. Resolve the table
before you acquire anything such a jump would strand.
A table field added after the one you built against may be missing from
an older zucrypt: test with ZUCRYPT_API_HAS(api, field) before calling
it.
For a package that cannot carry an Imports: – zuxlsx links its
siblings statically and has no runtime dependency on them by design.
# DESCRIPTION LinkingTo: zucrypt
A configure and configure.win resolve
system.file("lib", .Platform$r_arch, package = "zucrypt"), falling back
to system.file("lib", package = "zucrypt"), and substitute the result
into src/Makevars.in as a single-quoted PKG_LIBS entry – a library
path containing a space, which is the norm on Windows, otherwise reaches
the linker as two arguments. Then include <zucrypt.h> and call the
functions directly.
The archive is installed to lib/ plus the R sub-architecture – plain
lib/ on Linux and macOS, lib/x64/ on Windows – which is why the lookup
above tries the sub-architecture first. The licence of the backend
compiled into it is installed as licenses/tf-psa-crypto-LICENSE; a
binary of your package redistributes that code, so ship the notice too.
This shape owns the backend's lifetime: call zuc_init() before anything
else and zuc_shutdown() when finished. It is reference counted, so
nesting is safe. A call outside that window returns ZUC_ERR_NOT_READY.
Two consequences worth stating plainly. Your shared object contains its own
copy of the backend, kept private by hidden visibility. And upgrading
zucrypt does nothing for you until your package is reinstalled – including
a security fix – so report the version you actually linked, by calling
zuc_get_info() rather than reading a macro.
Hidden visibility keeps the backend private to your shared object, not
inside it. The archive defines psa_*() and mbedtls_*() as ordinary
symbols, so do not link another PSA Crypto or Mbed TLS (a second vendored
copy, or a system libmbedcrypto) into the same shared object as
libzucrypt.a. It is not supported, and a static link fails with a
duplicate symbol. In separate shared objects, zucrypt.so included, the
copies do not interfere (#112).
The archive is built from the objects zucrypt was compiled into, with
zucrypt's flags. If zucrypt was installed with link-time optimisation
(LTO = -flto in ~/.R/Makevars), those objects hold compiler
bytecode rather than machine code, and only a linker that reads that
compiler's bytecode can use them: build your package with the same
compiler. A different one (clang against a GCC LTO build) finds no
symbols in the archive. An ordinary installation is not affected (#144).
Every function that can fail returns a zuc_status; the rest are
queries and cleanups that cannot (zuc_alg_*(), zuc_status_name(),
zuc_status_string(), zuc_equal(), zuc_secure_zero(),
zuc_pkey_type(), zuc_pkey_bits(), zuc_pkey_is_private() and the
*_free() functions). None raises an R error, allocates an R object,
or calls back into R. No status is negative, so if (st) means "not
success".
An object the library allocated is destroyed only by a library function. No buffer you pass is retained after the call returns.
inst/include/zucrypt.h compiles standalone as C99 against <stddef.h>
and <stdint.h>, and names no backend type. You never have to reproduce
this package's build configuration.
Fields are appended to the table, never removed or reordered. A layout
change to any other type in the header renames the registered callable
instead, so an old consumer fails at R_GetCCallable() rather than
reading a structure that has moved.
Each AES and HMAC handle holds one key in a key store that grows on demand, so the number of live handles is bounded only by memory.
Main thread only, in this version.
The three surfaces are at different stages:
The crypt_*() R functions are stable.
The static archive – zucrypt.h, libzucrypt.a and where it is
installed – is frozen as ABI 1 from 0.1.0. The freeze followed its
first consumer: zuxlsx's decryption of password-protected workbooks was
written against it, linked it on Linux, macOS and Windows, and decrypted
a real encrypted workbook with it.
The registered table (zucrypt-r.h) is experimental: no package
uses it yet. It may change in any release until one does, again with
every change recorded in NEWS.md.
ZUCRYPT_ABI_VERSION is 1. Within major version 1:
functions and table fields may be added; nothing is removed, reordered or
given a new meaning; enumerator values are permanent, so an algorithm
compiled out of a build keeps its number and reports itself unavailable;
and a ZUC_*_REQUIRED_SIZE macro never grows, so a consumer built against
an older header keeps working without being rebuilt.
A layout change to a type that struct_size cannot see renames the
registered callable instead, so an old consumer fails at
R_GetCCallable() rather than reading a structure that has moved.
Not promised: the numeric value of a backend status behind
ZUC_ERR_BACKEND, the contents of an opaque handle, and thread safety
beyond the main thread.
crypt_info(), which reports the ABI version, the backend and the
algorithms this build provides.