-
Notifications
You must be signed in to change notification settings - Fork 244
Move ethkey crypto utils to parity crypto crate #210
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
fd0e2ec
EthKey modules moved to crypto crate
grbIzl fc1298f
2018 edition changes
grbIzl f1cf5dc
2 converters added
grbIzl a6f8c9f
Remove quick error
grbIzl 6940745
Public key primitives moved to the separate module
grbIzl 3c047ed
Feature include for public key module
grbIzl cad7824
Rust hex version increased, module docs added
grbIzl f6c4702
Move ethereum types include under public key feature
grbIzl 9b7a0c9
More specific names for files
grbIzl 34649b5
Errors usages corrected
grbIzl c1ba58a
Documentation for module components improved
grbIzl 377db06
Test and benchmark added
grbIzl 3a24be0
Static initialization for curve order method
grbIzl dc7dc4d
Couple of comments changed
grbIzl 46ece97
Generation point bytes glued into one array
grbIzl 7ca69cc
Tests for math operations added
grbIzl 5a77f83
Proper feauture for benches
grbIzl a69d130
Comments added to methods and parameters added
grbIzl 2acb917
Switch to try_from and Infallible traits
grbIzl fedfc96
Comment removed
grbIzl 669933f
Ethereum types version increased
grbIzl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| // Copyright 2015-2019 Parity Technologies (UK) Ltd. | ||
| // This file is part of Parity Ethereum. | ||
|
|
||
| // Parity Ethereum is free software: you can redistribute it and/or modify | ||
| // it under the terms of the GNU General Public License as published by | ||
| // the Free Software Foundation, either version 3 of the License, or | ||
| // (at your option) any later version. | ||
|
|
||
| // Parity Ethereum 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 General Public License for more details. | ||
|
|
||
| // You should have received a copy of the GNU General Public License | ||
| // along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>. | ||
|
|
||
|
grbIzl marked this conversation as resolved.
Outdated
|
||
| use secp256k1; | ||
| use std::io; | ||
| use crate::error::SymmError; | ||
| use quick_error::quick_error; | ||
|
|
||
| quick_error! { | ||
|
grbIzl marked this conversation as resolved.
Outdated
|
||
| #[derive(Debug)] | ||
| pub enum Error { | ||
| Secp(e: secp256k1::Error) { | ||
| display("secp256k1 error: {}", e) | ||
| cause(e) | ||
| from() | ||
| } | ||
| Io(e: io::Error) { | ||
| display("i/o error: {}", e) | ||
| cause(e) | ||
| from() | ||
| } | ||
| InvalidMessage { | ||
| display("invalid message") | ||
| } | ||
| Symm(e: SymmError) { | ||
| cause(e) | ||
| from() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// ECDH functions | ||
| pub mod ecdh { | ||
| use secp256k1::{self, ecdh, key}; | ||
| use super::Error; | ||
| use crate::{Secret, Public, SECP256K1}; | ||
|
|
||
| /// Agree on a shared secret | ||
| pub fn agree(secret: &Secret, public: &Public) -> Result<Secret, Error> { | ||
| let context = &SECP256K1; | ||
| let pdata = { | ||
| let mut temp = [4u8; 65]; | ||
| (&mut temp[1..65]).copy_from_slice(&public[0..64]); | ||
| temp | ||
| }; | ||
|
|
||
| let publ = key::PublicKey::from_slice(context, &pdata)?; | ||
| let sec = key::SecretKey::from_slice(context, secret.as_bytes())?; | ||
| let shared = ecdh::SharedSecret::new_raw(context, &publ, &sec); | ||
|
|
||
| Secret::from_unsafe_slice(&shared[0..32]) | ||
| .map_err(|_| Error::Secp(secp256k1::Error::InvalidSecretKey)) | ||
| } | ||
| } | ||
|
|
||
| /// ECIES function | ||
| pub mod ecies { | ||
| use ethereum_types::H128; | ||
| use super::{ecdh, Error}; | ||
| use crate::{Random, Generator, Public, Secret, aes, digest, hmac, is_equal}; | ||
|
|
||
| /// Encrypt a message with a public key, writing an HMAC covering both | ||
| /// the plaintext and authenticated data. | ||
| /// | ||
| /// Authenticated data may be empty. | ||
| pub fn encrypt(public: &Public, auth_data: &[u8], plain: &[u8]) -> Result<Vec<u8>, Error> { | ||
| let r = Random.generate()?; | ||
| let z = ecdh::agree(r.secret(), public)?; | ||
| let mut key = [0u8; 32]; | ||
| kdf(&z, &[0u8; 0], &mut key); | ||
|
|
||
| let ekey = &key[0..16]; | ||
| let mkey = hmac::SigKey::sha256(&digest::sha256(&key[16..32])); | ||
|
|
||
| let mut msg = vec![0u8; 1 + 64 + 16 + plain.len() + 32]; | ||
| msg[0] = 0x04u8; | ||
|
grbIzl marked this conversation as resolved.
Outdated
|
||
| { | ||
| let msgd = &mut msg[1..]; | ||
|
grbIzl marked this conversation as resolved.
Outdated
|
||
| msgd[0..64].copy_from_slice(r.public().as_bytes()); | ||
| let iv = H128::random(); | ||
|
ordian marked this conversation as resolved.
Outdated
|
||
| msgd[64..80].copy_from_slice(iv.as_bytes()); | ||
| { | ||
| let cipher = &mut msgd[(64 + 16)..(64 + 16 + plain.len())]; | ||
| aes::encrypt_128_ctr(ekey, iv.as_bytes(), plain, cipher)?; | ||
| } | ||
| let mut hmac = hmac::Signer::with(&mkey); | ||
| { | ||
| let cipher_iv = &msgd[64..(64 + 16 + plain.len())]; | ||
| hmac.update(cipher_iv); | ||
| } | ||
| hmac.update(auth_data); | ||
| let sig = hmac.sign(); | ||
| msgd[(64 + 16 + plain.len())..].copy_from_slice(&sig); | ||
| } | ||
| Ok(msg) | ||
| } | ||
|
|
||
| /// Decrypt a message with a secret key, checking HMAC for ciphertext | ||
| /// and authenticated data validity. | ||
| pub fn decrypt(secret: &Secret, auth_data: &[u8], encrypted: &[u8]) -> Result<Vec<u8>, Error> { | ||
| let meta_len = 1 + 64 + 16 + 32; | ||
|
grbIzl marked this conversation as resolved.
Outdated
|
||
| if encrypted.len() < meta_len || encrypted[0] < 2 || encrypted[0] > 4 { | ||
| return Err(Error::InvalidMessage); //invalid message: publickey | ||
| } | ||
|
|
||
| let e = &encrypted[1..]; | ||
| let p = Public::from_slice(&e[0..64]); | ||
| let z = ecdh::agree(secret, &p)?; | ||
| let mut key = [0u8; 32]; | ||
| kdf(&z, &[0u8; 0], &mut key); | ||
|
|
||
| let ekey = &key[0..16]; | ||
| let mkey = hmac::SigKey::sha256(&digest::sha256(&key[16..32])); | ||
|
|
||
| let clen = encrypted.len() - meta_len; | ||
|
grbIzl marked this conversation as resolved.
Outdated
|
||
| let cipher_with_iv = &e[64..(64+16+clen)]; | ||
| let cipher_iv = &cipher_with_iv[0..16]; | ||
| let cipher_no_iv = &cipher_with_iv[16..]; | ||
| let msg_mac = &e[(64+16+clen)..]; | ||
|
|
||
| // Verify tag | ||
| let mut hmac = hmac::Signer::with(&mkey); | ||
| hmac.update(cipher_with_iv); | ||
| hmac.update(auth_data); | ||
| let mac = hmac.sign(); | ||
|
|
||
| if !is_equal(&mac.as_ref()[..], msg_mac) { | ||
| return Err(Error::InvalidMessage); | ||
| } | ||
|
|
||
| let mut msg = vec![0u8; clen]; | ||
| aes::decrypt_128_ctr(ekey, cipher_iv, cipher_no_iv, &mut msg[..])?; | ||
| Ok(msg) | ||
| } | ||
|
|
||
| fn kdf(secret: &Secret, s1: &[u8], dest: &mut [u8]) { | ||
| // SEC/ISO/Shoup specify counter size SHOULD be equivalent | ||
| // to size of hash output, however, it also notes that | ||
| // the 4 bytes is okay. NIST specifies 4 bytes. | ||
| let mut ctr = 1u32; | ||
| let mut written = 0usize; | ||
| while written < dest.len() { | ||
| let mut hasher = digest::Hasher::sha256(); | ||
| let ctrs = [(ctr >> 24) as u8, (ctr >> 16) as u8, (ctr >> 8) as u8, ctr as u8]; | ||
| hasher.update(&ctrs); | ||
| hasher.update(secret.as_bytes()); | ||
| hasher.update(s1); | ||
| let d = hasher.finish(); | ||
| &mut dest[written..(written + 32)].copy_from_slice(&d); | ||
| written += 32; | ||
| ctr += 1; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::ecies; | ||
| use crate::{Random, Generator}; | ||
|
|
||
| #[test] | ||
| fn ecies_shared() { | ||
| let kp = Random.generate().unwrap(); | ||
| let message = b"So many books, so little time"; | ||
|
|
||
| let shared = b"shared"; | ||
| let wrong_shared = b"incorrect"; | ||
| let encrypted = ecies::encrypt(kp.public(), shared, message).unwrap(); | ||
| assert!(encrypted[..] != message[..]); | ||
| assert_eq!(encrypted[0], 0x04); | ||
|
|
||
| assert!(ecies::decrypt(kp.secret(), wrong_shared, &encrypted).is_err()); | ||
| let decrypted = ecies::decrypt(kp.secret(), shared, &encrypted).unwrap(); | ||
| assert_eq!(decrypted[..message.len()], message[..]); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.