• Stars
    star
    168
  • Rank 224,172 (Top 5 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created over 3 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🔐 Encrypts all the Serialize.

serde-encrypt

crates.io Crates.io docs.rs MSRV ci codecov License: MIT License: Apache 2.0

serde-encrypt logo

🔐 Encrypts all the Serialize.

               Alice                                         Bob
+-----------------------------------+        +-----------------------------------+
| #[derive(Serialize, Deserialize)] |        | #[derive(Serialize, Deserialize)] |
| struct Message                    |        | struct Message                    |
+-----------------------------------+        +-----------------------------------+
                 | .encrypt()                                  ^
                 v                                             | ::decrypt()
+-----------------------------------+        +-----------------------------------+
| struct EncryptedMessage           |        | struct EncryptedMessage           |
+-----------------------------------+        +-----------------------------------+
                 | .serialize()                                ^
                 v                                             | ::deserialize()
+-----------------------------------+        +-----------------------------------+
| struct Vec<u8>                    | -----> | struct Vec<u8>                    |
+-----------------------------------+        +-----------------------------------+

Overview

serde-encrypt encrypts/decrypts any structs and enums that implements serde::{Serialize, Deserialize}.

serde-encrypt supports both shared-key encryption (XChaCha20-Poly1305) and public-key encryption (XChaCha20-Poly1305 with X25519 key-exchange), both of which are considered to be secure enough.

serde-encrypt is optionally available in no_std environments.

[dependencies]
serde-encrypt = "(version)"  # If you use std
serde-encrypt = {version = "(version)", default-features = false}  # If you need no_std

Example

Good first example from shared key encryption test.

If you and your peer already have shared-key, just implement SerdeEncryptSharedKey trait to your Serialize and Deserialize data types.

#[derive(Debug, Serialize, Deserialize)]
struct Message {
    content: String,
    sender: String,
}

impl SerdeEncryptSharedKey for Message {
    type S = BincodeSerializer<Self>;  // you can specify serializer implementation (or implement it by yourself).
}

Then, you can serialize the Message into Vec<u8> in encrypted form.

    // Alternative:
    // const SHARED_KEY: SharedKey = SharedKey::new_const([0u8; 32]); 
    let shared_key = SharedKey::new([0u8; 32]); // or your peer reads from elsewhere.

    let msg = Message {
        content: "I ❤️ you.".to_string(),
        sender: "Alice".to_string(),
    };
    let encrypted_message = msg.encrypt(&shared_key)?;
    let serialized_encrypted_message: Vec<u8> = encrypted_message.serialize();

After your peer gets the binary, they can decrypt and deserialize it to Message.

    let shared_key = SharedKey::new([0u8; 32]);

    let encrypted_message = EncryptedMessage::deserialize(serialized_encrypted_message)?;
    let msg = Message::decrypt_owned(&encrypted_message, &shared_key);

Further examples...

Features and uses cases

Feature comparison

SerdeEncryptSharedKey SerdeEncryptSharedKeyDeterministic SerdeEncryptPublicKey
(a)symmetric? symmetric symmetric asymmetric
deterministic? (*1) no yes no
performance high high low

(*1) Deterministic encryptions always produce the same cipher-text from a given plain-text. More vulnerable but useful for equal-matching in cipher-text (e.g. RDBMS's encrypted index eq-search).

Encryption algorithm

SerdeEncryptSharedKey SerdeEncryptSharedKeyDeterministic SerdeEncryptPublicKey
key exchange - - X25519
encryption XChaCha20 XChaCha20 XChaCha20
message auth Poly1305 Poly1305 Poly1305
nonce (*2) XSalsa20 (random 24-byte) Fixed 24-byte XSalsa20 (random 24-byte)
Rng (*3) for nonce ChaCha20Rng - ChaCha20Rng
Implementation XChaCha20Poly1305 XChaCha20Poly1305 ChaChaBox

(*2) "Number used once": to make encryption non-deterministic. Although nonce for each encryption is not secret, nonce among different encryption must be different in order for attackers to get harder to guess plain-text.

(*3) Random number generator.

Serializer

Crate users can choose and even implement by themselves serialize representations in design.

Currently, the following serializers are built-in.

  • BincodeSerializer (only std feature)
    • Best choice for std to reduce message size in most cases.
  • PostcardSerializer
    • Best choice for no_std to reduce message size in most cases.
  • CborSerializer
    • Has large message size but deals with complex serde types. See Encrypts/Decrypts complex serde types example to check kind of serde types only CborSerializer can serialize.
    • Single available choice in serde-encrypt-sgx.
      • Both bincode and postcard crates cannot compile with Rust SGX SDK

Use cases

  • SerdeEncryptSharedKey
    • Both message sender and receiver already hold shared key.
    • Needs shared-key exchange via any safe way but wants high-speed encryption/decryption (e.g. communicates large amounts of messages).
  • SerdeEncryptSharedKeyDeterministic
    • Only when you need deterministic encryption for equal-matching in cipher-text.
    • Note that this is more vulnerable than SerdeEncryptSharedKey because, for example, attackers can find repeated patterns in cipher-text and then guess repeated patterns in plain-text.
  • SerdeEncryptPublicKey
    • To exchange SharedKey.
    • Quickly sends/receive small amounts of messages without secret shared key.

Rust SGX SDK support

Use serde-encrypt-sgx crate.

Feature flags

  • std (serde-encrypt [default] ; serde-encrypt-core [default])
    • std::error::Error trait implementation to serde_encrypt::Error.
    • Random number generator is created via SeedableRng::from_entropy(), which is considered to be more secure in OS-available environments.
    • BincodeSerializer available.

Implementation

Crates

serde-encrypt is a cargo workspace project and two crates are inside:

  • serde-encrypt-core
    • Encryption / Decryption implementations.
    • Traits for serialization / deserialization.
    • Traits for RNG (Random Number Generator) singleton.
  • serde-encrypt (depends on serde-encrypt-core)
    • Serialization / Deserialization impls.
    • RNG singleton impls.

serde-encrypt-sgx crate is also available in separate repository. It's in the same layer as serde-encrypt.

In order to use serde with Rust SGX SDK, people should use forked version serde-sgx. Also, Rust SGX SDK compiles with only old version of rustc (nightly-2020-10-25, currently), even simple no_std crate cannot build sometimes (e.g. spin crate cannot).

It is another choice to make serde-encrypt-sgx inside this repository using feature flags but it breaks cargo build --all-features in latest rustc.

Encryption

crypto_box crate is used both for public-key encryption and shared-key encryption.

Pure Rust implementation of the crypto_box public-key authenticated encryption scheme from NaCl-family libraries (e.g. libsodium, TweetNaCl) which combines the X25519 Diffie-Hellman function and the XSalsa20Poly1305 authenticated encryption cipher into an Elliptic Curve Integrated Encryption Scheme (ECIES).

Serialization

structs and enums to encrypt are serialized before encrypted. Built-in serializers are listed here.

Users can also implement TypedSerialized trait by themselves to get better serialization.

Changelog

See CHANGELOG.md.

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

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

More Repositories

1

rainbow_logging_handler

Ultimate Python colorized logger - https://pypi.python.org/pypi/rainbow_logging_handler
Python
77
star
2

trie-rs

Memory efficient trie (prefix tree) library based on LOUDS
Rust
49
star
3

PartialCsvParser

Parses specific part of CSV file. Used for PARALLEL CSV PARSING.
C++
25
star
4

SQLiteDbVisualizer

Visualize SQLite database fragmentation
Python
21
star
5

fid-rs

High performance FID (Fully Indexable Dictionary) library
Rust
20
star
6

louds-rs

High performance LOUDS (Level-Order Unary Degree Sequence) library
Rust
20
star
7

fst-rs

FST (Fast Succinct Trie) implementation in Rust
Rust
20
star
8

Lock-free_work-stealing_deque_in_C

Lock-free work stealing deque written in C. This is implemented after Chapter 16 of "The Art of Multiprocessor Programming."
C
19
star
9

MySQLite-Storage-Engine

MySQL storage engine that reads/writes SQLite database files.
C++
18
star
10

TheoryOfComputation

A memo of a lecture on Theory of Computation in the University of Tokyo.
TeX
17
star
11

ruby-benkyokai

Ruby初心者向け勉強会のレポジトリ
Ruby
14
star
12

mockall-example-rs

mockall を紹介する記事で扱うメアド帳アプリケーション
Rust
9
star
13

riscv64imac-hello-rs

A "Hellow World!" running on RISC-V (riscv64imac) written in Rust.
Dockerfile
7
star
14

Search-Fulltext

CPAN module supporting fulltext search
Perl
6
star
15

mysql-YetAnotherSkeletonEngine

Storage engine template working with MySQL 5.6 (or higher)
Shell
5
star
16

doc-view-fit-to-page

Fit-to-page extension for DocViewMode.
Emacs Lisp
5
star
17

resume-jp

公開職務経歴書
4
star
18

WelcomeToPython

Python初心者がPyPIライブラリを作れるように教育する(しごく)ためのレポジトリ
4
star
19

prml-python

PythonでPRMLの題材ゴニョゴニョしてニヨニヨする場
Python
4
star
20

h2o-ruby

Ruby
4
star
21

data-structures-and-algorithms-rs

ブログの連載『Rustではじめるデータ構造とアルゴリズム』のコード
Rust
4
star
22

WYSIWYG-TeX-el

WYSIWYG editting environment for TeX on Emacs.
Emacs Lisp
3
star
23

serde-encrypt-sgx

Rust SGX SDK compatible version of serde-encrypt
Rust
3
star
24

CursesImageViewer

An image (jpg/png/bmp/...) viewer works on curses.
C
3
star
25

ruby-finagle-thrift-client-example

finagle-thrift を使ったRPCクライアントのRuby最小(当社比)実装
Ruby
3
star
26

Java-mangling-problem-when-calling-from-Scala

Java
3
star
27

PyCC

Tiny C compiler writen in Python
C
2
star
28

miniCPU

A mini CPU which implements a subset of IA-32 instructions. This runs on ModelSim.
Verilog
2
star
29

dddfs_vis

DDDFS Visualizer
JavaScript
2
star
30

thinkvol

A volume controler for X on ThinkPad T400s.
Python
2
star
31

rust-RwLock-writer-starvation

Rust
2
star
32

streaming101-beam-opendata

Apache Beamとオープンデータで始めるストリーム処理入門
Java
2
star
33

sqlite3_benchmark

Flexible SQLite benchmark toolsets. Easily get result graphs.
Python
2
star
34

PEN200-OSCP-DynamicCheatSheat

A dynamic cheat sheet for PEN-200 and OSCP made with Google Sheets
2
star
35

web2bibtex

Input URL, and get the web page info in bibtex format.
Python
1
star
36

shellstreaming

A stream processor working with shell commands
Python
1
star
37

succinct.rs

[DEPRECATED] Succinct Data Structures library for Rust
Rust
1
star
38

safe_rm

`rm xxx' to `mv xxx ~/.Trash'
Python
1
star
39

isucon-renshu-20160904

滝行
Ruby
1
star
40

docker-ubuntu-vivado

XilinxのVivadoが入ったイメージを作る
Dockerfile
1
star
41

radicon

ラジコン作るよ!!
C
1
star
42

8-puzzle-solver

Solves 8-puzzle.
C++
1
star