A (mostly) pure-Rust implementation of various cryptographic algorithms.

Overview

Rust-Crypto

Build Status

A (mostly) pure-Rust implementation of various common cryptographic algorithms.

Rust-Crypto seeks to create practical, auditable, pure-Rust implementations of common cryptographic algorithms with a minimum amount of assembly code where appropriate. The x86-64, x86, and ARM architectures are supported, although the x86-64 architecture receives the most testing.

Rust-Crypto targets the current, stable build of Rust. If you are having issues while using an older version, please try upgrading to the latest stable.

Rust-Crypto has not been thoroughly audited for correctness, so any use where security is important is not recommended at this time.

Usage

To use Rust-Crypto, add the following to your Cargo.toml:

[dependencies]
rust-crypto = "^0.2"

and the following to your crate root:

extern crate crypto;

Contributions

Contributions are extremely welcome. The most significant needs are help adding documentation, implementing new algorithms, and general cleanup and improvement of the code. By submitting a pull request you are agreeing to make you work available under the license terms of the Rust-Crypto project.

License

Rust-Crypto is dual licensed under the MIT and Apache 2.0 licenses, the same licenses as the Rust compiler.

Algorithms

Rust-Crypto already supports a significant number of algorithms and with your help it will support even more in the future. Currently supported algorithms include:

  • AES
  • Bcrypt
  • BLAKE2b
  • BLAKE2s
  • Blowfish
  • ChaCha20
  • Curve25519
  • ECB, CBC, and CTR block cipher modes
  • Ed25519
  • Fortuna
  • Ghash
  • HC128
  • HMAC
  • MD5
  • PBKDF2
  • PKCS padding for CBC block cipher mode
  • Poly1305
  • RC4
  • RIPEMD-160
  • Salsa20 and XSalsa20
  • Scrypt
  • Sha1
  • Sha2 (All fixed output size variants)
  • Sha3
  • Sosemanuk
  • Whirlpool
