57 lines
1.7 KiB
Rust
57 lines
1.7 KiB
Rust
use std::{collections::HashMap, fs::read_to_string};
|
|
|
|
use ed25519_dalek::{ed25519::signature::SignerMut, Signature, SigningKey, VerifyingKey};
|
|
|
|
pub fn from_bytes(bytes: Vec<u8>) -> Result<VerifyingKey, anyhow::Error> {
|
|
let arr: [u8; 32] = TryInto::try_into(bytes).expect("");
|
|
Ok(VerifyingKey::from_bytes(&arr)?)
|
|
}
|
|
|
|
pub fn to_bytes(key: &VerifyingKey) -> Vec<u8> {
|
|
Into::<Vec<u8>>::into(key.to_bytes())
|
|
}
|
|
|
|
pub fn from_hex(s: &str) -> Result<VerifyingKey, anyhow::Error> {
|
|
from_bytes(hex::decode(s)?.try_into()?)
|
|
}
|
|
|
|
pub fn to_hex(key: &VerifyingKey) -> String {
|
|
hex::encode(key.to_bytes())
|
|
}
|
|
|
|
pub fn signing_key_from_bytes(bytes: Vec<u8>) -> Result<SigningKey, anyhow::Error> {
|
|
let arr: [u8; 32] = TryInto::try_into(bytes).expect("");
|
|
Ok(SigningKey::from_bytes(&arr))
|
|
}
|
|
|
|
pub fn signing_key_from_hex(s: &str) -> Result<SigningKey, anyhow::Error> {
|
|
signing_key_from_bytes(hex::decode(s)?.try_into()?)
|
|
}
|
|
|
|
pub fn signing_key_to_hex(key: &SigningKey) -> String {
|
|
hex::encode(key.to_bytes())
|
|
}
|
|
|
|
pub fn sign(key: &mut SigningKey, msg: Vec<u8>) -> Signature {
|
|
key.try_sign(&msg).unwrap()
|
|
}
|
|
|
|
pub fn verify(key: &VerifyingKey, msg: &Vec<u8>, sig: &Signature) -> Result<(), anyhow::Error> {
|
|
let _ = key.verify_strict(msg, sig)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub type Keychain = HashMap<[u8; 32], SigningKey>;
|
|
|
|
pub fn mk_keychain(keys_path: &str) -> Keychain {
|
|
let signing_keys = read_to_string(&keys_path).expect("Error reading file");
|
|
let mut keychain: Keychain = HashMap::new();
|
|
for key in signing_keys.lines() {
|
|
let secret_key = hex::decode(key.trim()).unwrap().try_into().unwrap();
|
|
let skey = SigningKey::from_bytes(&secret_key);
|
|
let vkey = skey.verifying_key();
|
|
keychain.insert(vkey.to_bytes(), skey);
|
|
}
|
|
keychain
|
|
}
|