Common cryptographic library used in software at Mysten Labs.

Overview

[fastcrypto]

crate Docs Build status Apache2/MIT licensed Rust Version

fastcrypto is a common cryptography library used in software at Mysten Labs. It is published as an independent crate to encourage reusability across different applications and domains. It is a wrapper library around several carefully selected crates with the following considerations:

  • Security: Whether the libraries are vulnerable to known attack vectors or possible misuses.
  • Performance: Whether the crate performs cryptographic operations with speed after extensive benchmarking. This is critical for the Sui Network to be performant when signing and verifying large amounts of transactions and certificates.
  • Determinism: Whether the signature is non-malleable.
  • Popularity: Whether the library is used by other consensus critical systems.

Furthermore, we extend the selected libraries with additional features:

  • Robust testing framework: Wycheproof tests and prop tests are added when possible to protect against arbitrary inputs and crafted edge cases.
  • Zeroization: Sensitive private key materials are cleared from memory securely and proactively when it goes out of scope using zeroize trait.
  • Serialization: Effective and standardized serialization are required.

This library will be continuously updated with more schemes and faster implementations based on benchmarking results, RFC updates, new research and auditor inputs.

This crate contains:

  • Traits that should be implemented by concrete types representing digital cryptographic materials.

    • [SigningKey]: Trait implemented by the private key with associated types of its public key and signature.
    • [VerifyingKey]: Trait implemented by the public key with associated types of its private key and signature. It also includes a default implementation of batch verification that fails on empty batch verification.
    • [Authenticator]: Trait implemented by the signature with associated types of its public key and private key.
    • [AggregateAuthenticator]: Trait implemented by the aggregated signature, which allows adding signatures to the aggregated signature and verifying against the public keys with the corresponding messages.
    • [KeyPair]: Trait that represents a public/private keypair, which includes the common get priv/pub key functions and a keypair generation function with seeded randomness.
    • [ToFromBytes]: Trait that aims to minimize the number of steps involved in obtaining a serializable key. [EncodeDecodeBase64]: Trait that extends ToFromBytes for immediate conversion to/from Base64 strings. This is the format in which cryptographic materials are stored.
  • Concrete signature schemes of type that implement the recommended traits required for cryptographic agility.

    • Ed25519: Backed by ed25519-consensus crate. Compliant to ZIP-215 that defines the signature validity that is lacking from RFC8032 but critical for consensus algorithms. ed25519-dalek is fully deprecated due to the recently discovered Chalkias double pub-key api vulnerability.
    • Secp256k1: Backed by Secp256k1 FFI wrapper that binds to C library and provides performance faster than the native Rust implementation k256 library by ~30% on verification. Produces a 65-byte recoverable signature of shape [r, s, v] where v can be 0 or 1 representing the recovery Id. Produces deterministic signatures using the pseudo-random deterministic nonce generation according to RFC6979, without the strong requirement to generate randomness for nonce protection. Uses sha256 as the default hash function for sign and verify. An interface for verify_hashed is provided to accept a pre-hashed message and its signature for verification. Supports public key recovery by providing the Secp256k1 signature with the corresponding pre-hashed message.
    • BLS12-381: Backed by blst crate written in Assembly and C that optimizes for performance and security. G1 and G2 points are serialized following ZCash specification in compressed format. Provides methods for verifying signatures in the G1 group against public keys in the G2 group. Provides methods for aggregating signatures and fast verifying aggregated signatures, where public keys are assumed to be verified for proof of possession.
  • Utility functions that serve as the underlying RUST implementation for the Move smart contract api.

    • HKDF: An HMAC-based key derivation function based on RFC-5869, to derive keypairs with a salt and an optional domain for the given keypair. This requires choosing an HMAC function that expands precisely to the byte length of a private key for the chosen KeyPair parameter.
    • Pedersen Commitment: Function to create a Pedersen commitment with a value and a blinding factor. Add or subtract Ristretto points that represent Pedersen commitments.
    • Bulletproofs Range Proof: Function to prove that a committed value is an unsigned integer that is within the range [0, 2^bits). Function to verify that the commitment is a Pedersen commitment of some value with an unsigned bit length, a value is an integer within the range [0, 2^bits)
  • A asynchronous signature service is provided for testing and benchmarking.

