diff --git a/Cargo.lock b/Cargo.lock index c0fec247086746c3e2d8776688cf5dc01d270de0..afae57ad242f3450d3b4a50a06176656bd081705 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -396,7 +396,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "dup-crypto-tests-tools 0.1.0", "durs-bc-db-reader 0.3.0-dev", "durs-bc-db-writer 0.3.0-dev", @@ -715,7 +715,7 @@ dependencies = [ "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", "dubp-user-docs-tests-tools 0.1.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "json-pest-parser 0.2.0", @@ -738,7 +738,7 @@ dependencies = [ "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", "dubp-user-docs-tests-tools 0.1.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "dup-crypto-tests-tools 0.1.0", "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "json-pest-parser 0.2.0", @@ -748,7 +748,7 @@ dependencies = [ name = "dubp-common-doc" version = "0.1.0" dependencies = [ - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "json-pest-parser 0.2.0", @@ -780,7 +780,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -795,7 +795,7 @@ name = "dubp-user-docs" version = "0.14.0" dependencies = [ "dubp-common-doc 0.1.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "json-pest-parser 0.2.0", @@ -817,7 +817,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "dup-crypto-tests-tools 0.1.0", ] @@ -839,9 +839,9 @@ dependencies = [ [[package]] name = "dup-crypto" version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "base64 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bincode 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "bs58 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "ring 0.16.9 (registry+https://github.com/rust-lang/crates.io-index)", @@ -856,7 +856,7 @@ dependencies = [ name = "dup-crypto-tests-tools" version = "0.1.0" dependencies = [ - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -869,7 +869,7 @@ dependencies = [ "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", "dubp-user-docs-tests-tools 0.1.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "dup-crypto-tests-tools 0.1.0", "durs-bc-db-reader 0.3.0-dev", "durs-bc-db-writer 0.3.0-dev", @@ -909,7 +909,7 @@ dependencies = [ "dubp-indexes 0.1.0", "dubp-user-docs 0.14.0", "dubp-user-docs-tests-tools 0.1.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "dup-crypto-tests-tools 0.1.0", "durs-common-tests-tools 0.1.0", "durs-common-tools 0.2.0", @@ -936,7 +936,7 @@ dependencies = [ "dubp-indexes 0.1.0", "dubp-user-docs 0.14.0", "dubp-user-docs-tests-tools 0.1.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "dup-crypto-tests-tools 0.1.0", "durs-bc-db-reader 0.3.0-dev", "durs-common-tests-tools 0.1.0", @@ -975,7 +975,7 @@ dependencies = [ "dirs 2.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "durs-message 0.3.0-dev", "durs-module 0.3.0-dev", @@ -998,7 +998,7 @@ dependencies = [ "chrono 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "dubp-currency-params 0.2.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-bc 0.3.0-dev", "durs-bc-db-reader 0.3.0-dev", "durs-common-tools 0.2.0", @@ -1047,7 +1047,7 @@ dependencies = [ "dubp-blocks-tests-tools 0.1.0", "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "dup-crypto-tests-tools 0.1.0", "durs-bc-db-reader 0.3.0-dev", "durs-common-tools 0.2.0", @@ -1075,7 +1075,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-module 0.3.0-dev", "durs-network 0.3.0-dev", "durs-network-documents 0.4.0", @@ -1090,7 +1090,7 @@ version = "0.3.0-dev" dependencies = [ "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "durs-network-documents 0.4.0", "envy 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1109,7 +1109,7 @@ dependencies = [ "dubp-block-doc 0.1.0", "dubp-common-doc 0.1.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "durs-module 0.3.0-dev", "durs-network-documents 0.4.0", @@ -1128,7 +1128,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tests-tools 0.1.0", "durs-common-tools 0.2.0", "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1150,7 +1150,7 @@ version = "0.1.0" dependencies = [ "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "durs-conf 0.3.0-dev", "durs-message 0.3.0-dev", @@ -1170,7 +1170,7 @@ version = "0.3.0-dev" dependencies = [ "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "durs-conf 0.3.0-dev", "durs-message 0.3.0-dev", @@ -1191,7 +1191,7 @@ name = "durs-wot" version = "0.8.0-a0.9" dependencies = [ "bincode 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "rayon 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1206,7 +1206,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tests-tools 0.1.0", "durs-common-tools 0.2.0", "durs-conf 0.3.0-dev", @@ -1238,7 +1238,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "durs-network-documents 0.4.0", "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1257,7 +1257,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "durs-module 0.3.0-dev", "durs-network-documents 0.4.0", @@ -1279,7 +1279,7 @@ dependencies = [ "dubp-common-doc 0.1.0", "dubp-currency-params 0.2.0", "dubp-user-docs 0.14.0", - "dup-crypto 0.8.0", + "dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "durs-common-tools 0.2.0", "durs-conf 0.3.0-dev", "durs-message 0.3.0-dev", @@ -3199,6 +3199,7 @@ dependencies = [ "checksum dirs-sys 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "afa0b23de8fd801745c471deffa6e12d248f962c9fd4b4c33787b055599bde7b" "checksum downcast 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4bb454f0228b18c7f4c3b0ebbee346ed9c52e7443b0999cd543ff3571205701d" "checksum dtoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "ea57b42383d091c85abcc2706240b94ab2a8fa1fc81c10ff23c4de06e2a90b5e" +"checksum dup-crypto 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6dddcce79edf70a20334a520d6a467404d8b6a44cea109ea4b50c36884e5c2d8" "checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" "checksum encoding_rs 0.8.22 (registry+https://github.com/rust-lang/crates.io-index)" = "cd8d03faa7fe0c1431609dfad7bbe827af30f82e1e2ae6f7ee4fca6bd764bc28" "checksum enum-as-inner 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "900a6c7fbe523f4c2884eaf26b57b81bb69b6810a01a236390a7ac021d09492e" diff --git a/Cargo.toml b/Cargo.toml index 43874c823dedd5fd6c3ff3fc1626aa77e8b69bb5..93eac8aad6fe96141f1bbfc74d36b8ac7ead91e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,6 @@ members = [ "lib/core/message", "lib/core/module", "lib/core/network", - "lib/crypto", "lib/dubp/block-doc", "lib/dubp/common-doc", "lib/dubp/currency-params", diff --git a/lib/core/conf/Cargo.toml b/lib/core/conf/Cargo.toml index 3c510c8492031ee275c57498c3bfe1e0d8225cd8..7c2092f465fd81763c5b12254fc963de8e9e930a 100644 --- a/lib/core/conf/Cargo.toml +++ b/lib/core/conf/Cargo.toml @@ -11,7 +11,7 @@ path = "src/lib.rs" [dependencies] dirs = "2.0.2" -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs= { path = "../../dubp/user-docs" } durs-message = { path = "../message" } diff --git a/lib/core/core/Cargo.toml b/lib/core/core/Cargo.toml index 3e5bffb6cfba707910822443f8197f590eb77911..96b60338ee07de6ee0981f0dddc2311fff856a16 100644 --- a/lib/core/core/Cargo.toml +++ b/lib/core/core/Cargo.toml @@ -17,7 +17,7 @@ durs-common-tools = { path = "../../tools/common-tools" } durs-bc-db-reader = { path = "../../modules-lib/bc-db-reader" } durs-conf = { path = "../conf" } durs-dbs-tools = { path = "../../tools/dbs-tools" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" dubp-currency-params = { path = "../../dubp/currency-params" } durs-message = { path = "../message" } durs-module = { path = "../module" } diff --git a/lib/core/message/Cargo.toml b/lib/core/message/Cargo.toml index 96c9a980002b11cf0ee066691eb6f7cc01d28e0e..2952c8705bbf9a256511aa9cf584add2b380c7fd 100644 --- a/lib/core/message/Cargo.toml +++ b/lib/core/message/Cargo.toml @@ -14,7 +14,7 @@ dubp-block-doc = { path = "../../dubp/block-doc"} #, version = "0.1.0" } dubp-common-doc = { path = "../../dubp/common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs= { path = "../../dubp/user-docs" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" durs-module = { path = "../module" } durs-network = { path = "../network" } durs-network-documents = { path = "../../dunp/network-documents" } diff --git a/lib/core/module/Cargo.toml b/lib/core/module/Cargo.toml index 54f5dde4aaa1a1ab3ec58a7dfb30fe889ffd658e..4d512129e548476ed8e9c85d72bbda83c6022f30 100644 --- a/lib/core/module/Cargo.toml +++ b/lib/core/module/Cargo.toml @@ -10,7 +10,7 @@ edition = "2018" path = "src/lib.rs" [dependencies] -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs = { path = "../../dubp/user-docs" } durs-common-tools = { path = "../../tools/common-tools" } diff --git a/lib/core/network/Cargo.toml b/lib/core/network/Cargo.toml index e3f21db2664652debe19a2ab5bafc1b0a55a0c51..863b381e3b64970c0730a70f53ad1b7d1b18c054 100644 --- a/lib/core/network/Cargo.toml +++ b/lib/core/network/Cargo.toml @@ -13,7 +13,7 @@ path = "lib.rs" dubp-block-doc = { path = "../../dubp/block-doc"} #, version = "0.1.0" } dubp-common-doc = { path = "../../dubp/common-doc"} #, version = "0.1.0" } dubp-user-docs= { path = "../../dubp/user-docs" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" durs-common-tools = { path = "../../tools/common-tools" } durs-module = { path = "../module" } durs-network-documents = { path = "../../dunp/network-documents" } diff --git a/lib/crypto/Cargo.toml b/lib/crypto/Cargo.toml deleted file mode 100644 index 9968949adbafe7bda85fd9f95ce7e22a1c2ef3d4..0000000000000000000000000000000000000000 --- a/lib/crypto/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "dup-crypto" -version = "0.8.0" -authors = ["nanocryk <nanocryk@duniter.org>", "elois <elois@duniter.org>"] -description = "Manage cryptographic operations for DUPs (DUniter Protocols)." -repository = "https://git.duniter.org/nodes/rust/duniter-rs" -readme = "README.md" -keywords = ["duniter", "keys", "cryptography"] -license = "AGPL-3.0" -edition = "2018" - -[lib] -path = "src/lib.rs" - -[dependencies] -base64 = "0.11.0" -bs58 = "0.3.0" -byteorder = "1.3.2" -ring = "0.16.9" -scrypt = { version = "0.2", default-features = false } -serde = { version = "1.0.*", features = ["derive"] } -thiserror = "1.0.11" -unwrap = "1.2.1" -zeroize = { version = "1.1.0", features = ["zeroize_derive"] } - -[dev-dependencies] -bincode = "1.2.0" - -[features] diff --git a/lib/crypto/README.md b/lib/crypto/README.md deleted file mode 100644 index 889c8c0e0f2456756fc5f6e9b0f0f32fff040130..0000000000000000000000000000000000000000 --- a/lib/crypto/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# crypto - -`dup-crypto` is a crate managing cryptographic operations for the DUP (DUniter Protocol). - -## How to use it - -You can add `dup-crypto` as a `cargo` dependency in your Rust project. diff --git a/lib/crypto/src/bases/b16.rs b/lib/crypto/src/bases/b16.rs deleted file mode 100644 index 91e36345beb6d639deabe38bf89838aefaf4aede..0000000000000000000000000000000000000000 --- a/lib/crypto/src/bases/b16.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Provide base16 convertion tools - -use crate::bases::BaseConvertionError; - -/// Convert a hexadecimal string in an array of 32 bytes. -/// -/// The hex string must only contains hex characters -/// and produce a 32 bytes value. -pub fn str_hex_to_32bytes(text: &str) -> Result<[u8; 32], BaseConvertionError> { - if text.len() != 64 { - Err(BaseConvertionError::InvalidLength { - expected: 64, - found: text.len(), - }) - } else { - let mut bytes = [0u8; 32]; - - let chars: Vec<char> = text.chars().collect(); - - for i in 0..64 { - if i % 2 != 0 { - continue; - } - - let byte1 = chars[i].to_digit(16); - let byte2 = chars[i + 1].to_digit(16); - - if let Some(byte1) = byte1 { - if let Some(byte2) = byte2 { - let byte = ((byte1 as u8) << 4) | byte2 as u8; - bytes[i / 2] = byte; - } else { - return Err(BaseConvertionError::InvalidCharacter { - character: chars[i + 1], - offset: i + 1, - }); - } - } else { - return Err(BaseConvertionError::InvalidCharacter { - character: chars[i], - offset: i, - }); - } - } - - Ok(bytes) - } -} diff --git a/lib/crypto/src/bases/b58.rs b/lib/crypto/src/bases/b58.rs deleted file mode 100644 index fea202ca5ebea468c46cefecea6866d2f52edcfc..0000000000000000000000000000000000000000 --- a/lib/crypto/src/bases/b58.rs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Provide base58 convertion tools - -use crate::bases::BaseConvertionError; - -/// Convert to base58 string -pub trait ToBase58 { - /// Convert to base58 string - fn to_base58(&self) -> String; -} - -/// Create an array of 32 bytes from a Base58 string. -pub fn str_base58_to_32bytes(base58_data: &str) -> Result<([u8; 32], usize), BaseConvertionError> { - match bs58::decode(base58_data).into_vec() { - Ok(result) => { - let len = result.len(); - if len <= 32 { - let mut u8_array = [0; 32]; - - u8_array[..len].clone_from_slice(&result[..len]); - - Ok((u8_array, len)) - } else { - Err(BaseConvertionError::InvalidLength { - expected: 32, - found: len, - }) - } - } - Err(bs58::decode::Error::InvalidCharacter { character, index }) => { - Err(BaseConvertionError::InvalidCharacter { - character, - offset: index, - }) - } - Err(bs58::decode::Error::BufferTooSmall) => { - Err(BaseConvertionError::InvalidBaseConverterLength) - } - _ => Err(BaseConvertionError::UnknownError), - } -} - -/// Create a Base58 string from a slice of bytes. -pub fn bytes_to_str_base58(bytes: &[u8]) -> String { - bs58::encode(bytes).into_string() -} - -/*/// Create an array of 64bytes from a Base58 string. -pub fn str_base58_to_64bytes(base58_data: &str) -> Result<[u8; 64], BaseConvertionError> { - match base58_data.from_base58() { - Ok(result) => { - if result.len() == 64 { - let mut u8_array = [0; 64]; - - u8_array[..64].clone_from_slice(&result[..64]); - - Ok(u8_array) - } else { - Err(BaseConvertionError::InvalidLength { - expected: 64, - found: result.len(), - }) - } - } - Err(FromBase58Error::InvalidBase58Character(character, offset)) => { - Err(BaseConvertionError::InvalidCharacter { character, offset }) - } - Err(FromBase58Error::InvalidBase58Length) => { - Err(BaseConvertionError::InvalidBaseConverterLength) - } - } -}*/ diff --git a/lib/crypto/src/bases/b64.rs b/lib/crypto/src/bases/b64.rs deleted file mode 100644 index 4cec3382262222b1d96c0ff85100f40c4860e222..0000000000000000000000000000000000000000 --- a/lib/crypto/src/bases/b64.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Provide base64 convertion tools - -use crate::bases::BaseConvertionError; - -/// Create an array of 64 bytes from a Base64 string. -pub fn str_base64_to64bytes(base64_data: &str) -> Result<[u8; 64], BaseConvertionError> { - let result = base64::decode(base64_data)?; - - if result.len() == 64 { - let mut u8_array = [0; 64]; - u8_array[..64].clone_from_slice(&base64::decode(base64_data)?[..64]); - - Ok(u8_array) - } else { - Err(BaseConvertionError::InvalidLength { - found: result.len(), - expected: 64, - }) - } -} diff --git a/lib/crypto/src/bases/mod.rs b/lib/crypto/src/bases/mod.rs deleted file mode 100644 index 961006443ab75d3e6fe3b6980f12ff4d2fa4070f..0000000000000000000000000000000000000000 --- a/lib/crypto/src/bases/mod.rs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Provide base convertion tools - -use thiserror::Error; - -/// Base16 conversion tools -pub mod b16; - -/// Base58 conversion tools -pub mod b58; - -/// Base64 conversion tools -pub mod b64; - -/// Errors enumeration for Base58/64 strings convertion. -#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)] -pub enum BaseConvertionError { - #[error("Data have invalid key length : expected {expected:?}, found {found:?}.")] - /// Data have invalid length. - InvalidLength { - /// Expected length - expected: usize, - /// Actual length - found: usize, - }, - #[error("Invalid character '{character:?}' at offset {offset:?}.")] - /// Base58/64 have an invalid character. - InvalidCharacter { - /// Character - character: char, - /// Offset (=position) - offset: usize, - }, - #[error("Invalid base converter length.")] - /// Base58/64 have invalid lendth - InvalidBaseConverterLength, - #[error("Invalid last symbol '{symbol:?}' at offset {offset:?}.")] - /// Base64 have invalid last symbol (symbol, offset) - InvalidLastSymbol { - /// Symbol - symbol: u8, - /// Offset (=position) - offset: usize, - }, - /// Unknown error - #[error("Unknown error.")] - UnknownError, -} - -impl From<base64::DecodeError> for BaseConvertionError { - fn from(err: base64::DecodeError) -> Self { - match err { - base64::DecodeError::InvalidByte(offset, byte) => { - BaseConvertionError::InvalidCharacter { - character: byte as char, - offset, - } - } - base64::DecodeError::InvalidLength => BaseConvertionError::InvalidBaseConverterLength, - base64::DecodeError::InvalidLastSymbol(offset, symbol) => { - BaseConvertionError::InvalidLastSymbol { symbol, offset } - } - } - } -} diff --git a/lib/crypto/src/hashs/mod.rs b/lib/crypto/src/hashs/mod.rs deleted file mode 100644 index c844978abc9003eaa3c86eedb40932afb94c471d..0000000000000000000000000000000000000000 --- a/lib/crypto/src/hashs/mod.rs +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Provide wrappers for cryptographic hashs - -use crate::bases::*; -use crate::rand::UnspecifiedRandError; -use ring::{digest, rand}; -use serde::{Deserialize, Serialize}; -use std::fmt::{Debug, Display, Error, Formatter}; - -/// A hash wrapper. -/// -/// A hash is often provided as string composed of 64 hexadecimal character (0 to 9 then A to F). -#[derive(Copy, Clone, Deserialize, Eq, Ord, PartialEq, PartialOrd, Hash, Serialize)] -pub struct Hash(pub [u8; 32]); - -impl Display for Hash { - fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { - write!(f, "{}", self.to_hex()) - } -} - -impl Debug for Hash { - fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { - write!(f, "Hash({})", self) - } -} - -impl Default for Hash { - fn default() -> Hash { - Hash([0; 32]) - } -} - -impl Hash { - /// Hash size (in bytes). - pub const SIZE_IN_BYTES: usize = 32; - - /// Generate a random Hash - #[inline] - pub fn random() -> Result<Self, UnspecifiedRandError> { - let random_bytes = rand::generate::<[u8; 32]>(&rand::SystemRandom::new()) - .map_err(|_| UnspecifiedRandError)?; - Ok(Hash(random_bytes.expose())) - } - - /// Compute hash of any binary datas - pub fn compute(datas: &[u8]) -> Hash { - let mut hash_buffer = [0u8; 32]; - hash_buffer.copy_from_slice(digest::digest(&digest::SHA256, datas).as_ref()); - Hash(hash_buffer) - } - /// Compute hash of a string - pub fn compute_str(str_datas: &str) -> Hash { - Hash::compute(str_datas.as_bytes()) - } - - /// Convert Hash into bytes vector - pub fn to_bytes_vector(&self) -> Vec<u8> { - self.0.to_vec() - } - - /// Convert a `Hash` to an hex string. - pub fn to_hex(&self) -> String { - let strings: Vec<String> = self.0.iter().map(|b| format!("{:02X}", b)).collect(); - - strings.join("") - } - - /// Convert a hex string in a `Hash`. - /// - /// The hex string must only contains hex characters - /// and produce a 32 bytes value. - #[inline] - pub fn from_hex(text: &str) -> Result<Hash, BaseConvertionError> { - Ok(Hash(b16::str_hex_to_32bytes(text)?)) - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - #[test] - fn test_hash_random() { - let hash1 = Hash::random(); - let hash2 = Hash::random(); - assert_ne!(hash1, hash2); - } - - #[test] - fn test_hash_debug() { - assert_eq!( - "Hash(0000000000000000000000000000000000000000000000000000000000000000)".to_owned(), - format!("{:?}", Hash::default()), - ); - } - - #[test] - fn test_hash_to_bytes() { - assert_eq!( - vec![ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0 - ], - Hash::default().to_bytes_vector(), - ); - } - - #[test] - fn test_hash_computation() { - assert_eq!( - Hash::from_hex("2CF24DBA5FB0A30E26E83B2AC5B9E29E1B161E5C1FA7425E73043362938B9824") - .expect("dev err"), - Hash::compute(b"hello"), - ); - - assert_eq!( - Hash::from_hex("2CF24DBA5FB0A30E26E83B2AC5B9E29E1B161E5C1FA7425E73043362938B9824") - .expect("dev err"), - Hash::compute_str("hello"), - ); - } - - #[test] - fn test_hash_from_hex() { - assert_eq!( - Ok(Hash::default()), - Hash::from_hex("0000000000000000000000000000000000000000000000000000000000000000") - ); - assert_eq!( - Err(BaseConvertionError::InvalidLength { - expected: 64, - found: 65, - }), - Hash::from_hex("00000000000000000000000000000000000000000000000000000000000000000") - ); - assert_eq!( - Err(BaseConvertionError::InvalidCharacter { - character: '_', - offset: 0, - }), - Hash::from_hex("_000000000000000000000000000000000000000000000000000000000000000") - ); - assert_eq!( - Err(BaseConvertionError::InvalidCharacter { - character: '_', - offset: 1, - }), - Hash::from_hex("0_00000000000000000000000000000000000000000000000000000000000000") - ); - } -} diff --git a/lib/crypto/src/keys/bin_signable.rs b/lib/crypto/src/keys/bin_signable.rs deleted file mode 100644 index 3693d40329c11ac44759c147c4159cb651053ce1..0000000000000000000000000000000000000000 --- a/lib/crypto/src/keys/bin_signable.rs +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Generic code for signing data in binary format - -use super::*; -use serde::{Deserialize, Serialize}; - -/// Signatureable in binary format -pub trait BinSignable<'de>: Serialize + Deserialize<'de> { - /// Error when serialize self into binary - type SerdeError: std::error::Error; - - /// Return entity issuer pubkey - fn issuer_pubkey(&self) -> PubKey; - /// Return signature - fn signature(&self) -> Option<Sig>; - /// Change signature - fn set_signature(&mut self, _signature: Sig); - /// Get binary datas without signature - fn get_bin_without_sig(&self) -> Result<Vec<u8>, Self::SerdeError>; - /// Add signature to bin datas - fn add_sig_to_bin_datas(&self, bin_datas: &mut Vec<u8>); - /// Sign entity with a signator - fn sign(&mut self, signator: &SignatorEnum) -> Result<Vec<u8>, SignError> { - if self.signature().is_some() { - return Err(SignError::AlreadySign); - } - match self.issuer_pubkey() { - PubKey::Ed25519(_) => { - let mut bin_msg = self - .get_bin_without_sig() - .map_err(|e| SignError::SerdeError(e.to_string()))?; - let sig = signator.sign(&bin_msg); - self.set_signature(sig); - self.add_sig_to_bin_datas(&mut bin_msg); - Ok(bin_msg) - } - _ => Err(SignError::WrongAlgo), - } - } - /// Check signature of entity - fn verify(&self) -> Result<(), SigError> { - if let Some(signature) = self.signature() { - match self.issuer_pubkey() { - PubKey::Ed25519(pubkey) => match signature { - Sig::Ed25519(sig) => { - let signed_part: Vec<u8> = self - .get_bin_without_sig() - .map_err(|e| SigError::SerdeError(format!("{}", e)))?; - pubkey.verify(&signed_part, &sig) - /* - if pubkey.verify(&signed_part, &sig) { - Ok(()) - } else { - Err(SigError::InvalidSig()) - } - */ - } - _ => Err(SigError::NotSameAlgo), - }, - _ => Err(SigError::NotSameAlgo), - } - } else { - Err(SigError::NotSig) - } - } -} - -#[cfg(test)] -mod tests { - - use super::*; - use bincode; - - #[derive(Deserialize, Serialize)] - struct BinSignableTestImpl { - datas: Vec<u8>, - issuer: PubKey, - sig: Option<Sig>, - } - - impl BinSignable<'_> for BinSignableTestImpl { - type SerdeError = bincode::Error; - - #[inline] - fn add_sig_to_bin_datas(&self, bin_datas: &mut Vec<u8>) { - bin_datas - .extend_from_slice(&bincode::serialize(&self.sig).expect("Fail to binarize sig !")); - } - #[inline] - fn get_bin_without_sig(&self) -> Result<Vec<u8>, bincode::Error> { - let mut bin_msg = bincode::serialize(&self)?; - let sig_size = bincode::serialized_size(&self.signature())?; - let bin_msg_len = bin_msg.len(); - bin_msg.truncate(bin_msg_len - (sig_size as usize)); - Ok(bin_msg) - } - fn issuer_pubkey(&self) -> PubKey { - self.issuer - } - fn signature(&self) -> Option<Sig> { - self.sig - } - fn set_signature(&mut self, new_signature: Sig) { - self.sig = Some(new_signature); - } - } - - #[test] - fn test_bin_signable() { - let key_pair = ed25519::KeyPairFromSeed32Generator::generate(Seed32::new([ - 0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, - ])); - - let signator = SignatorEnum::Ed25519( - key_pair - .generate_signator() - .expect("fail to generate signator !"), - ); - - let mut bin_signable_datas = BinSignableTestImpl { - datas: vec![0, 1, 2, 3], - issuer: PubKey::Ed25519(key_pair.pubkey), - sig: None, - }; - - assert_eq!(Err(SigError::NotSig), bin_signable_datas.verify()); - - let _bin_msg = bin_signable_datas - .sign(&signator) - .expect("Fail to sign datas !"); - - assert_eq!( - Err(SignError::AlreadySign), - bin_signable_datas.sign(&signator) - ); - - assert_eq!(Ok(()), bin_signable_datas.verify()) - } -} diff --git a/lib/crypto/src/keys/ed25519.rs b/lib/crypto/src/keys/ed25519.rs deleted file mode 100644 index 33f22e445acfba3e4e001129f61085302d84cfd7..0000000000000000000000000000000000000000 --- a/lib/crypto/src/keys/ed25519.rs +++ /dev/null @@ -1,728 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Provide wrappers around ed25519 keys and signatures -//! -//! Key pairs can be generated with [`KeyPairGenerator`]. -//! -//! [`KeyPairGenerator`]: struct.KeyPairGenerator.html - -use super::PublicKey as PublicKeyMethods; -use super::{PubkeyFromBytesError, SigError}; -use crate::bases::b58::{bytes_to_str_base58, ToBase58}; -use crate::bases::*; -use crate::rand::UnspecifiedRandError; -use crate::seeds::Seed32; -use base64; -use ring::signature::{Ed25519KeyPair as RingKeyPair, KeyPair, UnparsedPublicKey, ED25519}; -use serde::de::{Deserializer, Error, SeqAccess, Visitor}; -use serde::ser::{SerializeTuple, Serializer}; -use serde::{Deserialize, Serialize}; -use std::convert::TryFrom; -use std::fmt; -use std::fmt::{Debug, Display, Formatter}; -use std::hash::{Hash, Hasher}; -use std::marker::PhantomData; -use unwrap::unwrap; -use zeroize::Zeroize; - -/// Maximal size of a public key in bytes -pub static PUBKEY_SIZE_IN_BYTES: &usize = &32; -/// Minimal size of a public key in bytes -pub static PUBKEY_MIN_SIZE_IN_BYTES: &usize = &31; -/// Size of a signature in bytes -pub static SIG_SIZE_IN_BYTES: &usize = &64; - -/// Store a ed25519 signature. -#[derive(Clone, Copy)] -pub struct Signature(pub [u8; 64]); - -impl Hash for Signature { - fn hash<H: Hasher>(&self, state: &mut H) { - self.0.hash(state); - } -} - -impl Serialize for Signature { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - let mut seq = serializer.serialize_tuple(self.0.len())?; - for elem in &self.0[..] { - seq.serialize_element(elem)?; - } - seq.end() - } -} - -impl<'de> Deserialize<'de> for Signature { - fn deserialize<D>(deserializer: D) -> Result<Signature, D::Error> - where - D: Deserializer<'de>, - { - struct ArrayVisitor { - element: PhantomData<u8>, - } - - impl<'de> Visitor<'de> for ArrayVisitor { - type Value = Signature; - - #[cfg_attr(tarpaulin, skip)] - fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { - formatter.write_str(concat!("an array of length ", 64)) - } - - fn visit_seq<A>(self, mut seq: A) -> Result<Signature, A::Error> - where - A: SeqAccess<'de>, - { - let mut arr = [0u8; 64]; - for (i, byte) in arr.iter_mut().take(64).enumerate() { - *byte = seq - .next_element()? - .ok_or_else(|| Error::invalid_length(i, &self))?; - } - Ok(Signature(arr)) - } - } - - let visitor: ArrayVisitor = ArrayVisitor { - element: PhantomData, - }; - deserializer.deserialize_tuple(64, visitor) - } -} - -impl super::Signature for Signature { - #[inline] - fn from_base64(base64_data: &str) -> Result<Signature, BaseConvertionError> { - Ok(Signature(b64::str_base64_to64bytes(base64_data)?)) - } - - fn to_bytes_vector(&self) -> Vec<u8> { - self.0.to_vec() - } - - fn to_base64(&self) -> String { - base64::encode(&self.0[..]) // need to take a slice for required trait `AsRef<[u8]>` - } -} - -impl Display for Signature { - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - use super::Signature; - - write!(f, "{}", self.to_base64()) - } -} - -impl Debug for Signature { - // Signature { 1eubHHb... } - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - write!(f, "Signature {{ {} }}", self) - } -} - -impl PartialEq<Signature> for Signature { - fn eq(&self, other: &Signature) -> bool { - // No PartialEq for [u8;64], need to use 2 [u8;32] - self.0[0..32] == other.0[0..32] && self.0[32..64] == other.0[32..64] - } -} - -impl Eq for Signature {} - -/// Store a Ed25519 public key. -/// -/// Can be generated with [`KeyPairGenerator`]. -/// -/// [`KeyPairGenerator`]: struct.KeyPairGenerator.html -#[derive(Copy, Clone, Deserialize, PartialEq, Eq, Hash, Serialize)] -pub struct PublicKey { - datas: [u8; 32], - len: usize, -} - -impl Default for PublicKey { - fn default() -> Self { - PublicKey { - datas: [0u8; 32], - len: 32, - } - } -} - -impl AsRef<[u8]> for PublicKey { - fn as_ref(&self) -> &[u8] { - &self.datas[..self.len] - } -} - -impl TryFrom<&[u8]> for PublicKey { - type Error = PubkeyFromBytesError; - - fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { - if bytes.len() > *PUBKEY_SIZE_IN_BYTES || bytes.len() < *PUBKEY_MIN_SIZE_IN_BYTES { - Err(PubkeyFromBytesError::InvalidBytesLen { - expected: *PUBKEY_SIZE_IN_BYTES, - found: bytes.len(), - }) - } else { - let mut u8_array = [0; 32]; - u8_array[..bytes.len()].copy_from_slice(&bytes); - Ok(PublicKey { - datas: u8_array, - len: bytes.len(), - }) - } - } -} - -impl ToBase58 for PublicKey { - fn to_base58(&self) -> String { - bytes_to_str_base58(self.as_ref()) - } -} - -impl Display for PublicKey { - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - write!(f, "{}", bytes_to_str_base58(self.as_ref())) - } -} - -impl Debug for PublicKey { - // PublicKey { DNann1L... } - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - write!(f, "PublicKey {{ {} }}", self) - } -} - -impl super::PublicKey for PublicKey { - type Signature = Signature; - - #[inline] - fn from_base58(base58_data: &str) -> Result<Self, BaseConvertionError> { - let (datas, len) = b58::str_base58_to_32bytes(base58_data)?; - if len < *PUBKEY_MIN_SIZE_IN_BYTES { - Err(BaseConvertionError::InvalidLength { - expected: *PUBKEY_SIZE_IN_BYTES, - found: len, - }) - } else { - Ok(PublicKey { datas, len }) - } - } - - fn to_bytes_vector(&self) -> Vec<u8> { - self.as_ref().to_vec() - } - - fn verify(&self, message: &[u8], signature: &Self::Signature) -> Result<(), SigError> { - Ok(UnparsedPublicKey::new(&ED25519, self.as_ref()) - .verify(message, &signature.0) - .map_err(|_| SigError::InvalidSig)?) - } -} - -#[inline] -fn get_ring_ed25519_pubkey(ring_key_pair: &RingKeyPair) -> PublicKey { - let ring_pubkey: <RingKeyPair as KeyPair>::PublicKey = *ring_key_pair.public_key(); - unwrap!(PublicKey::try_from(ring_pubkey.as_ref())) -} - -/// Store a ed25519 cryptographic signator -#[derive(Debug)] -pub struct Signator(RingKeyPair); - -impl super::Signator for Signator { - type Signature = Signature; - type PublicKey = PublicKey; - - fn public_key(&self) -> Self::PublicKey { - get_ring_ed25519_pubkey(&self.0) - } - fn sign(&self, message: &[u8]) -> Self::Signature { - let mut sig_bytes = [0u8; 64]; - sig_bytes.copy_from_slice(self.0.sign(message).as_ref()); - Signature(sig_bytes) - } -} - -/// Store a ed25519 cryptographic key pair (`PublicKey` + `PrivateKey`) -#[derive(Debug, Clone, Eq)] -pub struct Ed25519KeyPair { - /// Store a Ed25519 public key. - pub pubkey: PublicKey, - /// Store a seed of 32 bytes. - pub seed: Seed32, -} - -impl Display for Ed25519KeyPair { - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - write!(f, "({}, hidden)", self.pubkey.to_base58()) - } -} - -impl PartialEq<Ed25519KeyPair> for Ed25519KeyPair { - fn eq(&self, other: &Ed25519KeyPair) -> bool { - self.pubkey.eq(&other.pubkey) && self.seed.eq(&other.seed) - } -} - -impl super::KeyPair for Ed25519KeyPair { - type Signator = Signator; - - fn generate_signator(&self) -> Result<Self::Signator, super::SignError> { - Ok(Signator( - RingKeyPair::from_seed_and_public_key(self.seed.as_ref(), self.pubkey.as_ref()) - .map_err(|_| super::SignError::CorruptedKeyPair)?, - )) - } - - fn public_key(&self) -> PublicKey { - self.pubkey - } - - fn seed(&self) -> &Seed32 { - &self.seed - } - - fn verify( - &self, - message: &[u8], - signature: &<Self::Signator as super::Signator>::Signature, - ) -> Result<(), SigError> { - self.public_key().verify(message, signature) - } -} - -impl Ed25519KeyPair { - /// Generate random keypair - pub fn generate_random() -> Result<Self, UnspecifiedRandError> { - Ok(KeyPairFromSeed32Generator::generate(Seed32::random()?)) - } -} - -/// Keypair generator with seed -#[derive(Debug, Copy, Clone)] -pub struct KeyPairFromSeed32Generator {} - -impl KeyPairFromSeed32Generator { - /// Create a keypair based on a given seed. - /// - /// The [`PublicKey`](struct.PublicKey.html) will be able to verify messaged signed with - /// the [`PrivateKey`](struct.PrivateKey.html). - pub fn generate(seed: Seed32) -> Ed25519KeyPair { - let ring_key_pair = RingKeyPair::from_seed_unchecked(seed.as_ref()) - .expect("dev error: fail to generate ed25519 keypair."); - Ed25519KeyPair { - pubkey: get_ring_ed25519_pubkey(&ring_key_pair), - seed, - } - } -} - -#[derive(Zeroize)] -#[zeroize(drop)] -/// Salted password -pub struct SaltedPassword { - salt: String, - password: String, -} - -impl SaltedPassword { - /// Create new salted password - pub fn new(salt: String, password: String) -> SaltedPassword { - SaltedPassword { salt, password } - } -} - -/// Keypair generator with given parameters for `scrypt` keypair function. -#[derive(Copy, Clone)] -pub struct KeyPairFromSaltedPasswordGenerator { - scrypt_params: scrypt::ScryptParams, -} - -impl KeyPairFromSaltedPasswordGenerator { - /// Create a `KeyPairGenerator` with default arguments `(log_n: 12, r: 16, p: 1)` - pub fn with_default_parameters() -> KeyPairFromSaltedPasswordGenerator { - KeyPairFromSaltedPasswordGenerator { - scrypt_params: scrypt::ScryptParams::new(12, 16, 1) - .expect("dev error: invalid default scrypt params"), - } - } - - /// Create a `KeyPairFromSaltedPasswordGenerator` with given arguments. - /// - /// # Arguments - /// - /// - log_n - The log2 of the Scrypt parameter N - /// - r - The Scrypt parameter r - /// - p - The Scrypt parameter p - pub fn with_parameters( - log_n: u8, - r: u32, - p: u32, - ) -> Result<KeyPairFromSaltedPasswordGenerator, scrypt::errors::InvalidParams> { - Ok(KeyPairFromSaltedPasswordGenerator { - scrypt_params: scrypt::ScryptParams::new(log_n, r, p)?, - }) - } - - /// Create a seed based on a given password and salt. - pub fn generate_seed(&self, password: &[u8], salt: &[u8]) -> Seed32 { - let mut seed = [0u8; 32]; - - scrypt::scrypt(password, salt, &self.scrypt_params, &mut seed) - .expect("dev error: invalid seed len"); - - Seed32::new(seed) - } - - /// Create a keypair based on a given password and salt. - /// - /// The [`PublicKey`](struct.PublicKey.html) will be able to verify messaged signed with - /// the [`PrivateKey`](struct.PrivateKey.html). - pub fn generate(&self, salted_password: SaltedPassword) -> Ed25519KeyPair { - // Generate seed from tuple (password + salt) - let seed = self.generate_seed( - salted_password.password.as_bytes(), - salted_password.salt.as_bytes(), - ); - // Generate keypair from seed - KeyPairFromSeed32Generator::generate(seed) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::keys::{KeyPair, Sig, Signator, Signature}; - use crate::seeds::Seed32; - use bincode; - use std::collections::hash_map::DefaultHasher; - - #[test] - fn base58_seed() { - let seed58 = "DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV"; - - // Test base58 encoding/decoding (loop for every bytes) - let seed = Seed32::from_base58(seed58).expect("fail to parser seed !"); - assert_eq!(seed.to_base58(), seed58); - - // Test seed display and debug - assert_eq!( - "DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV".to_owned(), - format!("{}", seed) - ); - assert_eq!( - "Seed32 { DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV }".to_owned(), - format!("{:?}", seed) - ); - - // Test seed equality - let same_seed = seed.clone(); - let other_seed = Seed32::default(); - assert!(seed.eq(&same_seed)); - assert!(!seed.eq(&other_seed)); - - // Test seed parsing - assert_eq!( - Seed32::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLVgth",).unwrap_err(), - BaseConvertionError::InvalidLength { - found: 35, - expected: 32 - } - ); - /*assert_eq!( - Seed32::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQd",).unwrap_err(), - BaseConvertionError::InvalidLength { - found: 31, - expected: 32 - } - );*/ - assert_eq!( - Seed32::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQd<<").unwrap_err(), - BaseConvertionError::InvalidCharacter { - character: '<', - offset: 42 - } - ); - assert_eq!( - Seed32::from_base58( - "\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - " - ) - .unwrap_err(), - BaseConvertionError::InvalidLength { - expected: 32, - found: 161 - } - ); - } - - #[test] - fn base58_public_key() { - let public58 = "DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV"; - let public_key = unwrap!(super::PublicKey::from_base58(public58)); - - // Test base58 encoding/decoding (loop for every bytes) - assert_eq!(public_key.to_base58(), public58); - let public_raw = unwrap!(b58::str_base58_to_32bytes(public58)); - assert_eq!(public_raw.0.to_vec(), public_key.to_bytes_vector()); - for (key, raw) in public_key.as_ref().iter().zip(public_raw.0.iter()) { - assert_eq!(key, raw); - } - - // Test pubkey debug - assert_eq!( - "PublicKey { DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV }".to_owned(), - format!("{:?}", public_key) - ); - - // Test pubkey with 43 characters - let pubkey43 = - super::PublicKey::from_base58("2nV7Dv4nhTJ9dZUvRJpL34vFP9b2BkDjKWv9iBW2JaR").unwrap(); - println!("pubkey43={:?}", pubkey43.as_ref()); - assert_eq!( - format!("{:?}", pubkey43), - "PublicKey { 2nV7Dv4nhTJ9dZUvRJpL34vFP9b2BkDjKWv9iBW2JaR }".to_owned(), - ); - assert_eq!( - super::PublicKey::from_base58("DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQd<<") - .unwrap_err(), - BaseConvertionError::InvalidCharacter { - character: '<', - offset: 42 - } - ); - assert_eq!( - super::PublicKey::from_base58( - "\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV\ - " - ) - .unwrap_err(), - BaseConvertionError::InvalidLength { - expected: 32, - found: 161 - } - ); - } - - #[test] - fn base64_signature() { - let signature64 = "1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FG\ - MMmQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAg=="; - let signature = unwrap!(super::Signature::from_base64(signature64)); - - // Test signature base64 encoding/decoding (loop for every bytes) - assert_eq!(signature.to_base64(), signature64); - let signature_raw = unwrap!(base64::decode(signature64)); - for (sig, raw) in signature.0.iter().zip(signature_raw.iter()) { - assert_eq!(sig, raw); - } - - // Test signature display and debug - assert_eq!( - "1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FGMMmQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAg==".to_owned(), - format!("{}", signature) - ); - assert_eq!( - "Signature { 1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FGMMmQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAg== }".to_owned(), - format!("{:?}", signature) - ); - - // Test signature hash - let mut hasher = DefaultHasher::new(); - signature.hash(&mut hasher); - let hash1 = hasher.finish(); - let mut hasher = DefaultHasher::new(); - let signature_copy = signature.clone(); - signature_copy.hash(&mut hasher); - let hash2 = hasher.finish(); - assert_eq!(hash1, hash2); - - // Test signature serialization/deserialization - let mut bin_sig = bincode::serialize(&signature).expect("Fail to serialize signature !"); - assert_eq!(*SIG_SIZE_IN_BYTES, bin_sig.len()); - assert_eq!(signature.to_bytes_vector(), bin_sig); - assert_eq!( - signature, - bincode::deserialize(&bin_sig).expect("Fail to deserialize signature !"), - ); - bin_sig.push(0); // add on byte to simulate invalid length - bincode::deserialize::<Sig>(&bin_sig) - .expect_err("Deserialization must be fail because length is invalid !"); - - // Test signature parsing - assert_eq!( - super::Signature::from_base64("YmhlaW9iaHNlcGlvaGVvaXNlcGl2ZXBvdm5pc2U=").unwrap_err(), - BaseConvertionError::InvalidLength { - found: 29, - expected: 64 - } - ); - assert_eq!( - super::Signature::from_base64( - "YmhlaW9iaHNlcGlvaGVvaXNlcGl2ZXBvdm5pc2V2c2JlaW9idmVpb3Zqc\ - 2V2Z3BpaHNlamVwZ25qZXNqb2dwZWpnaW9zZXNkdnNic3JicmJyZGJyZGI=", - ) - .unwrap_err(), - BaseConvertionError::InvalidLength { - found: 86, - expected: 64 - } - ); - assert_eq!( - super::Signature::from_base64( - "1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FGMM\ - mQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAgdha<<", - ) - .unwrap_err(), - BaseConvertionError::InvalidCharacter { - character: '<', - offset: 89 - } - ); - assert_eq!( - super::Signature::from_base64( - "1eubHHbuNfilHMM0G2bI30iZzebQ2cQ1PC7uPAw08FG\ - MMmQCRerlF/3pc4sAcsnexsxBseA/3lY03KlONqJBAg===", - ) - .unwrap_err(), - BaseConvertionError::InvalidBaseConverterLength, - ); - } - - #[test] - fn message_sign_verify() { - let seed = unwrap!(Seed32::from_base58( - "DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV" - )); - - let expected_signature = unwrap!(super::Signature::from_base64( - "9ARKYkEAwp+kQ01rgvWUwJLchVLpZvHg3t/3H32XwWOoG119NiVCtfPSPtR4GDOeOz6Y+29drOLahqhzy+ciBw==", - )); - - let message = "Version: 10 -Type: Identity -Currency: duniter_unit_test_currency -Issuer: DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV -UniqueID: tic -Timestamp: 0-E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855 -"; - - let signator = KeyPairFromSeed32Generator::generate(seed) - .generate_signator() - .expect("fail to generate signator !"); - let pubkey = signator.public_key(); - let sig = signator.sign(message.as_bytes()); - let wrong_sig = Signature([ - 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, - ]); - - assert_eq!(sig, expected_signature); - assert_eq!(Ok(()), pubkey.verify(message.as_bytes(), &sig)); - assert_eq!( - Err(SigError::InvalidSig), - pubkey.verify(message.as_bytes(), &wrong_sig) - ); - } - - #[test] - fn keypair_generate() { - let key_pair1 = KeyPairFromSaltedPasswordGenerator::with_default_parameters().generate( - SaltedPassword::new( - "JhxtHB7UcsDbA9wMSyMKXUzBZUQvqVyB32KwzS9SWoLkjrUhHV".to_owned(), - "JhxtHB7UcsDbA9wMSyMKXUzBZUQvqVyB32KwzS9SWoLkjrUhHV_".to_owned(), - ), - ); - - assert_eq!( - key_pair1.pubkey.to_string(), - "7iMV3b6j2hSj5WtrfchfvxivS9swN3opDgxudeHq64fb" - ); - - let key_pair2 = KeyPairFromSaltedPasswordGenerator::with_parameters(12u8, 16, 1) - .expect("fail to create KeyPairFromSaltedPasswordGenerator: invalid scrypt params.") - .generate(SaltedPassword::new("toto".to_owned(), "toto".to_owned())); - - // Test signature display and debug - assert_eq!( - "(EA7Dsw39ShZg4SpURsrgMaMqrweJPUFPYHwZA8e92e3D, hidden)".to_owned(), - format!("{}", key_pair2) - ); - - // Test key_pair equality - let same_key_pair = key_pair2.clone(); - let other_key_pair = KeyPairFromSeed32Generator::generate(Seed32::new([ - 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, - ])); - assert!(key_pair2.eq(&same_key_pair)); - assert!(!key_pair2.eq(&other_key_pair)); - } - - #[test] - fn keypair_generate_sign_and_verify() { - let keypair = KeyPairFromSaltedPasswordGenerator::with_default_parameters().generate( - SaltedPassword::new("password".to_owned(), "salt".to_owned()), - ); - - let message = "Version: 10 -Type: Identity -Currency: duniter_unit_test_currency -Issuer: DNann1Lh55eZMEDXeYt59bzHbA3NJR46DeQYCS2qQdLV -UniqueID: tic -Timestamp: 0-E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855 -"; - - let sig = keypair - .generate_signator() - .expect("fail to gen signator") - .sign(message.as_bytes()); - assert!(keypair.verify(message.as_bytes(), &sig).is_ok()); - } - - /*#[test] - fn test_tmp() { - let message = "InnerHash: A9697A9954EA447BBDC88D1B22AA8B60B2D11986DE806319C1A5AAFEB348C213\nNonce: 10300000043648\n"; - - let pubkey = unwrap!(PublicKey::from_base58("8kXygUHh1vLjmcRzXVM86t38EL8dfFJgfBeHmkaWLamu")); - let sig: super::Signature = unwrap!(Signature::from_base64( - "XDIvgPbJK02ZfMwrhrtNFmMVGhqazDBhnxPBvMXLsDgPbnh28NbUbOYIRHrsZlo/frAv/Oh0OUOQZD3JpSf8DQ==" - )); - - let pubkey_hex = hex::encode(&pubkey.0[..]); - println!("{}", pubkey_hex); - let sig_hex = hex::encode(&sig.0[..]); - println!("{}", sig_hex); - - assert!(pubkey.verify(message.as_bytes(), &sig).is_ok()); - }*/ -} diff --git a/lib/crypto/src/keys/mod.rs b/lib/crypto/src/keys/mod.rs deleted file mode 100644 index 79573f4aa9348524289cc16d35b7b20c3f3b3fd5..0000000000000000000000000000000000000000 --- a/lib/crypto/src/keys/mod.rs +++ /dev/null @@ -1,739 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Provide wrappers around public keys, private keys and signatures. -//! -//! - Keys can be converted to/from Base58 string format. -//! - Signatures can be converted to/from Base64 string format. -//! -//! # Usage -//! -//! ``` -//! use dup_crypto::keys::{KeyPair, PublicKey, Signator, Signature}; -//! use dup_crypto::keys::ed25519::{KeyPairFromSaltedPasswordGenerator, SaltedPassword}; -//! -//! let generator = KeyPairFromSaltedPasswordGenerator::with_default_parameters(); -//! -//! let keypair = generator.generate(SaltedPassword::new( -//! "salt".to_owned(), -//! "password".to_owned(), -//! )); -//! -//! let signator = keypair.generate_signator().expect("keypair corrupted"); -//! -//! let message = "Hello, world!"; -//! -//! let signature = signator.sign(&message.as_bytes()); -//! -//! assert!(keypair.pubkey.verify(&message.as_bytes(), &signature).is_ok()); -//! ``` -//! -//! # Format -//! -//! - Base58 use the following alphabet : -//! `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` -//! - Base64 use the following alphabet : -//! `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` -//! with `=` as padding character. - -pub mod bin_signable; -pub mod ed25519; -pub mod text_signable; - -pub use crate::seeds::Seed32; - -use crate::bases::b58::ToBase58; -use crate::bases::BaseConvertionError; -use serde::{Deserialize, Serialize}; -use std::convert::TryFrom; -use std::fmt::Debug; -use std::fmt::Display; -use std::fmt::Error; -use std::fmt::Formatter; -use std::hash::Hash; -use std::str::FromStr; -use thiserror::Error; - -/// Cryptographic keys algorithms list -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)] -pub enum KeysAlgo { - /// Ed25519 algorithm - Ed25519 = 0, - /// Schnorr algorithm - Schnorr = 1, -} - -/// Get the cryptographic algorithm. -pub trait GetKeysAlgo: Clone + Debug + PartialEq + Eq { - /// Get the cryptographic algorithm. - fn algo(&self) -> KeysAlgo; -} - -/// Errors enumeration for signature verification. -#[derive(Debug, Eq, Error, PartialEq)] -pub enum SigError { - /// Signature and pubkey are not the same algo - #[error("Signature and pubkey are not the same algo.")] - NotSameAlgo, - /// Invalid signature - #[error("Invalid signature.")] - InvalidSig, - /// Absence of signature - #[error("Absence of signature.")] - NotSig, - /// Serialization error - #[error("Serialization error: {0}")] - SerdeError(String), -} - -/// SignError -#[derive(Debug, Eq, Error, PartialEq)] -pub enum SignError { - /// Corrupted key pair - #[error("Corrupted key pair.")] - CorruptedKeyPair, - /// WrongAlgo - #[error("Wrong algo.")] - WrongAlgo, - /// WrongPrivkey - #[error("Wrong private key.")] - WrongPrivkey, - /// AlreadySign - #[error("Already signed.")] - AlreadySign, - /// Serialization error - #[error("Serialization error: {0}")] - SerdeError(String), -} - -/// Define the operations that can be performed on a cryptographic signature. -/// -/// A signature can be converted from/to Base64 format. -/// When converted back and forth the value should be the same. -/// -/// A signature can be made with a [`PrivateKey`] -/// and a message, and verified with the associated [`PublicKey`]. -/// -/// [`PrivateKey`]: trait.PrivateKey.html -/// [`PublicKey`]: trait.PublicKey.html -pub trait Signature: Clone + Display + Debug + PartialEq + Eq + Hash { - /// Create a `Signature` from a Base64 string. - /// - /// The Base64 string should contains only valid Base64 characters - /// and have a correct length (64 bytes when converted). If it's not the case, - /// a [`BaseConvertionError`] is returned with the corresponding variant. - /// - /// [`BaseConvertionError`]: enum.BaseConvertionError.html - fn from_base64(base64_string: &str) -> Result<Self, BaseConvertionError>; - - /// Convert Signature into butes vector - fn to_bytes_vector(&self) -> Vec<u8>; - - /// Encode the signature into Base64 string format. - fn to_base64(&self) -> String; -} - -/// Store a cryptographic signature. -#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] -pub enum Sig { - /// Store a ed25519 Signature - Ed25519(ed25519::Signature), - /// Store a Schnorr Signature - Schnorr(), -} - -impl Sig { - /// Get Sig size in bytes - pub fn size_in_bytes(&self) -> usize { - match *self { - Sig::Ed25519(_) => *ed25519::SIG_SIZE_IN_BYTES + 2, - Sig::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } -} - -impl Display for Sig { - fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { - write!(f, "{}", self.to_base64()) - } -} - -impl GetKeysAlgo for Sig { - fn algo(&self) -> KeysAlgo { - match *self { - Sig::Ed25519(_) => KeysAlgo::Ed25519, - Sig::Schnorr() => KeysAlgo::Schnorr, - } - } -} - -impl Signature for Sig { - #[cfg_attr(tarpaulin, skip)] - fn from_base64(_base64_string: &str) -> Result<Self, BaseConvertionError> { - unimplemented!() - } - fn to_bytes_vector(&self) -> Vec<u8> { - match *self { - Sig::Ed25519(ed25519_sig) => ed25519_sig.to_bytes_vector(), - Sig::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } - fn to_base64(&self) -> String { - match *self { - Sig::Ed25519(ed25519_sig) => ed25519_sig.to_base64(), - Sig::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } -} - -/// Define the operations that can be performed on a cryptographic public key. -/// -/// A `PublicKey` can be converted from/to Base64 format. -/// When converted back and forth the value should be the same. -/// -/// A `PublicKey` is used to verify the signature of a message -/// with the associated [`PrivateKey`]. -/// -/// [`PrivateKey`]: trait.PrivateKey.html -pub trait PublicKey: Clone + Display + Debug + PartialEq + Eq + Hash + ToBase58 { - /// Signature type of associated cryptosystem. - type Signature: Signature; - - /// Create a PublicKey from a Base58 string. - /// - /// The Base58 string should contains only valid Base58 characters - /// and have a correct length. If it's not the case, - /// a [`BaseConvertionError`] is returned with the corresponding variant. - /// - /// [`BaseConvertionError`]: enum.BaseConvertionError.html - fn from_base58(base58_string: &str) -> Result<Self, BaseConvertionError>; - - /// Convert into bytes vector - fn to_bytes_vector(&self) -> Vec<u8>; - - /// Verify a signature with this public key. - fn verify(&self, message: &[u8], signature: &Self::Signature) -> Result<(), SigError>; -} - -/// Store a cryptographic public key. -#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] -pub enum PubKey { - /// Store a ed25519 public key. - Ed25519(ed25519::PublicKey), - /// Store a Schnorr public key. - Schnorr(), -} - -#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] -/// Error when parsing pubkey bytes -pub enum PubkeyFromBytesError { - /// Invalid bytes length - InvalidBytesLen { - /// Expected length - expected: usize, - /// Found length - found: usize, - }, -} - -impl PubKey { - /// Create pubkey from bytes - #[inline] - pub fn from_bytes(bytes: &[u8]) -> Result<Self, PubkeyFromBytesError> { - Ok(PubKey::Ed25519(ed25519::PublicKey::try_from(bytes)?)) - } - /// Compute PubKey size in bytes - pub fn size_in_bytes(&self) -> usize { - match *self { - PubKey::Ed25519(_) => ed25519::PUBKEY_SIZE_IN_BYTES + 3, - PubKey::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } -} - -impl Default for PubKey { - fn default() -> Self { - PubKey::Ed25519(ed25519::PublicKey::default()) - } -} - -impl GetKeysAlgo for PubKey { - fn algo(&self) -> KeysAlgo { - match *self { - PubKey::Ed25519(_) => KeysAlgo::Ed25519, - PubKey::Schnorr() => KeysAlgo::Schnorr, - } - } -} - -impl ToBase58 for PubKey { - fn to_base58(&self) -> String { - match *self { - PubKey::Ed25519(ed25519_pub) => ed25519_pub.to_base58(), - PubKey::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } -} - -impl Display for PubKey { - fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { - write!(f, "{}", self.to_base58()) - } -} - -impl FromStr for PubKey { - type Err = BaseConvertionError; - - fn from_str(s: &str) -> Result<Self, Self::Err> { - ed25519::PublicKey::from_base58(s).map(PubKey::Ed25519) - } -} - -impl PublicKey for PubKey { - type Signature = Sig; - - #[cfg_attr(tarpaulin, skip)] - fn from_base58(_base58_string: &str) -> Result<Self, BaseConvertionError> { - unimplemented!() - } - fn to_bytes_vector(&self) -> Vec<u8> { - match *self { - PubKey::Ed25519(ed25519_pubkey) => ed25519_pubkey.to_bytes_vector(), - PubKey::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } - fn verify(&self, message: &[u8], signature: &Self::Signature) -> Result<(), SigError> { - match *self { - PubKey::Ed25519(ed25519_pubkey) => { - if let Sig::Ed25519(ed25519_sig) = signature { - ed25519_pubkey.verify(message, ed25519_sig) - } else { - Err(SigError::NotSameAlgo) - } - } - PubKey::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } -} - -/// Define the operations that can be performed on a cryptographic key pair. -pub trait KeyPair: Clone + Display + Debug + PartialEq + Eq { - /// Signator type of associated cryptosystem. - type Signator: Signator; - - /// Generate signator. - fn generate_signator(&self) -> Result<Self::Signator, SignError>; - - /// Get `PublicKey` - fn public_key(&self) -> <Self::Signator as Signator>::PublicKey; - - /// Get `Seed32` - fn seed(&self) -> &Seed32; - - /// Verify a signature with public key. - fn verify( - &self, - message: &[u8], - signature: &<Self::Signator as Signator>::Signature, - ) -> Result<(), SigError>; -} - -/// Define the operations that can be performed on a cryptographic signator. -pub trait Signator: Debug { - /// Signature type of associated cryptosystem. - type Signature: Signature; - /// PublicKey type of associated cryptosystem. - type PublicKey: PublicKey; - - /// Get `PublicKey` - fn public_key(&self) -> Self::PublicKey; - - /// Sign a message with private key encasuled in signator. - fn sign(&self, message: &[u8]) -> Self::Signature; -} - -/// Store a cryptographic key pair. -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum KeyPairEnum { - /// Store a ed25519 key pair. - Ed25519(ed25519::Ed25519KeyPair), - /// Store a Schnorr key pair. - Schnorr(), -} - -impl GetKeysAlgo for KeyPairEnum { - fn algo(&self) -> KeysAlgo { - match *self { - KeyPairEnum::Ed25519(_) => KeysAlgo::Ed25519, - KeyPairEnum::Schnorr() => KeysAlgo::Schnorr, - } - } -} - -impl Display for KeyPairEnum { - fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { - match self { - KeyPairEnum::Ed25519(ref ed25519_keypair) => { - write!(f, "({}, hidden)", ed25519_keypair.pubkey.to_base58()) - } - KeyPairEnum::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } -} - -impl KeyPair for KeyPairEnum { - type Signator = SignatorEnum; - - fn generate_signator(&self) -> Result<Self::Signator, SignError> { - match self { - KeyPairEnum::Ed25519(ref ed25519_keypair) => { - Ok(SignatorEnum::Ed25519(ed25519_keypair.generate_signator()?)) - } - KeyPairEnum::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } - fn public_key(&self) -> <Self::Signator as Signator>::PublicKey { - match self { - KeyPairEnum::Ed25519(ref ed25519_keypair) => { - PubKey::Ed25519(ed25519_keypair.public_key()) - } - KeyPairEnum::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } - fn seed(&self) -> &Seed32 { - match *self { - KeyPairEnum::Ed25519(ref ed25519_keypair) => &ed25519_keypair.seed(), - KeyPairEnum::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } - fn verify(&self, message: &[u8], signature: &Sig) -> Result<(), SigError> { - match self { - KeyPairEnum::Ed25519(ref ed25519_keypair) => { - if let Sig::Ed25519(ed25519_sig) = signature { - ed25519_keypair.verify(message, ed25519_sig) - } else { - Err(SigError::NotSameAlgo) - } - } - KeyPairEnum::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } -} - -/// Store a cryptographic signator. -#[derive(Debug)] -pub enum SignatorEnum { - /// Store a ed25519 signator. - Ed25519(ed25519::Signator), - /// Store a Schnorr signator. - Schnorr(), -} - -impl Signator for SignatorEnum { - type PublicKey = PubKey; - type Signature = Sig; - - fn public_key(&self) -> Self::PublicKey { - match self { - SignatorEnum::Ed25519(ref ed25519_signator) => { - PubKey::Ed25519(ed25519_signator.public_key()) - } - SignatorEnum::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } - - fn sign(&self, message: &[u8]) -> Sig { - match self { - SignatorEnum::Ed25519(ref ed25519_signator) => { - Sig::Ed25519(ed25519_signator.sign(message)) - } - SignatorEnum::Schnorr() => panic!("Schnorr algo not yet supported !"), - } - } -} - -#[cfg(test)] -mod tests { - - use super::*; - use unwrap::unwrap; - - pub fn valid_key_pair_1() -> KeyPairEnum { - KeyPairEnum::Ed25519(ed25519::KeyPairFromSeed32Generator::generate(Seed32::new( - [ - 59u8, 106, 39, 188, 206, 182, 164, 45, 98, 163, 168, 208, 42, 111, 13, 115, 101, - 50, 21, 119, 29, 226, 67, 166, 58, 192, 72, 161, 139, 89, 218, 41, - ], - ))) - } - - #[test] - fn sig() { - let sig_bytes = [ - 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, - ]; - let sig_str_b64 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==".to_owned(); - let sig = Sig::Ed25519(ed25519::Signature(sig_bytes)); - - assert_eq!(sig.size_in_bytes(), *ed25519::SIG_SIZE_IN_BYTES + 2); - assert_eq!(sig_str_b64, format!("{}", sig)); - - assert_eq!(KeysAlgo::Ed25519, sig.algo()); - assert_eq!(KeysAlgo::Schnorr, Sig::Schnorr().algo()); - - assert_eq!(sig_bytes.to_vec(), sig.to_bytes_vector()); - - assert_eq!(sig_str_b64, sig.to_base64()); - } - - #[test] - fn pubkey() { - let pubkey_default = PubKey::default(); - let pubkey_bytes = [ - 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, - ]; - let pubkey = PubKey::Ed25519(unwrap!(ed25519::PublicKey::try_from(&pubkey_bytes[..]))); - assert_eq!(pubkey_default, pubkey); - - let pubkey_str_b58 = "11111111111111111111111111111111".to_owned(); - assert_eq!( - pubkey_default, - PubKey::from_str(&pubkey_str_b58).expect("Fail to parse pubkey !") - ); - - assert_eq!(pubkey.size_in_bytes(), *ed25519::PUBKEY_SIZE_IN_BYTES + 3); - assert_eq!(pubkey_str_b58, format!("{}", pubkey)); - - assert_eq!(KeysAlgo::Ed25519, pubkey.algo()); - assert_eq!(KeysAlgo::Schnorr, PubKey::Schnorr().algo()); - - assert_eq!(pubkey_bytes.to_vec(), pubkey.to_bytes_vector()); - - assert_eq!(pubkey_str_b58, pubkey.to_base58()); - - assert_eq!( - Err(SigError::InvalidSig), - pubkey.verify( - b"message", - &Sig::Ed25519(ed25519::Signature([ - 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ])) - ) - ) - } - - #[test] - fn seed() { - let seed_default = Seed32::default(); - let seed_bytes = [ - 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, - ]; - let seed_str_b58 = "11111111111111111111111111111111".to_owned(); - let seed = Seed32::new(seed_bytes); - - assert_eq!(seed_default, seed); - assert_eq!( - seed_default, - Seed32::from_base58(&seed_str_b58).expect("Fail to parse seed !") - ); - - assert_eq!(seed_str_b58, format!("{}", seed)); - - assert_eq!(seed_str_b58, seed.to_base58()); - } - - fn false_key_pair_ed25519() -> ed25519::Ed25519KeyPair { - ed25519::KeyPairFromSeed32Generator::generate(Seed32::new([ - 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, - ])) - } - - #[test] - fn key_pair() { - let false_key_pair_ed25519 = false_key_pair_ed25519(); - let false_key_pair = KeyPairEnum::Ed25519(false_key_pair_ed25519.clone()); - - assert_eq!(KeysAlgo::Ed25519, false_key_pair.algo()); - assert_eq!(KeysAlgo::Schnorr, KeyPairEnum::Schnorr().algo()); - assert_eq!( - "(4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS, hidden)".to_owned(), - format!("{}", false_key_pair) - ); - assert_eq!( - PubKey::Ed25519(false_key_pair_ed25519.pubkey), - false_key_pair.public_key() - ); - assert_eq!(false_key_pair_ed25519.seed, false_key_pair.seed().clone()); - assert_eq!( - Err(SigError::InvalidSig), - false_key_pair.verify( - b"message", - &Sig::Ed25519(ed25519::Signature([ - 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - ])) - ) - ); - } - - #[test] - fn key_pair_verify_wrong_sig_algo() { - let false_key_pair_ed25519 = false_key_pair_ed25519(); - let false_key_pair = KeyPairEnum::Ed25519(false_key_pair_ed25519); - assert_eq!( - Err(SigError::NotSameAlgo), - false_key_pair.verify(b"message", &Sig::Schnorr()), - ); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn sig_schnorr_size() { - let sig = Sig::Schnorr(); - sig.size_in_bytes(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn sig_schnorr_to_bytes() { - let sig = Sig::Schnorr(); - sig.to_bytes_vector(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn sig_schnorr_to_base64() { - let sig = Sig::Schnorr(); - sig.to_base64(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn pubkey_schnorr_size() { - let pubkey = PubKey::Schnorr(); - pubkey.size_in_bytes(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn pubkey_schnorr_base58() { - let pubkey = PubKey::Schnorr(); - pubkey.to_base58(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn pubkey_schnorr_to_bytes() { - let pubkey = PubKey::Schnorr(); - pubkey.to_bytes_vector(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn pubkey_schnorr_verify() { - let pubkey = PubKey::Schnorr(); - let _ = pubkey.verify(b"message", &Sig::Schnorr()); - } - - #[test] - fn pubkey_verify_sig_wrong_algo() { - let pubkey = PubKey::default(); - assert_eq!( - Err(SigError::NotSameAlgo), - pubkey.verify(b"message", &Sig::Schnorr()), - ); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn key_pair_schnorr_display() { - let key_pair = KeyPairEnum::Schnorr(); - format!("{}", key_pair); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn key_pair_schnorr_generate_signator() { - let _ = KeyPairEnum::Schnorr().generate_signator(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn key_pair_schnorr_get_pubkey() { - let key_pair = KeyPairEnum::Schnorr(); - key_pair.public_key(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn key_pair_schnorr_get_seed() { - let key_pair = KeyPairEnum::Schnorr(); - key_pair.seed(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn key_pair_schnorr_verify() { - let key_pair = KeyPairEnum::Schnorr(); - let _ = key_pair.verify(b"message", &Sig::Schnorr()); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn signator_schnorr_get_pubkey() { - let signator = SignatorEnum::Schnorr(); - signator.public_key(); - } - - #[test] - #[should_panic(expected = "Schnorr algo not yet supported !")] - fn signator_schnorr_sign() { - let signator = SignatorEnum::Schnorr(); - signator.sign(b"message"); - } - - #[test] - fn pubkey_from_bytes() { - assert_eq!( - Err(PubkeyFromBytesError::InvalidBytesLen { - expected: *ed25519::PUBKEY_SIZE_IN_BYTES, - found: 2, - }), - PubKey::from_bytes(&[0u8, 1]), - ); - assert_eq!( - Err(PubkeyFromBytesError::InvalidBytesLen { - expected: *ed25519::PUBKEY_SIZE_IN_BYTES, - found: 33, - }), - PubKey::from_bytes(&[ - 0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 30, 31, 31 - ]), - ); - assert_eq!( - Ok(PubKey::Ed25519(ed25519::PublicKey::default())), - PubKey::from_bytes(&[0u8; 32]), - ); - } -} diff --git a/lib/crypto/src/keys/text_signable.rs b/lib/crypto/src/keys/text_signable.rs deleted file mode 100644 index 27c0c6c27a72a482b21fc4dadddc46d4324878c2..0000000000000000000000000000000000000000 --- a/lib/crypto/src/keys/text_signable.rs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Generic code for signing data in text format - -use super::*; - -/// Signatureable in text format -pub trait TextSignable: Debug + Clone { - /// Return signable text - fn as_signable_text(&self) -> String; - /// Return entity issuer pubkey - fn issuer_pubkey(&self) -> PubKey; - /// Return entity signature - fn signature(&self) -> Option<Sig>; - /// Change signature - fn set_signature(&mut self, _signature: Sig); - /// Sign entity - fn sign(&mut self, signator: &SignatorEnum) -> Result<String, SignError> { - if self.signature().is_some() { - return Err(SignError::AlreadySign); - } - match self.issuer_pubkey() { - PubKey::Ed25519(_) => match signator { - SignatorEnum::Ed25519(ed25519_signator) => { - let text = self.as_signable_text(); - let sig = ed25519_signator.sign(&text.as_bytes()); - self.set_signature(Sig::Ed25519(sig)); - let str_sig = sig.to_base64(); - Ok(format!("{}{}", text, str_sig)) - } - _ => Err(SignError::WrongAlgo), - }, - _ => Err(SignError::WrongAlgo), - } - } - /// Check signature of entity - fn verify(&self) -> Result<(), SigError> { - if let Some(signature) = self.signature() { - match self.issuer_pubkey() { - PubKey::Ed25519(pubkey) => match signature { - Sig::Ed25519(sig) => { - pubkey.verify(&self.as_signable_text().as_bytes(), &sig) - /* - if pubkey.verify(&self.as_signable_text().as_bytes(), &sig) { - Ok(()) - } else { - Err(SigError::InvalidSig()) - } - */ - } - _ => Err(SigError::NotSameAlgo), - }, - _ => Err(SigError::NotSameAlgo), - } - } else { - Err(SigError::NotSig) - } - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - #[derive(Debug, Clone)] - struct TextSignableTestImpl { - issuer: PubKey, - text: String, - sig: Option<Sig>, - } - - impl TextSignable for TextSignableTestImpl { - fn as_signable_text(&self) -> String { - format!("{}:{}", self.issuer, self.text) - } - fn issuer_pubkey(&self) -> PubKey { - self.issuer - } - fn signature(&self) -> Option<Sig> { - self.sig - } - fn set_signature(&mut self, new_signature: Sig) { - self.sig = Some(new_signature); - } - } - - #[test] - fn test_text_signable() { - let key_pair = super::super::tests::valid_key_pair_1(); - - let signator = key_pair - .generate_signator() - .expect("fail to generate signator"); - - let mut text_signable = TextSignableTestImpl { - issuer: key_pair.public_key(), - text: "toto".to_owned(), - sig: None, - }; - - assert_eq!(Err(SigError::NotSig), text_signable.verify()); - assert_eq!( - Err(SignError::WrongAlgo), - text_signable.sign(&SignatorEnum::Schnorr()) - ); - text_signable.issuer = PubKey::Schnorr(); - assert_eq!(Err(SignError::WrongAlgo), text_signable.sign(&signator)); - text_signable.issuer = key_pair.public_key(); - assert_eq!( - Ok("VYgskcKKh525MzFRzpCiT5KXCQrnFLTnzMLffbvm9uw:toto+IC1fFkkYo5ox2loc1IMLCtrir1i6oyljfshNXIyXVcz6sJMFqn+6o8Zip4XdTzoBEORkbcnEnqQEr4TgaHpCw==".to_owned()), - text_signable.sign(&signator) - ); - assert_eq!(Err(SignError::AlreadySign), text_signable.sign(&signator)); - assert_eq!(Ok(()), text_signable.verify()); - let old_sig = text_signable.sig.replace(Sig::Schnorr()); - assert_eq!(Err(SigError::NotSameAlgo), text_signable.verify()); - text_signable.sig = old_sig; - text_signable.issuer = PubKey::Schnorr(); - assert_eq!(Err(SigError::NotSameAlgo), text_signable.verify()); - } -} diff --git a/lib/crypto/src/lib.rs b/lib/crypto/src/lib.rs deleted file mode 100644 index 4c36431b691ce4533866f4d9716c21a975d0adc1..0000000000000000000000000000000000000000 --- a/lib/crypto/src/lib.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Manage cryptographic operations. - -#![deny( - clippy::option_unwrap_used, - clippy::result_unwrap_used, - missing_docs, - missing_copy_implementations, - trivial_casts, - trivial_numeric_casts, - unsafe_code, - unstable_features, - unused_import_braces, - unused_qualifications -)] -#![allow(non_camel_case_types)] - -pub mod bases; -pub mod hashs; -pub mod keys; -pub mod rand; -pub mod seeds; diff --git a/lib/crypto/src/rand.rs b/lib/crypto/src/rand.rs deleted file mode 100644 index 1b6f1024d61691b53377082b0843b7ace12ea232..0000000000000000000000000000000000000000 --- a/lib/crypto/src/rand.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Manage random generation. - -use byteorder::ByteOrder; -use ring::rand; - -/// An error with absolutely no details. -/// -/// *dup-crypto* uses this unit type as the error type in most of its results -/// because (a) usually the specific reasons for a failure are obvious or are -/// not useful to know, and/or (b) providing more details about a failure might -/// provide a dangerous side channel, and/or (c) it greatly simplifies the -/// error handling logic. -/// -/// Experience with using and implementing other crypto libraries like has -/// shown that sophisticated error reporting facilities often cause significant -/// bugs themselves, both within the crypto library and within users of the -/// crypto library. This approach attempts to minimize complexity in the hopes -/// of avoiding such problems. In some cases, this approach may be too extreme, -/// and it may be important for an operation to provide some details about the -/// cause of a failure. Users of *dup-crypto* are encouraged to report such cases so -/// that they can be addressed individually. -#[derive(Copy, Clone, Debug, PartialEq)] -pub struct UnspecifiedRandError; - -#[inline] -/// Generate random u32 -pub fn gen_u32() -> Result<u32, UnspecifiedRandError> { - let rng = rand::SystemRandom::new(); - let random_bytes = rand::generate::<[u8; 4]>(&rng).map_err(|_| UnspecifiedRandError)?; - Ok(byteorder::BigEndian::read_u32(&random_bytes.expose())) -} - -#[cfg(test)] -mod tests { - - use super::*; - - #[test] - fn test_gen_u32() { - assert_ne!(gen_u32(), gen_u32()) - } -} diff --git a/lib/crypto/src/seeds.rs b/lib/crypto/src/seeds.rs deleted file mode 100644 index 57b6873bc797164cc32f45f40aee41d33347d6ae..0000000000000000000000000000000000000000 --- a/lib/crypto/src/seeds.rs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (C) 2017-2019 The AXIOM TEAM Association. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -//! Provide wrappers around cryptographic seeds - -use crate::bases::b58::{bytes_to_str_base58, ToBase58}; -use crate::bases::*; -use crate::rand::UnspecifiedRandError; -use ring::rand; -use serde::{Deserialize, Serialize}; -use std::fmt::{self, Debug, Display, Formatter}; -use zeroize::Zeroize; - -/// Store a 32 bytes seed used to generate keys. -#[derive(Clone, Default, Deserialize, PartialEq, Eq, Hash, Serialize, Zeroize)] -#[zeroize(drop)] -pub struct Seed32([u8; 32]); - -impl AsRef<[u8]> for Seed32 { - fn as_ref(&self) -> &[u8] { - &self.0 - } -} - -impl ToBase58 for Seed32 { - fn to_base58(&self) -> String { - bytes_to_str_base58(&self.0[..]) - } -} - -impl Debug for Seed32 { - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - write!(f, "Seed32 {{ {} }}", self) - } -} - -impl Display for Seed32 { - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - write!(f, "{}", self.to_base58()) - } -} - -impl Seed32 { - #[inline] - /// Create new seed - pub fn new(seed_bytes: [u8; 32]) -> Seed32 { - Seed32(seed_bytes) - } - #[inline] - /// Create seed from base58 str - pub fn from_base58(base58_str: &str) -> Result<Self, BaseConvertionError> { - Ok(Seed32::new(b58::str_base58_to_32bytes(base58_str)?.0)) - } - #[inline] - /// Generate random seed - pub fn random() -> Result<Seed32, UnspecifiedRandError> { - let random_bytes = rand::generate::<[u8; 32]>(&rand::SystemRandom::new()) - .map_err(|_| UnspecifiedRandError)?; - Ok(Seed32::new(random_bytes.expose())) - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - #[test] - fn test_gen_random_seed() { - assert_ne!(Seed32::random(), Seed32::random()); - } -} diff --git a/lib/dubp/block-doc/Cargo.toml b/lib/dubp/block-doc/Cargo.toml index 803bcf4862938fc287d4b0c34d646300eb5992bf..88919ff16feee453fa08abdd0e9b0e63d3921c57 100644 --- a/lib/dubp/block-doc/Cargo.toml +++ b/lib/dubp/block-doc/Cargo.toml @@ -16,7 +16,7 @@ path = "src/lib.rs" dubp-common-doc = { path = "../common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../currency-params", version = "0.2.0" } dubp-user-docs = { path = "../user-docs", version = "0.14.0" } -dup-crypto = { path = "../../crypto", version = "0.8.0" } +dup-crypto = "0.8.0" durs-common-tools = { path = "../../tools/common-tools", version = "0.2.0" } failure = "0.1.5" json-pest-parser = { path = "../../tools/json-pest-parser", version = "0.2.0" } diff --git a/lib/dubp/common-doc/Cargo.toml b/lib/dubp/common-doc/Cargo.toml index 26e03480f0e4ed33d1513604e72b4d9e3aacc7de..ce1605a5a70daec6de2ad9e3ab45964398c9c227 100644 --- a/lib/dubp/common-doc/Cargo.toml +++ b/lib/dubp/common-doc/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" path = "src/lib.rs" [dependencies] -dup-crypto = { path = "../../crypto", version = "0.8.0" } +dup-crypto = "0.8.0" durs-common-tools = { path = "../../tools/common-tools", version = "0.2.0" } failure = "0.1.5" json-pest-parser = { path = "../../tools/json-pest-parser", version = "0.2.0" } diff --git a/lib/dubp/indexes/Cargo.toml b/lib/dubp/indexes/Cargo.toml index ac841101f0d54188cb5e48d6bc3b9a8160c8738e..2a059972f32810dc23adeb0a09314f0b85fe1e21 100644 --- a/lib/dubp/indexes/Cargo.toml +++ b/lib/dubp/indexes/Cargo.toml @@ -16,7 +16,7 @@ path = "src/lib.rs" dubp-common-doc = { path = "../common-doc"} #, version = "0.1.0" } dubp-user-docs = { path = "../user-docs"} #, version = "0.1.0" } dubp-currency-params = { path = "../currency-params", version = "0.2.0" } -dup-crypto = { path = "../../crypto", version = "0.8.0" } +dup-crypto = "0.8.0" durs-common-tools = { path = "../../tools/common-tools", version = "0.2.0" } failure = "0.1.5" log = "0.4.*" diff --git a/lib/dubp/user-docs/Cargo.toml b/lib/dubp/user-docs/Cargo.toml index 959e9ddc5d175618d0f3f76ed4d2f4c1e7eab3d8..9299130290620dd1711e751ff148f5529cba6947 100644 --- a/lib/dubp/user-docs/Cargo.toml +++ b/lib/dubp/user-docs/Cargo.toml @@ -14,7 +14,7 @@ path = "src/lib.rs" [dependencies] dubp-common-doc = { path = "../common-doc"} #, version = "0.1.0" } -dup-crypto = { path = "../../crypto", version = "0.8.0" } +dup-crypto = "0.8.0" durs-common-tools = { path = "../../tools/common-tools", version = "0.2.0" } failure = "0.1.5" json-pest-parser = { path = "../../tools/json-pest-parser", version = "0.2.0" } diff --git a/lib/dubp/wot/Cargo.toml b/lib/dubp/wot/Cargo.toml index bc40a4fbf9cc4e699dec9b92411a8931de509cbc..0e3afdcbf1a2a6438c2d0934e212a5e9bdbb71fb 100644 --- a/lib/dubp/wot/Cargo.toml +++ b/lib/dubp/wot/Cargo.toml @@ -13,7 +13,7 @@ edition = "2018" path = "lib.rs" [dependencies] -dup-crypto = { path = "../../crypto", version = "0.8.0" } +dup-crypto = "0.8.0" durs-common-tools = { path = "../../tools/common-tools", version = "0.2.0" } log = "0.4.*" rayon = "1.3.0" diff --git a/lib/dunp/network-documents/Cargo.toml b/lib/dunp/network-documents/Cargo.toml index 3930d37f97181cdac374fa384b4437d1f384ffa5..017ccd72a9cc0fef9009c412d9c90103f1a30c62 100644 --- a/lib/dunp/network-documents/Cargo.toml +++ b/lib/dunp/network-documents/Cargo.toml @@ -15,7 +15,7 @@ path = "src/lib.rs" dubp-common-doc = { path = "../../dubp/common-doc" } #, version = "0.1.0" } dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs= { path = "../../dubp/user-docs" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" durs-common-tests-tools = { path = "../../tests-tools/common-tests-tools" } durs-common-tools = { path = "../../tools/common-tools" } failure = "0.1.5" diff --git a/lib/modules-lib/bc-db-reader/Cargo.toml b/lib/modules-lib/bc-db-reader/Cargo.toml index 7523a25c01653914a03ed4a45bf0fd07820f2dce..bb8626a38d8604991af10a2baad48dc9882d2d69 100644 --- a/lib/modules-lib/bc-db-reader/Cargo.toml +++ b/lib/modules-lib/bc-db-reader/Cargo.toml @@ -13,7 +13,7 @@ path = "src/lib.rs" dubp-block-doc = { path = "../../dubp/block-doc"} #, version = "0.1.0" } dubp-common-doc = { path = "../../dubp/common-doc"} #, version = "0.1.0" } dubp-indexes = { path = "../../dubp/indexes"} #, version = "0.1.0" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs= { path = "../../dubp/user-docs" } durs-conf = { path = "../../core/conf" } diff --git a/lib/modules/blockchain/bc-db-writer/Cargo.toml b/lib/modules/blockchain/bc-db-writer/Cargo.toml index c530fd5bb3f7e706f8957f41ee0b671fe06cd173..d4ce332a6438fcc25f3ad7d6c2ff219d706299e1 100644 --- a/lib/modules/blockchain/bc-db-writer/Cargo.toml +++ b/lib/modules/blockchain/bc-db-writer/Cargo.toml @@ -15,7 +15,7 @@ dubp-common-doc = { path = "../../../dubp/common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../../../dubp/currency-params" } dubp-indexes = { path = "../../../dubp/indexes"} #, version = "0.1.0" } dubp-user-docs= { path = "../../../dubp/user-docs" } -dup-crypto = { path = "../../../crypto" } +dup-crypto = "0.8.0" durs-bc-db-reader = { path = "../../../modules-lib/bc-db-reader" } durs-common-tools = { path = "../../../tools/common-tools" } durs-conf = { path = "../../../core/conf" } diff --git a/lib/modules/blockchain/blockchain/Cargo.toml b/lib/modules/blockchain/blockchain/Cargo.toml index b1a5a045e874d078ee33fde066ec8228d1f65f16..a0fd9dc795875cacae31215243231c9df0c68c05 100644 --- a/lib/modules/blockchain/blockchain/Cargo.toml +++ b/lib/modules/blockchain/blockchain/Cargo.toml @@ -16,7 +16,7 @@ dubp-common-doc = { path = "../../../dubp/common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../../../dubp/currency-params" } durs-bc-db-reader = { path = "../../../modules-lib/bc-db-reader" } durs-bc-db-writer = { path = "../bc-db-writer" } -dup-crypto = { path = "../../../crypto" } +dup-crypto = "0.8.0" dubp-user-docs= { path = "../../../dubp/user-docs" } durs-common-tools = { path = "../../../tools/common-tools" } durs-network-documents = { path = "../../../dunp/network-documents" } diff --git a/lib/modules/gva/Cargo.toml b/lib/modules/gva/Cargo.toml index 909be9c0cf8956b82972dd1217152f78c28aa3ef..48aef115c768e7385d997561fb7201f489b5ad3f 100644 --- a/lib/modules/gva/Cargo.toml +++ b/lib/modules/gva/Cargo.toml @@ -14,7 +14,7 @@ actix-cors = "0.2.0" actix-rt = "1.0.0" actix-web = "2.0.0" dubp-block-doc = { path = "../../dubp/block-doc"} #, version = "0.1.0" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" durs-bc-db-reader = { path = "../../modules-lib/bc-db-reader", features = ["client-indexer"] } durs-conf = { path = "../../core/conf" } durs-message = { path = "../../core/message" } diff --git a/lib/modules/skeleton/Cargo.toml b/lib/modules/skeleton/Cargo.toml index 03282feb0bd9ba7f9c4cbe025ea83f82f4082c02..6109a7dc2b84511d528dba847a43222248f764a7 100644 --- a/lib/modules/skeleton/Cargo.toml +++ b/lib/modules/skeleton/Cargo.toml @@ -15,7 +15,7 @@ durs-conf = { path = "../../core/conf" } durs-message = { path = "../../core/message" } durs-module = { path = "../../core/module" } durs-network = { path = "../../core/network" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" dubp-currency-params = { path = "../../dubp/currency-params" } durs-common-tools = { path = "../../tools/common-tools" } failure = "0.1.5" diff --git a/lib/modules/tui/Cargo.toml b/lib/modules/tui/Cargo.toml index 1b71b320fe41e50bd102ac134f51e96550ffa1c9..1b04d794d393bd64dad5c327d73488afc9fc7830 100644 --- a/lib/modules/tui/Cargo.toml +++ b/lib/modules/tui/Cargo.toml @@ -11,7 +11,7 @@ path = "lib.rs" [dependencies] durs-conf = { path = "../../core/conf" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs= { path = "../../dubp/user-docs" } durs-common-tools = { path = "../../tools/common-tools" } diff --git a/lib/modules/ws2p-v1-legacy/Cargo.toml b/lib/modules/ws2p-v1-legacy/Cargo.toml index 8146dfce3dca4c8134be861572b91e5bb62e18d7..5df4ca8dba5c09ea1d7ca7e0365e35632455d4a8 100644 --- a/lib/modules/ws2p-v1-legacy/Cargo.toml +++ b/lib/modules/ws2p-v1-legacy/Cargo.toml @@ -15,7 +15,7 @@ dubp-block-doc = { path = "../../dubp/block-doc"} #, version = "0.1.0" } dubp-common-doc = { path = "../../dubp/common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs= { path = "../../dubp/user-docs" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" durs-conf = { path = "../../core/conf" } durs-module = { path = "../../core/module" } durs-network = { path = "../../core/network" } diff --git a/lib/modules/ws2p/ws2p-messages/Cargo.toml b/lib/modules/ws2p/ws2p-messages/Cargo.toml index 59bd89f547cc5abce9daa56891bf151126219fc8..f711fcb789864ee5adab2462a1c4ff5040beb88e 100644 --- a/lib/modules/ws2p/ws2p-messages/Cargo.toml +++ b/lib/modules/ws2p/ws2p-messages/Cargo.toml @@ -18,7 +18,7 @@ dubp-currency-params = { path = "../../../dubp/currency-params" } dubp-user-docs= { path = "../../../dubp/user-docs" } durs-network-documents = { path = "../../../dunp/network-documents" } durs-common-tools = { path = "../../../tools/common-tools" } -dup-crypto = { path = "../../../crypto" } +dup-crypto = "0.8.0" failure = "0.1.5" log = "0.4.*" serde = "1.0.*" diff --git a/lib/modules/ws2p/ws2p-protocol/Cargo.toml b/lib/modules/ws2p/ws2p-protocol/Cargo.toml index 20991e9f368f695d480e44b87b60ae0b30e53761..8979f9c47ded28045060cb17f5575d98afd1400e 100644 --- a/lib/modules/ws2p/ws2p-protocol/Cargo.toml +++ b/lib/modules/ws2p/ws2p-protocol/Cargo.toml @@ -14,7 +14,7 @@ dubp-common-doc = { path = "../../../dubp/common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../../../dubp/currency-params" } dubp-user-docs= { path = "../../../dubp/user-docs" } durs-common-tools = { path = "../../../tools/common-tools" } -dup-crypto = { path = "../../../crypto" } +dup-crypto = "0.8.0" durs-module = { path = "../../../core/module" } durs-network-documents = { path = "../../../dunp/network-documents" } durs-ws2p-messages = { path = "../ws2p-messages" } diff --git a/lib/modules/ws2p/ws2p/Cargo.toml b/lib/modules/ws2p/ws2p/Cargo.toml index 5ea3585a881cdc6734f5301ee028f4a826ba58cb..264d3a43163a948ecc2e13d9054d7304ed04f791 100644 --- a/lib/modules/ws2p/ws2p/Cargo.toml +++ b/lib/modules/ws2p/ws2p/Cargo.toml @@ -16,7 +16,7 @@ dubp-currency-params = { path = "../../../dubp/currency-params" } dubp-user-docs= { path = "../../../dubp/user-docs" } durs-network-documents = { path = "../../../dunp/network-documents" } durs-common-tools = { path = "../../../tools/common-tools" } -dup-crypto = { path = "../../../crypto" } +dup-crypto = "0.8.0" durs-conf= { path = "../../../core/conf" } durs-ws2p-messages = { path = "../ws2p-messages" } durs-ws2p-protocol = { path = "../ws2p-protocol" } diff --git a/lib/tests-tools/bc-db-tests-tools/Cargo.toml b/lib/tests-tools/bc-db-tests-tools/Cargo.toml index 97ad6bd5b93bf3ce38d71e6dd7dd915fd8112a61..2ff045cfcf1a55e09d8a3ad6d9d54373be98a327 100644 --- a/lib/tests-tools/bc-db-tests-tools/Cargo.toml +++ b/lib/tests-tools/bc-db-tests-tools/Cargo.toml @@ -17,7 +17,7 @@ dubp-block-doc = { path = "../../dubp/block-doc"} #, version = "0.1.0" } dubp-common-doc = { path = "../../dubp/common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs = { path = "../../dubp/user-docs" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" durs-bc-db-reader = { path = "../../modules-lib/bc-db-reader" } durs-bc-db-writer = { path = "../../modules/blockchain/bc-db-writer" } dup-crypto-tests-tools = { path = "../crypto-tests-tools" } diff --git a/lib/tests-tools/blocks-tests-tools/Cargo.toml b/lib/tests-tools/blocks-tests-tools/Cargo.toml index 1b86a3303775b9e90f8d5913279fd0e04dee4c7e..4bcc220dc4ca81e160ec44abb89b5bbb6f587c36 100644 --- a/lib/tests-tools/blocks-tests-tools/Cargo.toml +++ b/lib/tests-tools/blocks-tests-tools/Cargo.toml @@ -17,7 +17,7 @@ dubp-block-doc = { path = "../../dubp/block-doc"} #, version = "0.1.0" } dubp-common-doc = { path = "../../dubp/common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs = { path = "../../dubp/user-docs" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" dup-crypto-tests-tools = { path = "../crypto-tests-tools" } dubp-user-docs-tests-tools = { path = "../user-docs-tests-tools" } json-pest-parser = { path = "../../tools/json-pest-parser" } diff --git a/lib/tests-tools/crypto-tests-tools/Cargo.toml b/lib/tests-tools/crypto-tests-tools/Cargo.toml index a718019a90b6daa0ac2c8788c016d58260998f23..c1700695eb45dd3b8752542148a0d550bf5fe246 100644 --- a/lib/tests-tools/crypto-tests-tools/Cargo.toml +++ b/lib/tests-tools/crypto-tests-tools/Cargo.toml @@ -13,6 +13,6 @@ edition = "2018" path = "src/lib.rs" [dependencies] -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" [dev-dependencies] diff --git a/lib/tests-tools/user-docs-tests-tools/Cargo.toml b/lib/tests-tools/user-docs-tests-tools/Cargo.toml index 5906780fd37c1a1663874a7abbcb98ce41a64f90..54603b5fe54cd7d94f0fa1481da911c7510c6ad6 100644 --- a/lib/tests-tools/user-docs-tests-tools/Cargo.toml +++ b/lib/tests-tools/user-docs-tests-tools/Cargo.toml @@ -17,7 +17,7 @@ dubp-block-doc = { path = "../../dubp/block-doc"} #, version = "0.1.0" } dubp-common-doc = { path = "../../dubp/common-doc"} #, version = "0.1.0" } dubp-currency-params = { path = "../../dubp/currency-params" } dubp-user-docs = { path = "../../dubp/user-docs" } -dup-crypto = { path = "../../crypto" } +dup-crypto = "0.8.0" dup-crypto-tests-tools = { path = "../crypto-tests-tools" } [dev-dependencies]