Skip to content

Commit

Permalink
implement: signature params builder and object from string
Browse files Browse the repository at this point in the history
  • Loading branch information
junkurihara committed Jan 11, 2024
1 parent 9ab5b31 commit b2a95ce
Show file tree
Hide file tree
Showing 8 changed files with 631 additions and 36 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ publish = false
# serde_json = "1.0.108"
anyhow = { version = "1.0.79" }
tracing = { version = "0.1.40" }
derive_builder = { version = "0.12.0" }
rustc-hash = { version = "1.1.0" }
rand = { version = "0.8.5" }

# crypto
pkcs8 = { version = "0.10.2", default-features = false, features = ["pem"] }
Expand Down
30 changes: 24 additions & 6 deletions src/crypto/asymmetric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl SecretKey {
}
}

impl super::Signer for SecretKey {
impl super::SigningKey for SecretKey {
/// Sign data
fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
match &self {
Expand All @@ -126,19 +126,28 @@ impl super::Signer for SecretKey {
}

fn key_id(&self) -> String {
use super::Verifier;
use super::VerifyingKey;
self.public_key().key_id()
}

fn alg(&self) -> String {
use super::VerifyingKey;
self.public_key().alg()
}
}

impl super::Verifier for SecretKey {
impl super::VerifyingKey for SecretKey {
fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
self.public_key().verify(data, signature)
}

fn key_id(&self) -> String {
self.public_key().key_id()
}

fn alg(&self) -> String {
self.public_key().alg()
}
}

/* -------------------------------- */
Expand Down Expand Up @@ -201,7 +210,7 @@ impl PublicKey {
}
}

impl super::Verifier for PublicKey {
impl super::VerifyingKey for PublicKey {
/// Verify signature
fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
match self {
Expand Down Expand Up @@ -246,6 +255,15 @@ impl super::Verifier for PublicKey {
let hash = hasher.finalize();
general_purpose::URL_SAFE_NO_PAD.encode(hash)
}

/// Get the algorithm name
fn alg(&self) -> String {
match self {
Self::EcdsaP256Sha256(_) => "ecdsa-p256-sha256".to_string(),
Self::EcdsaP384Sha384(_) => "ecdsa-p384-sha384".to_string(),
Self::Ed25519(_) => "ed25519".to_string(),
}
}
}

#[cfg(test)]
Expand Down Expand Up @@ -307,7 +325,7 @@ MCowBQYDK2VwAyEA1ixMQcxO46PLlgQfYS46ivFd+n0CcDHSKUnuhm3i1O0=

#[test]
fn test_sign_verify() {
use super::super::{Signer, Verifier};
use super::super::{SigningKey, VerifyingKey};
let sk = SecretKey::from_pem(P256_SECERT_KEY).unwrap();
let pk = PublicKey::from_pem(P256_PUBLIC_KEY).unwrap();
let data = b"hello world";
Expand All @@ -332,7 +350,7 @@ MCowBQYDK2VwAyEA1ixMQcxO46PLlgQfYS46ivFd+n0CcDHSKUnuhm3i1O0=

#[test]
fn test_kid() -> Result<()> {
use super::super::Verifier;
use super::super::VerifyingKey;
let sk = SecretKey::from_pem(P256_SECERT_KEY)?;
let pk = PublicKey::from_pem(P256_PUBLIC_KEY)?;
assert_eq!(sk.public_key().key_id(), pk.key_id());
Expand Down
10 changes: 6 additions & 4 deletions src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ mod symmetric;
pub use asymmetric::{PublicKey, SecretKey};
pub use symmetric::SharedKey;

/// Signer trait
pub trait Signer {
/// SigningKey trait
pub trait SigningKey {
fn sign(&self, data: &[u8]) -> anyhow::Result<Vec<u8>>;
fn key_id(&self) -> String;
fn alg(&self) -> String;
}

/// Verifier trait
pub trait Verifier {
/// VerifyingKey trait
pub trait VerifyingKey {
fn verify(&self, data: &[u8], signature: &[u8]) -> anyhow::Result<()>;
fn key_id(&self) -> String;
fn alg(&self) -> String;
}
25 changes: 18 additions & 7 deletions src/crypto/symmetric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub enum SharedKey {
HmacSha256(Vec<u8>),
}

impl super::Signer for SharedKey {
impl super::SigningKey for SharedKey {
/// Sign the data
fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
match self {
Expand All @@ -25,14 +25,19 @@ impl super::Signer for SharedKey {
}
/// Get the key id
fn key_id(&self) -> String {
use super::Verifier;
<Self as Verifier>::key_id(self)
use super::VerifyingKey;
<Self as VerifyingKey>::key_id(self)
}
/// Get the algorithm name
fn alg(&self) -> String {
use super::VerifyingKey;
<Self as VerifyingKey>::alg(self)
}
}
impl super::Verifier for SharedKey {
impl super::VerifyingKey for SharedKey {
/// Verify the mac
fn verify(&self, data: &[u8], expected_mac: &[u8]) -> Result<()> {
use super::Signer;
use super::SigningKey;
let calcurated_mac = self.sign(data)?;
if calcurated_mac == expected_mac {
Ok(())
Expand All @@ -47,12 +52,18 @@ impl super::Verifier for SharedKey {
match self {
SharedKey::HmacSha256(key) => {
let mut hasher = <Sha256 as Digest>::new();
hasher.update(&key);
hasher.update(key);
let hash = hasher.finalize();
general_purpose::URL_SAFE_NO_PAD.encode(hash)
}
}
}
/// Get the algorithm name
fn alg(&self) -> String {
match self {
SharedKey::HmacSha256(_) => "hmac-sha256".to_string(),
}
}
}

#[cfg(test)]
Expand All @@ -61,7 +72,7 @@ mod tests {

#[test]
fn symmetric_key_works() {
use super::super::{Signer, Verifier};
use super::super::{SigningKey, VerifyingKey};
let inner = b"01234567890123456789012345678901";
let key = SharedKey::HmacSha256(inner.to_vec());
let data = b"hello";
Expand Down
28 changes: 19 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
mod crypto;
use crypto::{PublicKey, SecretKey, Signer, Verifier};
pub fn test() {
println!("Hello, world!");
}
mod signature_params;
mod trace;

use crate::{
crypto::{PublicKey, SecretKey, SigningKey, VerifyingKey},
signature_params::{HttpSignatureParams, HttpSignatureParamsBuildConfig},
};

#[cfg(test)]
mod tests {
Expand Down Expand Up @@ -33,10 +36,10 @@ Signature: sig-b26=:wqcAqbmYJ2ji2glfAMaRy4gruYYnx2nEFN2HN6jrnDnQCK1\
u02Gb04v9EDgwUPiu4A0w6vuQv5lIp5WPpBKRCw==:"##;

#[test]
fn test() {
println!("{}", SIGNATURE_BASE);
println!("{}", SIGNATURE_VALUE);
println!("{}", SIGNATURE_RESULT);
fn test_using_test_vector() {
// println!("{}", SIGNATURE_BASE);
// println!("{}", SIGNATURE_VALUE);
// println!("{}", SIGNATURE_RESULT);

let sk = SecretKey::from_pem(EDDSA_SECRET_KEY).unwrap();
let pk = PublicKey::from_pem(EDDSA_PUBLIC_KEY).unwrap();
Expand All @@ -49,9 +52,16 @@ Signature: sig-b26=:wqcAqbmYJ2ji2glfAMaRy4gruYYnx2nEFN2HN6jrnDnQCK1\

let signature = sk.sign(SIGNATURE_BASE.as_bytes()).unwrap();
let signature_value = general_purpose::STANDARD.encode(signature);
println!("{}", signature_value);
// println!("{}", signature_value);
let signature_bytes = general_purpose::STANDARD.decode(signature_value).unwrap();
let verification_result = pk.verify(SIGNATURE_BASE.as_bytes(), &signature_bytes);
assert!(verification_result.is_ok());
}

#[test]
fn test_http_signature_params() {
let signature_params_str = r##"("date" "@method" "@path" "@authority" "content-type" "content-length");created=1618884473;keyid="test-key-ed25519""##;
let signature_params = HttpSignatureParams::try_from(signature_params_str).unwrap();
assert_eq!(signature_params.to_string(), signature_params_str);
}
}
Loading

0 comments on commit b2a95ce

Please sign in to comment.