apub/apub-rustcrypto/src/lib.rs
2021-11-17 22:17:36 -06:00

95 lines
2.1 KiB
Rust

use rsa::{hash::Hash, PaddingScheme, RsaPrivateKey};
use sha2::{Digest, Sha256};
use std::fmt::Debug;
#[derive(Debug, Clone)]
pub struct Sha256Digest {
digest: Sha256,
}
pub struct RsaSigner {
private_key: RsaPrivateKey,
}
pub struct Rustcrypto {
key_id: String,
private_key: RsaPrivateKey,
}
impl Rustcrypto {
pub fn new(key_id: String, private_key: RsaPrivateKey) -> Self {
Self {
key_id,
private_key,
}
}
}
impl apub_digest::Digest for Sha256Digest {
const NAME: &'static str = "SHA-256";
fn digest(mut self, input: &[u8]) -> String {
self.digest.update(input);
let bytes = self.digest.finalize();
base64::encode(&bytes)
}
}
impl apub_signer::Sign for RsaSigner {
type Error = rsa::errors::Error;
fn sign(&self, signing_string: &str) -> Result<String, Self::Error> {
let hashed = Sha256::digest(signing_string.as_bytes());
let bytes = self.private_key.sign(
PaddingScheme::PKCS1v15Sign {
hash: Some(Hash::SHA2_256),
},
&hashed,
)?;
Ok(base64::encode(bytes))
}
}
impl apub_digest::DigestFactory for Rustcrypto {
type Digest = Sha256Digest;
fn digest(&self) -> Self::Digest {
Sha256Digest {
digest: Sha256::new(),
}
}
}
impl apub_signer::SignFactory for Rustcrypto {
type Signer = RsaSigner;
type KeyId = String;
fn key_id(&self) -> Self::KeyId {
self.key_id.clone()
}
fn signer(&self) -> Self::Signer {
RsaSigner {
private_key: self.private_key.clone(),
}
}
}
impl Debug for RsaSigner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RsaSigner")
.field("private_key", &"hidden")
.finish()
}
}
impl Debug for Rustcrypto {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Rustcrypto")
.field("key_id", &self.key_id)
.field("private_key", &"hidden")
.finish()
}
}