Skip to content

Commit

Permalink
Merge pull request #4 from securesecrets/viewing-keys
Browse files Browse the repository at this point in the history
Viewing keys
  • Loading branch information
FloppyDisck authored Feb 16, 2022
2 parents 256d7dc + a7e2121 commit 0064bb5
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 2 deletions.
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "flexible-permits"
name = "query-authentication"
version = "0.1.0"
edition = "2018"

Expand All @@ -16,4 +16,6 @@ schemars = "0.7"
remain = "0.2.2"
ripemd160 = "0.9.1"
secp256k1 = "0.20.3"
bech32 = "0.8.1"
bech32 = "0.8.1"

sha2 = { version = "0.9.1", default-features = false }
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod permit;
pub mod transaction;
pub mod viewing_keys;
66 changes: 66 additions & 0 deletions src/viewing_keys.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use sha2::{Digest, Sha256};

pub trait ViewingKey<const KEY_SIZE: usize>: ToString {
fn compare_hashes(s1: &[u8], s2: &[u8]) -> bool {
s1.eq(s2)
}

fn compare(&self, hashed: &[u8]) -> bool {
Self::compare_hashes(&self.hash(), hashed)
}

fn hash(&self) -> [u8; KEY_SIZE] {
Sha256::digest(self.to_string().as_bytes())
.as_slice()
.try_into()
.expect("Incorrect password length")
}
}

#[cfg(test)]
mod viewing_key_tests {
use crate::viewing_keys::ViewingKey;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
struct Key(pub String);

impl ToString for Key {
fn to_string(&self) -> String {
self.0.clone()
}
}

impl ViewingKey<32> for Key {}

#[test]
fn hash_creation() {
let pwd = Key("password".to_string());

let hashed = pwd.hash();

assert_eq!(hashed.len(), 32)
}

#[test]
fn hash_comparing() {
let pwd = Key("password".to_string());
let hashed = pwd.hash();

assert!(pwd.compare(&hashed));
assert!(Key::compare_hashes(&hashed, &Key("password".to_string()).hash()));

let wrong_pwd = Key("wrong_password".to_string());
let wrong_hashed = wrong_pwd.hash();

for i in 0..32 {
assert_ne!(hashed[i], wrong_hashed[i]);
}
assert!(!pwd.compare(&wrong_hashed));
assert!(!Key::compare_hashes(&hashed, &wrong_hashed));
}
}

0 comments on commit 0064bb5

Please sign in to comment.