Tests and Benchmarks

There exist tests for all the three schemes, which can be run by:

$ cargo test

One can compare all currently implemented schemes for sign, verify, verify_batch and key-generation by running:

$ cargo bench

License

All crates licensed under either of

Comments
  • Keypair Serde is Broken

    Keypair Serde is Broken

    Description

    Keypair serializes, but does not deserialize when trying to test it out in MystenLabs/narwhal#557. Does not break Narwhal nor Sui so continuing with MystenLabs/narwhal#557 anyways.

    To replicate this issue, run the following test:

    #[test]
    fn test_kp_serde() {
        let kp = keys().pop().unwrap();
        let serialized = bincode::serialize(&kp).unwrap();
        let deserialized: Ed25519KeyPair = bincode::deserialize(&serialized).unwrap();
    }
    

    We get this error:

    thread 'bls12377_tests::test_kp_serde' panicked at 'called `Result::unwrap()` on an `Err` value: Custom("invalid Base64 encoding")', crypto/src/tests/bls12377_tests.rs:375:75
    

    Upon further digging, it looks like removing this line fixes the issue:

    #[serde(tag = "type")] // REMOVE THIS LINE
    pub struct Ed25519KeyPair {
        name: Ed25519PublicKey,
        secret: Ed25519PrivateKey,
    }
    
    bug crypto 
    opened by punwai 6
  • Remove support for BLS12-377 signing & bump library version

    Remove support for BLS12-377 signing & bump library version

    Rationale

    1. while we do use the BLS12-377 curve for proving (for good reason), we do not use it for signing, and are unlikely to do so in the near to medium term (due to strict performance requirements),
    2. @benr-ml is about to introduce a completely distinct instance & implementation of this curve as a dependency, in the context of threshold signing (see repo)
    3. The implementations of BLS12-377 as a signing scheme are not as mature as other instances, notably in the area of hashing to the curve. Indeed, BLS12-377 does not yet have a suite in the hash-to-curve RFC.
    Deep-dive into item 3

    Celo-BLS-snark-rs (upstream of this implementation)

    https://github.com/celo-org/celo-bls-snark-rs

    W3f/BLS

    https://github.com/w3f/bls

    Consensys/gnark

    https://github.com/ConsenSys/gnark-crypto

    • in Go,
    • maintained,
    • implements an SSWU map (see RFC section 6.6.2)
    • the parameters are undocumented
    • but the parameters may come from this script

    Conclusion

    It seems best to spend a little bit of time thinking about BLS12-377, a scheme we don't really use, before adopting & maintaining a version of it. Once we sort out the map_to_curve part, it may be suitable to improve & build on the implementation we're set to receive from (2.) above (or to an upstream impl) rather than continuing with this specific variant of the code.

    Fixes #242.

    opened by huitseeker 5
  • Problem building SUI repo with local changes to fastcrypto

    Problem building SUI repo with local changes to fastcrypto

    Hi I'm trying to build the sui repo with a change in the Cargo.toml file

    fastcrypto = { path = "../fastcrypto/fastcrypto"}
    

    So that I can reference a local repo o ffastcrypto reset to the revision

    git reset --hard bbb2d02a7a64c27314721748cc4d015b00490dbe
    

    I get the following error. Any ideas on what I am doing wrong? Thanks. error[E0277]: the trait bound fastcrypto::bls12381::min_sig::BLS12381PublicKey: MallocSizeOf` is not satisfied --> narwhal/types/src/primary.rs:148:48 | 148 | #[derive(Builder, Clone, Default, Deserialize, MallocSizeOf, Serialize)] | ^^^^^^^^^^^^ the trait `MallocSizeOf` is not implemented for `fastcrypto::bls12381::min_sig::BLS12381PublicKey

    opened by arthurgreef 4
  • feat: implement display/debug traits for private keys

    feat: implement display/debug traits for private keys

    Fixes #14, at least partially! For the public keys, base64 will have to do until #1 is resolved.

    For consideration: do you think a Secret derive macro that:

    1. derives Zeroize
    2. implements safe Display and Debug
    3. implements unsafe_write_secret: &self -> String (for debugging)

    makes sense? I could slot it into this PR. This would make the code nicer:

    #[derive(SecretMaterial)]
     pub struct BLS12381PrivateKey {
         pub privkey: blst::SecretKey,
         pub bytes: OnceCell<[u8; BLS_PRIVATE_KEY_LENGTH]>,
         ...
    }
    
    opened by erwanor 4
  • Add benchmarking workflow to CI

    Add benchmarking workflow to CI

    Closing #181. PR #209 should be merged first.

    This PR adds benchmarking to the CI.

    • Running all benchmarks takes ~1 hour, so we only do it on publish, but it may also be triggered manually.
    • We use cargo criterion to run benchmarks and generate reports:
      • In order to keep history of benchmarks, we first checkout the old reports from gh-pages
      • Then we use cargo criterion to run all benchmarks with the most recent version of fastcrypto and generate reports,
      • The new reports (including history) are pushed to gh-pages. See https://mystenlabs.github.io/fastcrypto/benchmarks/criterion/reports/ for an incomplete report (not all benchmarks have been run yet), and https://mystenlabs.github.io/fastcrypto/benchmarks/criterion/reports/Verify/Ed25519/history.html for an example of how the history of a benchmark is shown.
      • The results are stored as a JSON-file and stored under benchmarks/history with the latest commit hash as the filename. This allows analysis of historic data and comparison of versions using various analysis tools.

    This restructures the gh-pages such that documentation is put under "docs" and benchmarks under "benchmarks".

    opened by jonas-lj 3
  • [TB-crypto] Define a crypto-standard for Timestamped Benchmarks

    [TB-crypto] Define a crypto-standard for Timestamped Benchmarks

    As our backends evolve, we might realize that down the road the efficiency of some schemes might be updated, perhaps also have additional parallelization improvements etc. Let's maintain a timestamped bench-results page with diagrams to track improvement. Then protocol designers (and crypto paper authors) can really have a fair (and evolving) primitive comparison matrixes.

    TL;DR We receive incredibly positive feedback that fastcrypto gradually starts being a de facto reference implementation for future research papers and protocol designers due to providing a well-defined comparison matrix between some of the fastest implementations in the space + for batch/aggregated (in the future w precomputed table) + parallelization-friendly versions etc. Our results already:

    • changed the perception on how modern BLS impl. perform compared to the fastest ECDSA and EdDSA crates.
    • identified unfair or outdated comparisons reported by some lib authors.
    • some implementations perform extra serialization operations and/or others provide different security guarantees. for instance: -- BLS fast_aggregation_verify can be applied when rogue key attack protection already took place (ie via PoP sigs) -- another case in ed25519 batch-verify where two different libs use as inputs Objects Vs raw bytes (and thus extra serialization steps are required in the 2nd, skewing the comparison results a bit). -- another case is base64 malleable vs non-malleable and/or constant vs variable time implementations.
    • how can someone combine different backends for different setups and input sizes (ie see the results for base64 encoders where for different input sizes we have another winner impl).
    • what are the sweet points when we compare the two fastest Rust implementations (or ports). Example: Many ask about "When aggregated BLS starts winning against batched ed25519?", "what if we used a parallelized version?" etc.
    • we already have evidence that some cryptographic protocols, which were supposed to be hanging behind re performance, are in practice a lot faster than expected and vice versa.
    • how parallel and/or vectorized implementations perform against each other (ie AVX2, no-threads BLST etc)?
    • easily compare against optimized and experimental versions (i.e., with precomputed tables, removing one half-scalar in random combinations, half-aggregation etc).
    crypto 
    opened by kchalkias 3
  • We should add hash wrappers as well for all Sui/Narwhal used functions

    We should add hash wrappers as well for all Sui/Narwhal used functions

    This will help to avoid surprises in Sui or Narwhal re using different sha2/sha3/keccak deps in different places. Ideally we should control every crypto algorithm in fastcrypto. After having these wrappers, we should update both Narwhal and Sui repos by invoking fastcrypto's api.

    I was thinking that the same applies for base64, but let's wait for this, as Rust's popular base64 crate is working on the malleability fix.

    opened by kchalkias 3
  • Implement MSKR for min_sig as well

    Implement MSKR for min_sig as well

    Actually this should be the default mode, as our benchmarks say this is faster + sigs are reused, while pks are usually static for BFT committees (at least per epoch).

    opened by kchalkias 2
  • Fix bug in test_sk_zeroization_on_drop for BLS12377

    Fix bug in test_sk_zeroization_on_drop for BLS12377

    The test_sk_zeroization_on_drop test for BLS12377 fails sometimes because one of the bytes from the secret key not changing before this check will cause the test to fail. We instead check that not all the bytes are still equal.

    opened by jonas-lj 2
  • Bump signature from 1.6.3 to 1.6.4

    Bump signature from 1.6.3 to 1.6.4

    Bumps signature from 1.6.3 to 1.6.4.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.

    Dependabot will merge this PR once CI passes on it, as requested by @mystenadmin.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies rust 
    opened by dependabot[bot] 2
  • Add AES CTR, CBC, GCM

    Add AES CTR, CBC, GCM

    Added support for AES with 128 and 256 bit keys using either CTR, CBC, GCM with PKCS#7 padding. All modes are backed by crates from RustCrypto (https://github.com/RustCrypto/block-modes).

    opened by jonas-lj 2
  • {PublicKeyBytes, Base64Representation} -> BytesRepresentation, and introduce serialize_deserialize_with_to_from_byte_array

    {PublicKeyBytes, Base64Representation} -> BytesRepresentation, and introduce serialize_deserialize_with_to_from_byte_array

    • Removed PublicKeyBytes and it dependencies (verified they are not used in sui/). That struct could have stored invalid "serialized" objects, thus it was not always safe to use it.
    • Changed Base64Representation to serialize differently depending on is_human_readable and renamed it to BytesRepresentation. (I couldn't find a nicer way to support both options unfortunately). We may use BytesRepresentation everywhere we intended to use PublicKeyBytes. Also added a macro for deriving such type for a given type generate_bytes_representation.
    • Added a macro serialize_deserialize_with_to_from_byte_array for simplifying adding ser/des for objects without caching.
    opened by benr-ml 0
  • crypto: Add Intent and IntentMessage

    crypto: Add Intent and IntentMessage

    moving this from sui to fastcrypto since both sui and narwhal depends on it. see https://github.com/MystenLabs/sui/pull/6927 for usage

    intent_tests needed struct defined in sui, so the tests are kept there.

    opened by joyqvq 0
  • Keypair encoding / serialization to store the private key only

    Keypair encoding / serialization to store the private key only

    This is better hygiene, to also defend against the private - public key mismatching we found on ed25519 libs. The pub key can be derived during deserialization. Creating a similar issue in Sui repo.

    opened by kchalkias 1
Releases(v0.1.2)
Owner
Mysten Labs
We create foundational infrastructure to accelerate web3 adoption
Mysten Labs
Dexios-Core is a library used for managing cryptographic functions and headers that adhere to the Dexios format.

What is it? Dexios-Core is a library used for managing cryptographic functions and headers that adhere to the Dexios format. Security Dexios-Core uses

brxken 3 Jul 4, 2022
Sodium Oxide: Fast cryptographic library for Rust (bindings to libsodium)

sodiumoxide |Crate|Documentation|Gitter| |:---:|:-----------:|:--------:|:-----:|:------:|:----:| |||| NaCl (pronounced "salt") is a new easy-to-use h

sodiumoxide 642 Dec 17, 2022
A library to help you sew up your Ethereum project with Rust and just like develop in a common backend

SewUp Secondstate EWasm Utility Program, a library helps you sew up your Ethereum project with Rust and just like development in a common backend. The

Second State 48 Dec 18, 2022
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Dec 30, 2022
A (mostly) pure-Rust implementation of various cryptographic algorithms.

Rust-Crypto A (mostly) pure-Rust implementation of various common cryptographic algorithms. Rust-Crypto seeks to create practical, auditable, pure-Rus

null 1.2k Dec 27, 2022
Collection of cryptographic hash functions written in pure Rust

RustCrypto: hashes Collection of cryptographic hash functions written in pure Rust. All algorithms reside in the separate crates and implemented using

Rust Crypto 1.2k Jan 8, 2023
Modern Cryptographic Firmware

Trussed® Modern Cryptographic Firmware Status Very much WIP. Actively developed. Unstable APIs.

Trussed® 300 Dec 16, 2022
The underlying cryptographic primitives for Manta Ecosystem

manta crypto The underlying cryptography that manta ecosystem relies on. It comes with the following traits: checksum: definitions for message digest.

Manta Network 10 Nov 10, 2021
Secure storage for cryptographic secrets in Rust

secrets secrets is a library to help Rust programmers safely held cryptographic secrets in memory. It is mostly an ergonomic wrapper around the memory

Stephen Touset 165 Dec 22, 2022
Pure Rust implementation of the RNCryptor cryptographic format by Rob Napier

rncryptor Rust Implementation of the RNCryptor spec This library implements the specification for the RNCryptor encrypted file format by Rob Napier. d

null 7 Jun 29, 2022
Pure-Rust traits and utilities for constant-time cryptographic implementations.

subtle Pure-Rust traits and utilities for constant-time cryptographic implementations. It consists of a Choice type, and a collection of traits using

dalek cryptography 196 Dec 13, 2022
Cryptographic Primitive Code Generation by Fiat

Fiat-Crypto: Synthesizing Correct-by-Construction Code for Cryptographic Primitives Building This repository requires Coq 8.11 or later. Note that if

Programming Languages and Verification Group at MIT CSAIL 538 Jan 7, 2023
Cryptographic signature algorithms: ECDSA, Ed25519

RustCrypto: signatures Support for digital signatures, which provide authentication of data using public-key cryptography. All algorithms reside in th

Rust Crypto 300 Jan 8, 2023
the official Rust and C implementations of the BLAKE3 cryptographic hash function

BLAKE3 is a cryptographic hash function that is: Much faster than MD5, SHA-1, SHA-2, SHA-3, and BLAKE2. Secure, unlike MD5 and SHA-1. And secure again

BLAKE3 team 3.7k Jan 6, 2023
Fastmurmur3 - Fast non-cryptographic hash, with the benchmarks to prove it.

Fastmurmur3 Murmur3 is a fast, non-cryptographic hash function. fastmurmur3 is, in my testing, the fastest implementation of Murmur3. Usage let bytes:

Kurt Wolf 13 Dec 2, 2022
Fuel cryptographic primitives

Fuel Crypto Fuel cryptographic primitives. Compile features std: Unless set, the crate will link to the core-crate instead of the std-crate. More info

Fuel Labs 19 Sep 8, 2022
Key derivation and cryptographic signing functionality for Ethereum applications (ethers-rs)

ethers-signer-factory ethers-signer-factory is a Rust crate that provides functions for key derivation and signing of Ethereum transactions and messag

Ilia 3 Sep 27, 2023
Expose various non-cryptographic hashing functions with Digest traits

noncrypto-digests Expose various non-cryptographic hashing functions with Digest traits. This allows users to use any hashing function with the same t

Yuri Astrakhan 3 Dec 9, 2023
A Boring(SSL)-compatible API abstraction for Rust cryptographic implementations.

A Boring(SSL)-compatible API abstraction for Rust cryptographic implementations. What is Superboring? Superboring hides the complexity, diversity and

Frank Denis 7 Dec 29, 2023