Sodium Oxide: Fast cryptographic library for Rust (bindings to libsodium)

Overview

sodiumoxide

|Crate|Documentation|Gitter| |:---:|:-----------:|:--------:|:-----:|:------:|:----:| |Crates.io|Docs|Gitter|

NaCl (pronounced "salt") is a new easy-to-use high-speed software library for network communication, encryption, decryption, signatures, etc. NaCl's goal is to provide all of the core operations needed to build higher-level cryptographic tools. Of course, other libraries already exist for these core operations. NaCl advances the state of the art by improving security, by improving usability, and by improving speed.

Sodium is a portable, cross-compilable, installable, packageable fork of NaCl (based on the latest released upstream version nacl-20110221), with a compatible API.

This package aims to provide a type-safe and efficient Rust binding that's just as easy to use. Rust >= 1.36.0 is required because of mem::MaybeUninit.

Basic usage

Cloning

git clone https://github.com/sodiumoxide/sodiumoxide.git
cd sodiumoxide
git submodule update --init --recursive

Building

cargo build

Testing

cargo test

Documentation

cargo doc

Documentation will be generated in target/doc/...

Most documentation is taken from NaCl, with minor modification where the API differs between the C and Rust versions.

Support for the AES AEAD Variant

The AES AEAD variant crypto_aead_aes256gcm requires hardware support for the AES and CLMUL instruction set extensions to x86; you can read why that's the case here. These instruction set extensions were first made available in Intel Westmere (early 2010) and at the time of writing x86 hardware support for them is near universal.

Libsodium exposes an API for runtime feature detection and doesn't prevent you from calling crypto_aead_aes256gcm on a machine lacking AES and CMUL expressions; doing so will result in a runtime SIGILL (illegal instruction). By contrast sodiumoxide exposes an API that precludes the use of the crypto_aead_aes256gcm_* family of functions without performing the runtime check. It's important to note that the use of sodiumoxide::init() is mandatory when using AES; unless you call init calls aead::aes256gcm::Aes256Gcm::new() will always return Err(_) even if your runtime hardware supports AES.

Dependencies

C compiler (cc, clang, ...) must be installed in order to build libsodium from source.

Extended usage

This project contains a snapshot of libsodium and builds it by default, favouring a statically-built, fixed version of the native library.

Although it is highly recommended to use the default way with the pinned version, there are several ways you may want to use this crate:

  • link it against the library installed on your system
  • link it against a precompiled library that you built on your own

You can do this by setting environment variables.

Name Description Example value Notes
SODIUM_LIB_DIR Where to find a precompiled library /usr/lib/x86_64-linux-gnu/ The value should be set to the directory containing .so,.a,.la,.dll or .lib
SODIUM_SHARED Tell rustc to link the library dynamically 1 Works only with SODIUM_LIB_DIR. We check only the presence
SODIUM_USE_PKG_CONFIG Tell build.rs to find system library using pkg-config 1 We check only the presence
SODIUM_DISABLE_PIE Build with --disable-pie 1 Certain situations may require building libsodium configured with --disable-pie. Useful for !Windows only and when building libsodium from source. We check only the presence

Examples on *nix

Using pkg-config

(Ubuntu: apt install pkg-config, OSX: brew install pkg-config, ...)

export SODIUM_USE_PKG_CONFIG=1
cargo build

Using precompiled library

See https://download.libsodium.org/doc/installation.

export SODIUM_LIB_DIR=/home/user/libsodium-1.0.18/release/lib/
export SODIUM_SHARED=1
cargo build

Optional features

Several optional features are available:

  • std (default: enabled). When this feature is disabled, sodiumoxide builds using #![no_std]. Some functionality may be lost.

  • serde (default: enabled). Allows serialization and deserialization of keys, authentication tags, etc. using the serde library.

  • benchmarks (default: disabled). Compile benchmark tests. Requires a nightly build of Rust.

Cross-Compiling

Cross-Compiling for armv7-unknown-linux-gnueabihf

  1. Install dependencies and toolchain:
sudo apt update
sudo apt install build-essential gcc-arm-linux-gnueabihf libc6-armhf-cross libc6-dev-armhf-cross -y
rustup target add armv7-unknown-linux-gnueabihf
  1. Add the following to a .cargo/config file:
[target.armv7-unknown-linux-gnueabihf]
linker = "arm-linux-gnueabihf-gcc"
  1. Build by running:
cargo build --release --target armv7-unknown-linux-gnueabihf

Cross-Compiling for armv7-unknown-linux-musleabihf via docker

  1. cargo.config:
[target.armv7-unknown-linux-musleabihf]
linker = "arm-buildroot-linux-musleabihf-gcc"
  1. Dockerfile:
FROM rust:1.36.0

ENV TARGET="armv7-unknown-linux-musleabihf"

