Skip to content

Commit

Permalink
wip: first implementation of deriving encryption key from passphrase
Browse files Browse the repository at this point in the history
  • Loading branch information
Nuhvi committed Dec 8, 2023
1 parent 9326933 commit 68bdfa9
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 1 deletion.
41 changes: 41 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions kytes/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
blake3 = "1.5.0"
bytes = "1.5.0"
rand = "0.8.5"
z32 = "1.0.2"
35 changes: 34 additions & 1 deletion kytes/src/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use bytes::{BufMut, Bytes, BytesMut};
use rand::Rng;

const SEED_FILE_PREFIX: &str = "kytes encrypted-seed";
const SEED_FILE_PREFIX: &str = "kytes seed";
const VERSION: u8 = 0;

const PASSPHRASE_HASHING_ITERATIONS: i32 = 100_000;

/// Takes an encrypted seed and format it into a seed file as follows:
/// `kytes encrypted-seed v<version> <zbase32 encoded encrypted_seed>`
pub fn format_encrypted_seed_file(encrypted_seed: &[u8; 32]) -> Bytes {
Expand Down Expand Up @@ -35,19 +37,50 @@ pub fn generate_seed() -> [u8; 32] {
rng.gen()
}

pub fn seed_encryption_key(passphrase: &str) -> [u8; 32] {
let mut hash: [u8; 32] = blake3::hash(passphrase.as_bytes()).into();

for i in 0..PASSPHRASE_HASHING_ITERATIONS {
hash = blake3::hash(&hash).into();
}

hash.to_owned()
}

#[cfg(test)]
mod test {
use std::time::Instant;

use crate::passphrase::generate_4words_passphrase;

use super::*;

#[test]
fn test_format_encrypted_seed_file() {
let seed = generate_seed();
let seed_file = format_encrypted_seed_file(&seed);

dbg!(&seed_file);

assert_eq!(seed_file.len(), 52 + 4 + SEED_FILE_PREFIX.len());
assert!(seed_file.starts_with(SEED_FILE_PREFIX.as_bytes()));
assert!(seed_file.starts_with(SEED_FILE_PREFIX.as_bytes()));
assert_eq!(encrypted_seed_file_version(&seed_file).unwrap(), 0);
assert!(seed_file.ends_with(&z32::encode(&seed).as_bytes()));
}

#[test]
fn hash() {
let passphrase = generate_4words_passphrase();

let start = Instant::now();

println!("start hashing...");

let hash = seed_encryption_key(&passphrase);

println!("final hash: {:?}", hash);

println!("{} ms", start.elapsed().as_millis());
}
}

0 comments on commit 68bdfa9

Please sign in to comment.