identity_ecdsa_verifier/
secp256k1.rsuse std::ops::Deref;
use identity_verification::jwk::JwkParamsEc;
use identity_verification::jws::SignatureVerificationError;
use identity_verification::jws::SignatureVerificationErrorKind;
use identity_verification::jwu::{self};
use k256::ecdsa::Signature;
use k256::ecdsa::VerifyingKey;
use k256::elliptic_curve::sec1::FromEncodedPoint;
use k256::elliptic_curve::subtle::CtOption;
use k256::EncodedPoint;
use k256::PublicKey;
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct Secp256K1Verifier {}
impl Secp256K1Verifier {
pub fn verify(
input: &identity_verification::jws::VerificationInput,
public_key: &identity_verification::jwk::Jwk,
) -> Result<(), SignatureVerificationError> {
let params: &JwkParamsEc = public_key
.try_ec_params()
.map_err(|_| SignatureVerificationErrorKind::UnsupportedKeyType)?;
let public_key_bytes = jwu::decode_b64(¶ms.x)
.map_err(|err| {
SignatureVerificationError::new(SignatureVerificationErrorKind::KeyDecodingFailure).with_source(err)
})?
.into_iter()
.chain(jwu::decode_b64(¶ms.y).map_err(|err| {
SignatureVerificationError::new(SignatureVerificationErrorKind::KeyDecodingFailure).with_source(err)
})?)
.collect();
let encoded_point: EncodedPoint = EncodedPoint::from_untagged_bytes(&public_key_bytes);
let public_key: PublicKey = {
let opt_public_key: CtOption<PublicKey> = PublicKey::from_encoded_point(&encoded_point);
if opt_public_key.is_none().into() {
return Err(SignatureVerificationError::new(
SignatureVerificationErrorKind::KeyDecodingFailure,
));
} else {
opt_public_key.unwrap()
}
};
let verifying_key: VerifyingKey = VerifyingKey::from(public_key);
let mut signature: Signature = Signature::try_from(input.decoded_signature.deref()).map_err(|err| {
SignatureVerificationError::new(SignatureVerificationErrorKind::InvalidSignature).with_source(err)
})?;
if let Some(normalized) = signature.normalize_s() {
signature = normalized;
}
match signature::Verifier::verify(&verifying_key, &input.signing_input, &signature) {
Ok(()) => Ok(()),
Err(err) => {
Err(SignatureVerificationError::new(SignatureVerificationErrorKind::InvalidSignature).with_source(err))
}
}
}
}