ARG TOOLCHAIN_ARM7="armv7-eabihf--musl--stable-2018.02-2"
ARG TC_ARM7_URL="https://toolchains.bootlin.com/downloads/releases/toolchains/armv7-eabihf/tarballs/${TOOLCHAIN_ARM7}.tar.bz2"

RUN rustup target add ${TARGET}
COPY cargo.config "${CARGO_HOME}/config"

WORKDIR /opt
RUN curl -o- ${TC_ARM7_URL} | tar -xjf -

ENV PATH="${PATH}:/opt/${TOOLCHAIN_ARM7}/bin"
ENV CC_armv7_unknown_linux_musleabihf=arm-buildroot-linux-musleabihf-gcc
ENV CXX_armv7_unknown_linux_musleabihf=arm-buildroot-linux-musleabihf-g++
ENV LD_armv7_unknown_linux_musleabihf=arm-buildroot-linux-musleabihf-ld

WORKDIR /work
RUN git clone https://github.com/sodiumoxide/sodiumoxide

WORKDIR /work/sodiumoxide
RUN cargo build --target=${TARGET}

Cross-Compiling for 32-bit Linux

  1. Install dependencies and toolchain:
sudo apt update
sudo apt install build-essential gcc-multilib -y
rustup target add i686-unknown-linux-gnu
  1. Build by running:
cargo build --release --target i686-unknown-linux-gnu

Examples

TBD

Platform Compatibiility

Sodiumoxide has been tested on:

  • Linux: Yes
  • Windows: Yes (MSVC)
  • Mac OS: Yes
  • IOS: TODO
  • Android: Yes

Join in

File bugs in the issue tracker

Master git repository

git clone https://github.com/sodiumoxide/sodiumoxide.git

License

Licensed under either of

at your option.

Contribution

Go through the CONTRIBUTING.md document to know more about how to contribute to this project.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Code of Conduct

We believe in creating an enabling community for developers and have laid out a general code of conduct. Please read and adopt it to help us achieve and maintain the desired community standards.

