Skip to content

Commit

Permalink
fix encoding of private keys
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed May 26, 2024
1 parent 45673f2 commit d021439
Show file tree
Hide file tree
Showing 9 changed files with 140 additions and 140 deletions.
1 change: 1 addition & 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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ amplify = "4.6.0"
strict_encoding = "2.7.0-beta.4"
ascii-armor = "0.7.0"
baid64 = "0.2.2"
base64 = "0.22.1"
secp256k1 = { version = "0.29.0", features = ["rand", "global-context", "rand-std"] }
ec25519 = "0.1.0"
rand = "0.8.5"
Expand Down
27 changes: 1 addition & 26 deletions src/bip340.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,14 @@
// limitations under the License.

use std::cmp::Ordering;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::str::FromStr;

use baid64::{Baid64ParseError, DisplayBaid64, FromBaid64Str};
use secp256k1::schnorr::Signature;
use secp256k1::{Keypair, Message, SecretKey, XOnlyPublicKey, SECP256K1};

use crate::{Algo, Chain, InvalidPubkey, InvalidSig, SsiPub, SsiSig};

#[derive(Clone, Eq, PartialEq)]
#[derive(Clone, Eq, PartialEq, From)]
pub struct Bip340Secret(pub(crate) SecretKey);

impl Ord for Bip340Secret {
Expand All @@ -46,18 +42,6 @@ impl Hash for Bip340Secret {
fn hash<H: Hasher>(&self, state: &mut H) { self.0.secret_bytes().hash(state) }
}

impl DisplayBaid64 for Bip340Secret {
const HRI: &'static str = "bip340-priv";
const CHUNKING: bool = false;
const PREFIX: bool = true;
const EMBED_CHECKSUM: bool = true;
const MNEMONIC: bool = false;

fn to_baid64_payload(&self) -> [u8; 32] { <[u8; 32]>::from(self.clone()) }
}

impl FromBaid64Str for Bip340Secret {}

impl From<Bip340Secret> for [u8; 32] {
fn from(ssi: Bip340Secret) -> Self { ssi.0.secret_bytes() }
}
Expand All @@ -68,15 +52,6 @@ impl From<[u8; 32]> for Bip340Secret {
}
}

impl Display for Bip340Secret {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_baid64(f) }
}

impl FromStr for Bip340Secret {
type Err = Baid64ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> { Self::from_baid64_str(s) }
}

