referrerpolicy=no-referrer-when-downgrade

sp_statement_store/
ecies.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18// tag::description[]
19//! ECIES encryption scheme using x25519 key exchange and AEAD.
20// end::description[]
21
22use aes_gcm::{aead::Aead, AeadCore, KeyInit};
23use rand::rngs::OsRng;
24use sha2::Digest;
25use sp_core::crypto::Pair;
26
27/// x25519 secret key.
28pub type SecretKey = x25519_dalek::StaticSecret;
29/// x25519 public key.
30pub type PublicKey = x25519_dalek::PublicKey;
31
32/// Encryption or decryption error.
33#[derive(Debug, PartialEq, Eq, thiserror::Error)]
34pub enum Error {
35	/// Generic AES encryption error.
36	#[error("Encryption error")]
37	Encryption,
38	/// Generic AES decryption error.
39	#[error("Decryption error")]
40	Decryption,
41	/// Error reading key data. Not enough data in the buffer.
42	#[error("Bad cypher text")]
43	BadData,
44}
45
46const NONCE_LEN: usize = 12;
47const PK_LEN: usize = 32;
48const AES_KEY_LEN: usize = 32;
49
50fn aes_encrypt(key: &[u8; AES_KEY_LEN], nonce: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, Error> {
51	let enc = aes_gcm::Aes256Gcm::new(key.into());
52
53	enc.encrypt(nonce.into(), aes_gcm::aead::Payload { msg: plaintext, aad: b"" })
54		.map_err(|_| Error::Encryption)
55}
56
57fn aes_decrypt(key: &[u8; AES_KEY_LEN], nonce: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, Error> {
58	let dec = aes_gcm::Aes256Gcm::new(key.into());
59	dec.decrypt(nonce.into(), aes_gcm::aead::Payload { msg: ciphertext, aad: b"" })
60		.map_err(|_| Error::Decryption)
61}
62
63fn kdf(shared_secret: &[u8]) -> [u8; AES_KEY_LEN] {
64	let hkdf = hkdf::Hkdf::<sha2::Sha256>::new(None, shared_secret);
65	let mut aes_key = [0u8; AES_KEY_LEN];
66	hkdf.expand(b"", &mut aes_key)
67		.expect("There's always enough data for derivation. qed.");
68	aes_key
69}
70
71/// Encrypt `plaintext` with the given public x25519 public key. Decryption can be performed with
72/// the matching secret key.
73pub fn encrypt_x25519(pk: &PublicKey, plaintext: &[u8]) -> Result<Vec<u8>, Error> {
74	let ephemeral_sk = x25519_dalek::StaticSecret::random_from_rng(OsRng);
75	let ephemeral_pk = x25519_dalek::PublicKey::from(&ephemeral_sk);
76
77	let mut shared_secret = ephemeral_sk.diffie_hellman(pk).to_bytes().to_vec();
78	shared_secret.extend_from_slice(ephemeral_pk.as_bytes());
79
80	let aes_key = kdf(&shared_secret);
81
82	let nonce = aes_gcm::Aes256Gcm::generate_nonce(OsRng);
83	let ciphertext = aes_encrypt(&aes_key, &nonce, plaintext)?;
84
85	let mut out = Vec::with_capacity(ciphertext.len() + PK_LEN + NONCE_LEN);
86	out.extend_from_slice(ephemeral_pk.as_bytes());
87	out.extend_from_slice(nonce.as_slice());
88	out.extend_from_slice(ciphertext.as_slice());
89
90	Ok(out)
91}
92
93/// Encrypt `plaintext` with the given ed25519 public key. Decryption can be performed with the
94/// matching secret key.
95pub fn encrypt_ed25519(pk: &sp_core::ed25519::Public, plaintext: &[u8]) -> Result<Vec<u8>, Error> {
96	let ed25519 = curve25519_dalek::edwards::CompressedEdwardsY(pk.0);
97	let x25519 = ed25519.decompress().ok_or(Error::BadData)?.to_montgomery();
98	let montgomery = x25519_dalek::PublicKey::from(x25519.to_bytes());
99	encrypt_x25519(&montgomery, plaintext)
100}
101
102/// Decrypt with the given x25519 secret key.
103pub fn decrypt_x25519(sk: &SecretKey, encrypted: &[u8]) -> Result<Vec<u8>, Error> {
104	if encrypted.len() < PK_LEN + NONCE_LEN {
105		return Err(Error::BadData)
106	}
107	let mut ephemeral_pk: [u8; PK_LEN] = Default::default();
108	ephemeral_pk.copy_from_slice(&encrypted[0..PK_LEN]);
109	let ephemeral_pk = PublicKey::from(ephemeral_pk);
110
111	let mut shared_secret = sk.diffie_hellman(&ephemeral_pk).to_bytes().to_vec();
112	shared_secret.extend_from_slice(ephemeral_pk.as_bytes());
113
114	let aes_key = kdf(&shared_secret);
115
116	let nonce = &encrypted[PK_LEN..PK_LEN + NONCE_LEN];
117	aes_decrypt(&aes_key, &nonce, &encrypted[PK_LEN + NONCE_LEN..])
118}
119
120/// Decrypt with the given ed25519 key pair.
121pub fn decrypt_ed25519(pair: &sp_core::ed25519::Pair, encrypted: &[u8]) -> Result<Vec<u8>, Error> {
122	let raw = pair.to_raw_vec();
123	let hash: [u8; 32] = sha2::Sha512::digest(&raw).as_slice()[..32]
124		.try_into()
125		.map_err(|_| Error::Decryption)?;
126	let secret = x25519_dalek::StaticSecret::from(hash);
127	decrypt_x25519(&secret, encrypted)
128}
129
130#[cfg(test)]
131mod test {
132	use super::*;
133	use rand::rngs::OsRng;
134	use sp_core::crypto::Pair;
135
136	#[test]
137	fn basic_x25519_encryption() {
138		let sk = SecretKey::random_from_rng(OsRng);
139		let pk = PublicKey::from(&sk);
140
141		let plain_message = b"An important secret message";
142		let encrypted = encrypt_x25519(&pk, plain_message).unwrap();
143
144		let decrypted = decrypt_x25519(&sk, &encrypted).unwrap();
145		assert_eq!(plain_message, decrypted.as_slice());
146	}
147
148	#[test]
149	fn basic_ed25519_encryption() {
150		let (pair, _) = sp_core::ed25519::Pair::generate();
151		let pk = pair.public();
152
153		let plain_message = b"An important secret message";
154		let encrypted = encrypt_ed25519(&pk, plain_message).unwrap();
155
156		let decrypted = decrypt_ed25519(&pair, &encrypted).unwrap();
157		assert_eq!(plain_message, decrypted.as_slice());
158	}
159
160	#[test]
161	fn fails_on_bad_data() {
162		let sk = SecretKey::random_from_rng(OsRng);
163		let pk = PublicKey::from(&sk);
164
165		let plain_message = b"An important secret message";
166		let encrypted = encrypt_x25519(&pk, plain_message).unwrap();
167
168		assert_eq!(decrypt_x25519(&sk, &[]), Err(Error::BadData));
169		assert_eq!(
170			decrypt_x25519(&sk, &encrypted[0..super::PK_LEN + super::NONCE_LEN - 1]),
171			Err(Error::BadData)
172		);
173	}
174}