Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Added ECIES encryption #13832

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 15 additions & 1 deletion client/keystore/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use sp_application_crypto::{AppCrypto, AppPair, IsWrappedBy};
use sp_core::{bls377, bls381};
use sp_core::{
crypto::{ByteArray, ExposeSecret, KeyTypeId, Pair as CorePair, SecretString, VrfSecret},
ecdsa, ed25519, sr25519,
ecdsa, ecies, ed25519, sr25519,
};
use sp_keystore::{Error as TraitError, Keystore, KeystorePtr};
use std::{
Expand Down Expand Up @@ -196,6 +196,20 @@ impl Keystore for LocalKeystore {
self.sign::<ed25519::Pair>(key_type, public, msg)
}

fn ed25519_decrypt(
&self,
key_type: KeyTypeId,
public: &ed25519::Public,
msg: &[u8],
) -> std::result::Result<Option<Vec<u8>>, TraitError> {
self.0
.read()
.key_pair_by_type::<ed25519::Pair>(public, key_type)?
.map(|pair| ecies::decrypt_ed25519(&pair, msg))
.transpose()
.map_err(|e| TraitError::Other(format!("Decryption error: {:?}", e)))
}

fn ecdsa_public_keys(&self, key_type: KeyTypeId) -> Vec<ecdsa::Public> {
self.public_keys::<ecdsa::Pair>(key_type)
}
Expand Down
16 changes: 15 additions & 1 deletion primitives/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ thiserror = { version = "1.0.30", optional = true }
bitflags = "1.3"
paste = "1.0.7"

# ECIES dependencies
ed25519-dalek = { version = "1.0", optional = true }
x25519-dalek = { version = "2.0.0-pre.1", optional = true }
curve25519-dalek = { version = "3.2", optional = true }
aes-gcm = { version = "0.10", optional = true }
hkdf = { version = "0.12.0", optional = true }
sha2 = { version = "0.10.0", optional = true }

# full crypto
array-bytes = { version = "4.1", optional = true }
ed25519-zebra = { version = "3.1.0", default-features = false, optional = true }
Expand All @@ -57,7 +65,6 @@ w3f-bls = { version = "0.1.3", default-features = false, optional = true}

[dev-dependencies]
sp-serializer = { version = "4.0.0-dev", path = "../serializer" }
rand = "0.8.5"
criterion = "0.4.0"
serde_json = "1.0"
sp-core-hashing-proc-macro = { version = "5.0.0", path = "./hashing/proc-macro" }
Expand Down Expand Up @@ -114,6 +121,13 @@ std = [
"futures/thread-pool",
"libsecp256k1/std",
"dyn-clonable",

"ed25519-dalek",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am a bit ~ with this ed25519 story, but guess here we needed ed25519-dalek (in addition to already included zebra) to be able to use x25 dalek ? (remember something like this on mixnet).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, ed25519-zebra provide a limitied API for signinig/verification only. We need ECDH exchange here.

"x25519-dalek",
"curve25519-dalek",
"aes-gcm",
"hkdf",
"sha2",
]

# This feature enables all crypto primitives for `no_std` builds like microcontrollers
Expand Down
178 changes: 178 additions & 0 deletions primitives/core/src/ecies.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// tag::description[]
//! ECIES encryption scheme using x25519 key exchange and AEAD.
// end::description[]

use crate::crypto::Pair;
use aes_gcm::{aead::Aead, KeyInit};
use rand::{rngs::OsRng, RngCore};
use sha2::Digest;

/// x25519 secret key.
pub type SecretKey = x25519_dalek::StaticSecret;
/// x25519 public key.
pub type PublicKey = x25519_dalek::PublicKey;

/// Encryption or decryption error.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum Error {
/// Generic AES encryption error.
#[error("Encryption error")]
Encryption,
/// Generic AES decryption error.
#[error("Decryption error")]
Decryption,
/// Error reading key data. Not enough data in the buffer.
#[error("Bad cypher text")]
BadData,
}

const NONCE_LEN: usize = 12;
const PK_LEN: usize = 32;
const AES_KEY_LEN: usize = 32;