impl Bip340Secret {
pub fn new(chain: Chain) -> Self {
use rand::thread_rng;
Expand Down
27 changes: 1 addition & 26 deletions src/ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,14 @@
// limitations under the License.

use std::cmp::Ordering;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::str::FromStr;

use baid64::{Baid64ParseError, DisplayBaid64, FromBaid64Str};
use ec25519::{KeyPair, Noise, PublicKey, SecretKey, Seed, Signature};

use crate::{Algo, Chain, InvalidPubkey, InvalidSig, SsiPub, SsiSig};

#[derive(Clone, Eq, PartialEq)]
#[derive(Clone, Eq, PartialEq, From)]
pub struct Ed25519Secret(pub(crate) SecretKey);

impl Ord for Ed25519Secret {
Expand All @@ -46,18 +42,6 @@ impl Hash for Ed25519Secret {
fn hash<H: Hasher>(&self, state: &mut H) { self.0.as_slice().hash(state) }
}

impl DisplayBaid64<64> for Ed25519Secret {
const HRI: &'static str = "ed25519-priv";
const CHUNKING: bool = false;
const PREFIX: bool = true;
const EMBED_CHECKSUM: bool = true;
const MNEMONIC: bool = false;

fn to_baid64_payload(&self) -> [u8; 64] { <[u8; 64]>::from(self.clone()) }
}

impl FromBaid64Str<64> for Ed25519Secret {}

impl From<Ed25519Secret> for [u8; 64] {
fn from(ssi: Ed25519Secret) -> Self { *ssi.0.deref() }
}
Expand All @@ -68,15 +52,6 @@ impl From<[u8; 64]> for Ed25519Secret {
}
}

impl Display for Ed25519Secret {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_baid64(f) }
}

impl FromStr for Ed25519Secret {
type Err = Baid64ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> { Self::from_baid64_str(s) }
}

impl Ed25519Secret {
pub fn new(chain: Chain) -> Self {
loop {
Expand Down
26 changes: 11 additions & 15 deletions src/encrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@

use std::str::FromStr;

use aes_gcm::aead::{Aead, OsRng};
use aes_gcm::{AeadCore, Aes256Gcm, KeyInit, Nonce};
use aes_gcm::aead::{Aead, Nonce, OsRng};
use aes_gcm::{AeadCore, Aes256Gcm, KeyInit};
use amplify::confinement::{Confined, SmallOrdMap, U64 as U64MAX};
use amplify::{Bytes32, Wrapper};
use armor::{ArmorHeader, ArmorParseError, AsciiArmor};
Expand Down Expand Up @@ -75,6 +75,7 @@ impl SymmetricKey {
#[strict_type(lib = LIB_NAME_SSI)]
pub struct Encrypted {
pub keys: SmallOrdMap<SsiPub, Bytes32>,
pub nonce: [u8; 12],
pub data: Confined<Vec<u8>, 0, U64MAX>,
}

Expand All @@ -91,7 +92,7 @@ impl AsciiArmor for Encrypted {

fn to_ascii_armored_data(&self) -> Vec<u8> {
self.to_strict_serialized::<U64MAX>()
.expect("64 bits will not error")
.expect("64 bits will never error")
.into_inner()
}

Expand Down Expand Up @@ -122,9 +123,10 @@ impl Encrypted {
.map_err(|_| EncryptionError::InvalidPubkey(pk))?,
);
}
let msg = encrypt(source, key);
let (nonce, msg) = encrypt(source, key);
Ok(Self {
keys: Confined::try_from(keys).map_err(|_| EncryptionError::TooManyReceivers)?,
nonce: nonce.into(),
data: Confined::from_collection_unsafe(msg),
})
}
Expand All @@ -140,7 +142,7 @@ impl Encrypted {
let key = pair
.decrypt_key(key)
.map_err(|_| DecryptionError::InvalidPubkey(pair.pk))?;
Ok(decrypt(self.data.to_inner(), key))
Ok(decrypt(self.data.as_slice(), self.nonce.into(), key))
}
}

Expand Down Expand Up @@ -179,7 +181,7 @@ impl SsiPair {
}
}

pub fn encrypt(source: Vec<u8>, key: impl AsRef<[u8]>) -> Vec<u8> {
pub fn encrypt(source: Vec<u8>, key: impl AsRef<[u8]>) -> (Nonce<Aes256Gcm>, Vec<u8>) {
let key = Sha256::digest(key.as_ref());
let key = aes_gcm::Key::<Aes256Gcm>::from_slice(key.as_slice());

Expand All @@ -189,23 +191,17 @@ pub fn encrypt(source: Vec<u8>, key: impl AsRef<[u8]>) -> Vec<u8> {
let ciphered_data = cipher
.encrypt(&nonce, source.as_ref())
.expect("failed to encrypt");
// combining nonce and encrypted data together
// for storage purpose
let mut encrypted_data: Vec<u8> = nonce.to_vec();
encrypted_data.extend_from_slice(&ciphered_data);

encrypted_data
(nonce, ciphered_data)
}

pub fn decrypt(encrypted: Vec<u8>, key: impl AsRef<[u8]>) -> Vec<u8> {
pub fn decrypt(encrypted: &[u8], nonce: Nonce<Aes256Gcm>, key: impl AsRef<[u8]>) -> Vec<u8> {
let key = Sha256::digest(key.as_ref());
let key = aes_gcm::Key::<Aes256Gcm>::from_slice(key.as_slice());

let (nonce_arr, ciphered_data) = encrypted.split_at(12);
let nonce = Nonce::from_slice(nonce_arr);
let cipher = Aes256Gcm::new(key);

cipher
.decrypt(nonce, ciphered_data)
.decrypt(&nonce, encrypted)
.expect("failed to decrypt data")
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ pub use public::{
SsiSig, UnknownAlgo, UnknownChain, VerifyError,
};
pub use runtime::{LoadError, SignerError, SsiRuntime, SSI_DIR};
pub use secret::{SecretParseError, SsiPair, SsiSecret};
pub use secret::{EncryptedSecret, RevealError, SecretParseError, SsiPair, SsiSecret};

pub const LIB_NAME_SSI: &str = "SSI";
8 changes: 2 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,19 +252,15 @@ fn exec(command: Command) -> Result<(), CliError> {
.map_err(CliError::Password)?;

eprintln!("Generating new {algo} identity....");
let mut secret = match prefix {
let secret = match prefix {
Some(prefix) => SsiSecret::vanity(&prefix, algo, chain, threads),
None => SsiSecret::new(algo, chain),
};

let ssi = Ssi::new(uids, expiry, &secret);
println!("{ssi}");

if !passwd.is_empty() {
secret.conceal(passwd);
}

runtime.secrets.insert(secret);
runtime.secrets.insert(secret.conceal(passwd));
runtime.identities.insert(ssi);

runtime.store().map_err(CliError::Store)?;
Expand Down
19 changes: 8 additions & 11 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ use std::path::PathBuf;

use baid64::Baid64ParseError;

use crate::{Fingerprint, SecretParseError, Ssi, SsiPair, SsiParseError, SsiQuery, SsiSecret};
use crate::{
EncryptedSecret, Fingerprint, SecretParseError, Ssi, SsiPair, SsiParseError, SsiQuery,
};

#[derive(Debug, Display, Error, From)]
#[display(inner)]
Expand Down Expand Up @@ -57,7 +59,7 @@ pub enum SignerError {
}

pub struct SsiRuntime {
pub secrets: BTreeSet<SsiSecret>,
pub secrets: BTreeSet<EncryptedSecret>,
pub identities: BTreeSet<Ssi>,
}

Expand Down Expand Up @@ -156,12 +158,9 @@ impl SsiRuntime {
.secrets
.iter()
.find_map(|s| {
let mut s = (*s).clone();
if !passwd.is_empty() {
s.reveal(passwd);
}
if s.to_public() == ssi.pk {
Some(s)
let sk = s.reveal(passwd).ok()?;
if sk.to_public() == ssi.pk {
Some(sk)
} else {
None
}
Expand All @@ -170,7 +169,5 @@ impl SsiRuntime {
Ok(SsiPair::new(ssi, sk))
}

pub fn is_signing(&self, fp: Fingerprint) -> bool {
self.secrets.iter().any(|s| s.fingerprint() == fp)
}
pub fn is_signing(&self, fp: Fingerprint) -> bool { self.secrets.iter().any(|s| s.fp == fp) }
}
Loading

0 comments on commit d021439

Please sign in to comment.