Comments
  • Add include & lib build metadata to libsodium-sys

    Add include & lib build metadata to libsodium-sys

    Adds DEP_SODIUM_INCLUDE & DEP_SODIUM_LIB env variable to can be used by dependent crates. In my case, I use it to link against libsodium from a c++ library (libzmq) built via cargo.

    opened by jean-airoldie 57
  • Bump the libsodium submodule to the current stable branch.

    Bump the libsodium submodule to the current stable branch.

    libsodium recommends using its stable branch when building from source as it contains critical fixes since the last release.

    We should probably decide on

    • [x] How to handle the binaries we ship for MinGW and MSVC as they are from the tagged release: We'll ship binaries from the stable-branch-based snapshot builds.
    • [x] How to handle the version check we building against an external libsodium version. before merging this: The version check is unchanged as the stable branch will always be compatible to the latest tagged release.
    opened by adamreichold 29
  • Support for the libsodium aeads

    Support for the libsodium aeads

    Implement formal support for aes256gcm and chacha20poly1305. Combined modes only.

    I was tempted to model their commonality in the type system, but it looks like 1) it's not project style, and 2) the commonalities start to fall apart when you look at modes outside combined mode. I can still go that route if you give me a nudge.

    opened by JohnHeitmann 24
  • Used call_once in init() to make it thread-safe and updated documentation.

    Used call_once in init() to make it thread-safe and updated documentation.

    I believe this makes it safe for users to call init() concurrently.

    The test doesn't check that any init() call actually succeeded, only that it didn't execute the call more than once. Ideally I'd like to have checked that it returned success exactly once, but I don't know if that's reasonable - i.e. if there are environments where the library can still be used safely despite init() returning false.

    Also, since the tests run in parallel by default, I think we should be calling init() at the start of every test. This PR makes it safe to do that now, although I plan to make that change in a separate PR if you agree and are OK with this one.

    opened by Fraser999 22
  • Add support for the AES256-GCM AEAD construction

    Add support for the AES256-GCM AEAD construction

    This commit adds support for AES256-GCM. NB: libsodium limits its support of AES256-GCM to x86/x86-64 processors with the AES-NI instruction set. Compile time feature flags are used to hide GCM functionality for targets lacking the requisite support. In the interest of maintaining parity with the libsodium API an is_available function mapping to crypto_aead_aes256gcm_is_available is unconditionally exported but shouldn't be required given the compile-time check.

    Signed-off-by: Kelly Littlepage [email protected]

    opened by klittlepage 21
  • Avoid ptr_cast feature as it was not yet stable in Rust 1.36.

    Avoid ptr_cast feature as it was not yet stable in Rust 1.36.

    Also adds a Travis CI job to check building against the minimum supported Rust version, i.e. 1.36.0, and fixes the xcopy flags again to allow overriding files in the target directory.

    opened by adamreichold 21
  • Add support for systems that output the pinned libsodium to lib64

    Add support for systems that output the pinned libsodium to lib64

    Building sodiumoxide on OpenSUSE Tumbleweed as of 2018/12/18 causes the build of the pinned libsodium library to fail.

    This is caused by build.rs presuming the library to be output in the lib directory, while the actual output directory is lib64.

         Running `/home/elyzion/.cargo/bin/sccache rustc --crate-name libsodium_sys libsodium-sys/src/lib.rs --color always --crate-type lib --emit=dep-info,link -C debuginfo=2 -C metadata=43c000b33b9ab959 -C extra-filename=-43c000b33b9ab959 --out-dir /home/elyzion/workspace/github.com/elyzion/sodiumoxide/target/debug/deps -C incremental=/home/elyzion/workspace/github.com/elyzion/sodiumoxide/target/debug/incremental -L dependency=/home/elyzion/workspace/github.com/elyzion/sodiumoxide/target/debug/deps --extern libc=/home/elyzion/workspace/github.com/elyzion/sodiumoxide/target/debug/deps/liblibc-c0ea49ff27a168b5.rlib -L native=/home/elyzion/workspace/github.com/elyzion/sodiumoxide/target/debug/build/libsodium-sys-21cd69d46e7fda91/out/installed/lib -l static=sodium`
    error: could not find native static library `sodium`, perhaps an -L flag is missing?
    
    error: aborting due to previous error
    
    error: Could not compile `libsodium-sys`.
    

    This is a quick solution to this problem that simple adds another search path for cargo.

    Pending: Discussion 
    opened by elyzion 19
  • Made most types encodable and decodable.

    Made most types encodable and decodable.

    The main thrust of this PR is to make most of the data types encodable and decodable by adding the relevant rustc_serialize traits inside the newtype_impl macro.

    We've also added tests for these functions to all affected types.

    There are a few places where we have applied Eq and PartialEq to non-secret types.

    opened by Fraser999 19
  • implement seal_detached_inplace and open_detached_inplace

    implement seal_detached_inplace and open_detached_inplace

    https://github.com/dnaq/sodiumoxide/issues/24

    This is another take on non-allocating primitives for secretbox. If we like it, we could do the same thing for box too. There were two particular design questions in my head for what interface to expose for this:

    1. Combined mode vs detached mode. Detached mode is the lower-level primitive of the two, and it's easy to implement combined mode as a wrapper, but not the other way around. This is also how libsodium's implementation is organized. So I went with detached mode.

    2. In-place vs two-buffers. Libsodium supports both, by checking the pointers to see if they're overlapping. Rust makes it hard to support both in a single interface, because &mut references can never be aliased. I think it's easier to wrap an in-place function to become a two-buffers one than the other way around, so I went with in-place.

    Detached-and-in-place has the extra advantage that it can never panic, because there are no length checks. The length of the tag is statically known, and any length of the message is valid.

    opened by oconnor663 17
  • Maintenance fixes for dependency updates

    Maintenance fixes for dependency updates

    Hi! I know the README says you'll only accept security fixes, but I'm trying my luck with sneaking these maintenance fixes in anyway.

    ed25519 version 1.3.0 changed Signature::new() to panic on invalid data, which broke tests and caused deprecation warnings; I fixed that and bumped the dep version.

    build.rs uses cc::Tool::cflags_env(), which was introduced in cc 1.0.3. Specifying a too-low dependency breaks any -Z minimum-versions builds downstream, I bumped the dep version there as well.

    I also prepared a release commit that bumps the version numbers and updates the changelog, I can of course remove that though if you want to do it yourself.

    opened by Xiretza 16
  • WIP: Custom error type for secretbox::open and secretbox::open_detached

    WIP: Custom error type for secretbox::open and secretbox::open_detached

    Adds a custom error type SecretBoxError. Is this pattern good enough to implement everywhere?

    Addresses https://github.com/sodiumoxide/sodiumoxide/issues/221

    opened by cyberia-ng 16
Releases(0.1.0)
Owner
sodiumoxide
sodiumoxide
OXiDE - A PoC packer written in Rust

OXiDE is a PoC Rust packer. It doesn't do much other than compress the target binary, but if you read the code, you'll find that extending it to do more (e.g., obfuscation, anti-reversing) is very possible!

frank2 44 Nov 30, 2022
A fast, non-cryptographic, minimally DoS-resistant hashing algorithm for Rust.

Foldhash This repository contains foldhash, a fast, non-cryptographic, minimally DoS-resistant hashing algorithm implemented in Rust designed for comp

Orson Peters 155 Oct 23, 2024
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
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
Common cryptographic library used in software at Mysten Labs.

[fastcrypto] fastcrypto is a common cryptography library used in software at Mysten Labs. It is published as an independent crate to encourage reusabi

Mysten Labs 85 Dec 20, 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
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
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
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
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
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
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
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