fn aes_encrypt(key: &[u8; AES_KEY_LEN], nonce: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, Error> {
let enc = aes_gcm::Aes256Gcm::new(key.into());

enc.encrypt(nonce.into(), aes_gcm::aead::Payload { msg: plaintext, aad: b"" })
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we use aad to some additional kdf content?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I understand aad is not that useful as long as we use a new unique ephemeral key for each encryption.

.map_err(|_| Error::Encryption)
}

fn aes_decrypt(key: &[u8; AES_KEY_LEN], nonce: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, Error> {
let dec = aes_gcm::Aes256Gcm::new(key.into());
dec.decrypt(nonce.into(), aes_gcm::aead::Payload { msg: ciphertext, aad: b"" })
.map_err(|_| Error::Decryption)
}

fn kdf(shared_secret: &[u8]) -> [u8; AES_KEY_LEN] {
cheme marked this conversation as resolved.
Show resolved Hide resolved
let hkdf = hkdf::Hkdf::<sha2::Sha256>::new(None, shared_secret);
let mut aes_key = [0u8; AES_KEY_LEN];
hkdf.expand(b"", &mut aes_key)
.expect("There's always enough data for derivation.");
aes_key
}

/// Encrypt `plaintext` with the given public x25519 public key. Decryption can be performed with
/// the matching secret key.
pub fn encrypt_x25519(pk: &PublicKey, plaintext: &[u8]) -> Result<Vec<u8>, Error> {
let ephemeral_sk = x25519_dalek::StaticSecret::new(OsRng);
let ephemeral_pk = x25519_dalek::PublicKey::from(&ephemeral_sk);

let mut shared_secret = ephemeral_sk.diffie_hellman(pk).to_bytes().to_vec();
shared_secret.extend_from_slice(ephemeral_pk.as_bytes());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could be ephemeral_pk then shared_secret. I don t think it matter (and found it describe in the order you use).


let aes_key = kdf(&shared_secret);

let mut nonce = [0u8; NONCE_LEN];
OsRng.fill_bytes(&mut nonce);
cheme marked this conversation as resolved.
Show resolved Hide resolved
let ciphertext = aes_encrypt(&aes_key, &nonce, plaintext)?;

let mut out = Vec::with_capacity(ciphertext.len() + PK_LEN + NONCE_LEN);
out.extend_from_slice(ephemeral_pk.as_bytes());
out.extend_from_slice(nonce.as_slice());
out.extend_from_slice(ciphertext.as_slice());

Ok(out)
}

/// Encrypt `plaintext` with the given ed25519 public key. Decryption can be performed with the
/// matching secret key.
pub fn encrypt_ed25519(pk: &crate::ed25519::Public, plaintext: &[u8]) -> Result<Vec<u8>, Error> {
let ed25519 = curve25519_dalek::edwards::CompressedEdwardsY(pk.0);
let x25519 = ed25519
.decompress()
.ok_or(Error::BadData)
.expect("The compressed point is invalid")
.to_montgomery();
let montgomery = x25519_dalek::PublicKey::from(x25519.to_bytes());
encrypt_x25519(&montgomery, plaintext)
}

/// Decrypt with the given x25519 secret key.
pub fn decrypt_x25519(sk: &SecretKey, encrypted: &[u8]) -> Result<Vec<u8>, Error> {
if encrypted.len() < PK_LEN + NONCE_LEN {
return Err(Error::BadData)
}
let mut ephemeral_pk: [u8; PK_LEN] = Default::default();
ephemeral_pk.copy_from_slice(&encrypted[0..PK_LEN]);
let ephemeral_pk = PublicKey::from(ephemeral_pk);

let mut shared_secret = sk.diffie_hellman(&ephemeral_pk).to_bytes().to_vec();
shared_secret.extend_from_slice(ephemeral_pk.as_bytes());

let aes_key = kdf(&shared_secret);

let nonce = &encrypted[PK_LEN..PK_LEN + NONCE_LEN];
aes_decrypt(&aes_key, &nonce, &encrypted[PK_LEN + NONCE_LEN..])
}

/// Decrypt with the given ed25519 key pair.
pub fn decrypt_ed25519(pair: &crate::ed25519::Pair, encrypted: &[u8]) -> Result<Vec<u8>, Error> {
let raw = pair.to_raw_vec();
let hash: [u8; 32] =
sha2::Sha512::digest(&raw).as_slice()[..32].try_into().expect("Hashing error");
let secret = x25519_dalek::StaticSecret::from(hash);
decrypt_x25519(&secret, encrypted)
}

#[cfg(test)]
mod test {
use super::*;
use crate::crypto::Pair;
use rand::rngs::OsRng;

#[test]
fn basic_x25519_encryption() {
let sk = SecretKey::new(OsRng);
let pk = PublicKey::from(&sk);

let plain_message = b"An important secret message";
let encrypted = encrypt_x25519(&pk, plain_message).unwrap();

let decrypted = decrypt_x25519(&sk, &encrypted).unwrap();
assert_eq!(plain_message, decrypted.as_slice());
}

#[test]
fn basic_ed25519_encryption() {
let (pair, _) = crate::ed25519::Pair::generate();
let pk = pair.into();

let plain_message = b"An important secret message";
let encrypted = encrypt_ed25519(&pk, plain_message).unwrap();

let decrypted = decrypt_ed25519(&pair, &encrypted).unwrap();
assert_eq!(plain_message, decrypted.as_slice());
}

#[test]
fn fails_on_bad_data() {
let sk = SecretKey::new(OsRng);
let pk = PublicKey::from(&sk);

let plain_message = b"An important secret message";
let encrypted = encrypt_x25519(&pk, plain_message).unwrap();

assert_eq!(decrypt_x25519(&sk, &[]), Err(Error::BadData));
assert_eq!(
decrypt_x25519(&sk, &encrypted[0..super::PK_LEN + super::NONCE_LEN - 1]),
Err(Error::BadData)
);
}
}
2 changes: 2 additions & 0 deletions primitives/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ pub use paste;
pub mod bls;
pub mod defer;
pub mod ecdsa;
#[cfg(feature = "std")]
pub mod ecies;
pub mod ed25519;
pub mod hash;
#[cfg(feature = "std")]
Expand Down
15 changes: 15 additions & 0 deletions primitives/keystore/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,21 @@ pub trait Keystore: Send + Sync {
msg: &[u8],
) -> Result<Option<ed25519::Signature>, Error>;

/// Decrypt a message with a given ed25519 key.
///
/// Receives [`KeyTypeId`] and an [`ed25519::Public`] key to be able to map
/// them to a private key that exists in the keystore.
///
/// Returns an decrypted [`Vec<u8>`] or `None` in case the given `key_type`
/// and `public` combination doesn't exist in the keystore.
/// An `Err` will be returned if decryption has failed.
fn ed25519_decrypt(
&self,
key_type: KeyTypeId,
public: &ed25519::Public,
msg: &[u8],
) -> Result<Option<Vec<u8>>, Error>;

/// Returns all ecdsa public keys for the given key type.
fn ecdsa_public_keys(&self, key_type: KeyTypeId) -> Vec<ecdsa::Public>;

Expand Down
14 changes: 13 additions & 1 deletion primitives/keystore/src/testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::{Error, Keystore, KeystorePtr};
use sp_core::{bls377, bls381};
use sp_core::{
crypto::{ByteArray, KeyTypeId, Pair, VrfSecret},
ecdsa, ed25519, sr25519,
ecdsa, ecies, ed25519, sr25519,
};

use parking_lot::RwLock;
Expand Down Expand Up @@ -183,6 +183,18 @@ impl Keystore for MemoryKeystore {
self.sign::<ed25519::Pair>(key_type, public, msg)
}

fn ed25519_decrypt(
&self,
key_type: KeyTypeId,
public: &ed25519::Public,
msg: &[u8],
) -> Result<Option<Vec<u8>>, Error> {
self.pair::<ed25519::Pair>(key_type, public)
.map(|pair| ecies::decrypt_ed25519(&pair, msg))
.transpose()
.map_err(|e| Error::Other(format!("Decryption error: {:?}", e)))
}

fn ecdsa_public_keys(&self, key_type: KeyTypeId) -> Vec<ecdsa::Public> {
self.public_keys::<ecdsa::Pair>(key_type)
}
Expand Down