summary refs log tree commit diff
path: root/crypto/src/mozilla/SignedPublicKeyAndChallenge.cs
blob: 03b8e90ac270f55ae4d65a4d9d4b61639518d93b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Operators;
using Org.BouncyCastle.Security;

namespace Org.BouncyCastle.Mozilla
{
    public sealed class SignedPublicKeyAndChallenge
    {
        private readonly Asn1.Mozilla.SignedPublicKeyAndChallenge m_spkac;

        public SignedPublicKeyAndChallenge(byte[] encoding)
            : this(Asn1.Mozilla.SignedPublicKeyAndChallenge.GetInstance(encoding))
        {
        }

        public SignedPublicKeyAndChallenge(Asn1.Mozilla.SignedPublicKeyAndChallenge spkac)
        {
            m_spkac = spkac ?? throw new ArgumentNullException(nameof(spkac));
        }

        public AsymmetricKeyParameter GetPublicKey() => PublicKeyFactory.CreateKey(m_spkac.PublicKeyAndChallenge.Spki);

        public bool IsSignatureValid(AsymmetricKeyParameter publicKey) =>
            CheckSignatureValid(new Asn1VerifierFactory(m_spkac.SignatureAlgorithm, publicKey));

        public bool IsSignatureValid(IVerifierFactoryProvider verifierProvider) =>
            CheckSignatureValid(verifierProvider.CreateVerifierFactory(m_spkac.SignatureAlgorithm));

        public Asn1.Mozilla.SignedPublicKeyAndChallenge ToAsn1Structure() => m_spkac;

        public void Verify(AsymmetricKeyParameter publicKey) =>
            CheckSignature(new Asn1VerifierFactory(m_spkac.SignatureAlgorithm, publicKey));

        public void Verify(IVerifierFactoryProvider verifierProvider) =>
            CheckSignature(verifierProvider.CreateVerifierFactory(m_spkac.SignatureAlgorithm));

        private void CheckSignature(IVerifierFactory verifier)
        {
            if (!CheckSignatureValid(verifier))
                throw new InvalidKeyException("Public key presented not for SPKAC signature");
        }

        private bool CheckSignatureValid(IVerifierFactory verifier) =>
            X509.X509Utilities.VerifySignature(verifier, m_spkac.PublicKeyAndChallenge, m_spkac.Signature);
    }
}