feat: add yubikey-rs-demo

This commit is contained in:
2023-03-11 00:32:57 +08:00
parent 9e06880a81
commit 8e03973dda
3 changed files with 1497 additions and 0 deletions

1410
__crypto/yubikey-rs-demo/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,15 @@
[package]
name = "yubikey-rs-demo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
elliptic-curve = { version = "0.13.2", features = ["sec1"] }
hex = "0.4.3"
p256 = { version = "0.13.0", features = ["ecdh"] }
rand = "0.8.5"
rust_util = "0.6.41"
sha2 = "0.10.6"
yubikey = { version = "0.7.0", features = ["untested"] }

View File

@@ -0,0 +1,72 @@
use p256::{ecdh::EphemeralSecret, EncodedPoint, PublicKey};
use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use rand::rngs::OsRng;
use rust_util::{failure_and_exit, information, XResult};
use yubikey::Context;
use yubikey::piv::{AlgorithmId, decrypt_data, RetiredSlotId, SlotId};
// const EPK_BYTES: usize = 33;
#[derive(Debug)]
pub(crate) struct EphemeralKeyBytes(p256::EncodedPoint);
impl EphemeralKeyBytes {
// fn from_bytes(bytes: [u8; EPK_BYTES]) -> Option<Self> {
// let encoded = p256::EncodedPoint::from_bytes(&bytes).ok()?;
// if encoded.is_compressed()
// && p256::PublicKey::from_encoded_point(&encoded)
// .is_some()
// .into()
// {
// Some(EphemeralKeyBytes(encoded))
// } else {
// None
// }
// }
fn from_public_key(epk: &p256::PublicKey) -> Self {
EphemeralKeyBytes(epk.to_encoded_point(true))
}
// pub(crate) fn as_bytes(&self) -> &[u8] {
// self.0.as_bytes()
// }
pub(crate) fn decompress(&self) -> p256::EncodedPoint {
// EphemeralKeyBytes is a valid compressed encoding by construction.
let p = p256::PublicKey::from_encoded_point(&self.0).unwrap();
p.to_encoded_point(false)
}
}
fn main() -> XResult<()> {
let mut readers = Context::open()?;
let reader = readers.iter()?.next().unwrap_or_else(|| failure_and_exit!("No reader!"));
let mut yubikey = reader.open()?;
let esk = EphemeralSecret::random(&mut OsRng);
let epk = esk.public_key();
let epk_bytes = EphemeralKeyBytes::from_public_key(&epk);
let encoded_point = EncodedPoint::from_bytes(&hex::decode(
"04dd3eebd906c9cf00b08ec29f7ed61804d1cc1d1352d9257b628191e08fc3717c4fae3298cd5c4829cec8bf3a946e7db60b7857e1287f6a0bae6b3f2342f007d0"
)?)?;
let public_key = PublicKey::from_encoded_point(&encoded_point).unwrap();
let shared_secret = esk.diffie_hellman(&public_key);
information!("Shared secret: {}", hex::encode(shared_secret.raw_secret_bytes()));
// yubikey.verify_pin(b"123456").expect("Verify pin!");
let decrypted_shared_secret = decrypt_data(
&mut yubikey,
epk_bytes.decompress().as_bytes(),
AlgorithmId::EccP256,
SlotId::Retired(RetiredSlotId::R1),
)?;
information!("Decrypted shared secret: {}", hex::encode(&decrypted_shared_secret.to_vec()));
Ok(())
}