Comments
  • Authenticated encryption

    Authenticated encryption

    This has the api and GCM mode, I'm almost done with chacha20/poly1305 as well and also figured we could do a generic version that just accepts any cipher and mac combination.

    Just to be clear not ready to merge yet.

    The api I defined is that the constructor for the aead takes key, iv, additional data (any anything else the cipher needs), then aeads have a trait of encrypt or decrypt that takes input, output, or tag. For encrypt it writes to the tag and for decrypt you're passing in the tag. It is intentional non-streaming as it verifies the tag before it decrypts.

    I had to make some modifications to how ghash worked as I found it changed types when you added ciphered data

    opened by calvinmetcalf 21
  • Can't compile on OSX 10.10

    Can't compile on OSX 10.10

    Hello everyone,

    I can't seem to compile the master branch of rust-crypto on OSX 10.10.2.

    I get several compile errors about rotate_left(s as usize) expecting u32 instead of usize in src/md5.rs:

    screenshot 2015-03-04 23 31 35

    So I tried removing as usize. When I do that, I get a compiler error:

    screenshot 2015-03-04 23 32 00

    These are the version of rustc/cargo I use:

    rustc 1.0.0-nightly (fed12499e 2015-03-03) (built 2015-03-03)
    cargo 0.0.1-pre-nightly (a58ffd7 2015-02-27) (built 2015-02-27)
    

    Has anyone had similar issues ?

    Thanks for your help.

    opened by conradkleinespel 15
  • 96 bit nonces for chacha plus some cleanup

    96 bit nonces for chacha plus some cleanup

    this adds 2 commits

    1. pulls some of the functions for chacha out into macros and some local variables out into constants
    2. allows 96 bit nonces and limits itself to only use the first counter byte, boringssl also does this for 8 byte nonces.
    opened by calvinmetcalf 13
  • Renaming rust-crypto crate to crypto

    Renaming rust-crypto crate to crypto

    Hey, I wanted to suggest a rename of the rust-crypto crate to just crypto.

    It can be done in the Cargo.toml leaving the package name intact by just renaming the crate.

    [lib]
    # name = "rust-crypto"
    name = "crypto"
    path = "src/rust-crypto/lib.rs"
    

    All import calls would then be:

    // extern crate "rust-crypto" as crypto; // old way
    extern crate crypto; // new way
    

    What do you think?

    opened by icorderi 13
  • Unable to create Hmac for Sha384 and Sha512

    Unable to create Hmac for Sha384 and Sha512

    Since all Sha256, Sha384, Sha512 implement the trait Digest and Hmac::new accepts Digest, why do I have an error in this code?

    extern crate crypto;
    use crypto::sha2::{Sha256, Sha384, Sha512};
    use crypto::hmac::Hmac;
    use crypto::digest::Digest;
    use crypto::mac::Mac;
    
    
    enum MyType {
      Type1,
      Type2,
      Type3
    }
    
    //......
    
    let mut hmac = Hmac::new(match myType {
       MyType::Type1 => Sha256::new(),
       MyType::Type2 => Sha384::new(),
       MyType::Type3 => Sha512::new()
      }, my_secret.to_string().as_bytes()
    );
    
    

    The error is:

    error: match arms have incompatible types:
     expected `crypto::sha2::Sha256`,
        found `crypto::sha2::Sha384`
    (expected struct `crypto::sha2::Sha256`,
        found struct `crypto::sha2::Sha384`) [E0308]
       let mut hmac = Hmac::new(match myType {
           MyType::Type1 => Sha256::new(),
           MyType::Type2 => Sha384::new(),
           MyType::Type3 => Sha512::new(),
           _ => panic!()
         }, my_secret.to_string().as_bytes()
     note: match arm with an incompatible type
           MyType::Type2 => Sha384::new(),
                                             ^~~~~~~~~~~~~
     help: methods from traits can only be called if the trait is implemented and in scope; the following traits define a method `input`, perhaps you need to implement one of them:
     help: candidate #1: `crypto::cryptoutil::FixedBuffer`
     help: candidate #2: `crypto::digest::Digest`
     help: candidate #3: `crypto::mac::Mac`
     help: methods from traits can only be called if the trait is implemented and in scope; the following traits define a method `result`, perhaps you need to implement one of them:
     help: candidate #1: `crypto::digest::Digest`
     help: candidate #2: `crypto::mac::Mac`
    
    opened by GildedHonour 11
  • Ed25519-keypair based key exchange/agreement

    Ed25519-keypair based key exchange/agreement

    As may be known, key exchange and signing are only very slightly different operations on the same base curve. It is possible to convert Ed25519 keys to Curve25519 keys - but not vice versa (trivially, anyway), as far as I am aware. It is therefore possible to use a single keypair for both key exchange and signing, which cuts down on complexity. curve25519.rs is missing a keypair gen function (there is the curve25519_base function, but it lacks clamping), so this can stand in for that for the time being perhaps.

    opened by xorxornop 10
  • creating non-simple pbkdf2

    creating non-simple pbkdf2

    I looked at your test for pbkdf2:

    
        #[test]
        fn test_pbkdf2() {
            let tests = tests();
            for t in tests.iter() {
                let mut mac = Hmac::new(Sha1::new(), t.password[]);
                let mut result = Vec::from_elem(t.expected.len(), 0u8);
                pbkdf2(&mut mac, t.salt[], t.c, result[mut]);
                assert!(result == t.expected);
            }
        }
    

    and modified it to this for my purposes, to generate a single key

    //where seed_value/mnemonic are both &str
     let mut mac = Hmac::new(Sha256::new(),mnemonic.as_bytes());
        let mut result = Vec::new();
        pbkdf2(&mut mac,seed_value.as_bytes(),PBKDF2_ROUNDS,result[mut]);
    

    however I'm getting an error that the pbkfd2 tests aren't:

    src/rust_mnemonic.rs:150:57: 150:69 error: slicing syntax is experimental
    src/rust_mnemonic.rs:150     pbkdf2(&mut mac,seed_value.as_bytes(),PBKDF2_ROUNDS,result[mut]);
    

    I'm confused as to why rust-crypto doesn't have the same compiler error that I do?

    opened by leshow 8
  • Having trouble using rust-crypto

    Having trouble using rust-crypto

    I'm very new to rust and just trying to learn how to import and use this crate successfully.

    extern crate "rust-crypto" as rust_crypto;
    
    use rust_crypto::md5::Md5;
    
    fn main() {
      let mut sh = Md5::new();
      sh.input_str("The quick brown fox jumps over the lazy dog");
      let out_str = sh.result_str();
      println!("{}",out_str);
    }
    

    I build it properly with cargo, rust-crypto is being brought in successfully. And looking at the tests written in md5.rs it seems to me like the above should work. What am I doing wrong?

    opened by leshow 8
  • build error (cannot move out of captured outer variable)

    build error (cannot move out of captured outer variable)

    I get the following build errors in sha1.rs when building: http://pastebin.com/rMYEGWL6 I am at revision 4b330cd (up-to-date at time of writing).

    I guess something changed recently in Rust to trigger this. I was able to build successfully by capturing a std::cell::Cell instead of the value itself, but I'm not convinced that's the best solution!

    opened by tinyplasticgreyknight 8
  • Include a kaccak implementation?

    Include a kaccak implementation?

    Someone ported the kaccak reference implementation to rust. Since it is the winner for SHA-3, it might be within the scope of the project to include an implementation in rust-crypto (even if it's not that implementation)?

    opened by dcrewi 8
  • How to encrypt / decrypt  big string using Blowfish ECB?

    How to encrypt / decrypt big string using Blowfish ECB?

    I need to encrypt / decrypt a String of unknown size using Blowfish, however, the only functions provided in the module are encrypt_block and decrypt_block, which only work on &[u8] slices of 8 bytes.

    I'm guessing there's an interface for using all symmetric block ciphers? I'm having trouble finding examples.

    opened by danielrs 7
  • Ed25519 signature verification fails

    Ed25519 signature verification fails

    Signature verification fails, pleqse help!

    use crypto::ed25519::{keypair, signature, verify};
    fn main() {
        let seed: &[u8] = b"This is a seed";
        let message: &[u8] = b"This is a test of the tsunami a This is a test of the tsunami a ";
        let (mut secret_key, mut public_key) = keypair(seed);
        let mut sig = signature(message, &secret_key);
        assert!(verify(message, &public_key, &sig)); // Assert fails here
    }
    
    opened by LumaRay 0
  • aes::ecb_encryptor result not right and aes::ecb_decryptor error

    aes::ecb_encryptor result not right and aes::ecb_decryptor error

    rust-crypto = "0.2.36"

    key = vkWlFRxheBecchrd; input text = {"datas":{"email":null,"phone":null,"nickName":null,"lastIp":null,"userStatus":null},"status":-1,"msg":"Login Failed"}

    main code below: let mut encrypter = aes::ecb_encryptor(aes::KeySize::KeySize128, key, PkcsPadding); let json_to_string = {input text below}; let mut result = vec![0; json_to_string.as_bytes().len() * 4]; let mut read_buffer = RefReadBuffer::new(json_to_string.as_bytes()); let mut write_buffer = RefWriteBuffer::new(&mut result); let encrypt_result = encrypter.encrypt(&mut read_buffer, &mut write_buffer, true);

    aes::ecb_encryptor result = lRu5mBFQWBYWT2xNRWUGw5lkxJYQp11/v0d4ngcHp+HASfcfGh37EdjYZyEjST1/LwdkQXhxSeYUD+X/5gM2P2Fk7unIC0cNSU/S7HwlAhBZQDpgz02EZOvN/ejR3gRuMIG92xM8UXzyv6wQeURpBta68Oem4IDWpiixsx8lSw==

    right result = lRu5mBFQWBYWT2xNRWUGw5lkxJYQp11/v0d4ngcHp+HASfcfGh37EdjYZyEjST1/LwdkQXhxSeYUD+X/5gM2P2Fk7unIC0cNSU/S7HwlAhBZQDpgz02EZOvN/ejR3gRuMIG92xM8UXzyv6wQeURpBta68Oem4IDWpgAosbMfJUs=

    Could you please help to check?

    opened by cam510 1
  • build error: error: failed to run custom build command for rust-crypto v0.2.36

    build error: error: failed to run custom build command for rust-crypto v0.2.36

    error: failed to run custom build command for rust-crypto v0.2.36

    Caused by: process didn't exit successfully: /Users/denghui/dev_codes/parity-bitcoin/target/debug/build/rust-crypto-3ba811552027839f/build-script-build (signal: 11, SIGSEGV: invalid memory reference) --- stderr thread '' panicked at 'attempted to leave type nodrop::NoDrop<(epoch::Epoch, garbage::Bag)> uninitialized, which is invalid', /rustc/2fd73fabe469357a12c2c974c140f67e7cdd76d0/library/core/src/mem/mod.rs:671:9 note: run with RUST_BACKTRACE=1 environment variable to display a backtrace warning: build failed, waiting for other jobs to finish...

    opened by dhcn 1
  • Shouldn't Digest.result_str call output_bytes instead of repeating the code ?

    Shouldn't Digest.result_str call output_bytes instead of repeating the code ?

    https://github.com/DaGenix/rust-crypto/blob/cc1a5fde1ce957bd1a8a2e30169443cdb4780111/src/digest.rs#L77

    Sorry if it is too nit-picky, I just used the rust-analyzer "Go to Definition" and noticed.

    opened by Mr-Dispatch 0
  • aes::cbc_encryptor result not Send

    aes::cbc_encryptor result not Send

    Is there any reason for aes::cbc_encryptor (& co) to return a Box<dyn Encryptor + 'static> and not a Box<dyn Encryptor + Send + 'static> ? The CbcEncryptor it returns is Send and the function requires a PaddingProcessor+Send.

    opened by Emm54321 0
Releases(v0.2.36)
  • v0.2.36(May 20, 2016)

  • v0.2.35(Apr 4, 2016)

    • Improve cross compiling from GCC to msvc.
    • Fix BCrypt algorithm when using a cost of 31.
    • Improve building on OpenBSD.
    • Add implementation of SHA3 digest function.
    • Fix errors in Blake2b that could lead to incorrect output. The Blake2b initialization functions are modified to take parameters by value instead of by reference, which may break users of the interfaces.
    Source code(tar.gz)
    Source code(zip)
Owner
null
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
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
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
A pure-Rust implementation of various threshold secret sharing schemes

Threshold Secret Sharing Efficient pure-Rust library for secret sharing, offering efficient share generation and reconstruction for both traditional S

Snips 137 Dec 29, 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
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
Collection of block cipher algorithms written in pure Rust

RustCrypto: block ciphers Collection of block ciphers and block modes written in pure Rust. Warnings Currently only the aes crate provides constant-ti

Rust Crypto 506 Jan 3, 2023
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
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
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
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
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