summary refs log tree commit diff
path: root/crypto/src/openpgp/EdDsaSigner.cs
blob: 040fac4e790e34f53cda8bf418037cb94e53136e (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Bcpg.OpenPgp
{
    internal sealed class EdDsaSigner
        : ISigner
    {
        private readonly ISigner m_signer;
        private readonly IDigest m_digest;

        internal EdDsaSigner(ISigner signer, IDigest digest)
        {
            m_signer = signer;
            m_digest = digest;
        }

        public string AlgorithmName => m_signer.AlgorithmName;

        public void Init(bool forSigning, ICipherParameters cipherParameters)
        {
            m_signer.Init(forSigning, cipherParameters);
            m_digest.Reset();
        }

        public void Update(byte b)
        {
            m_digest.Update(b);
        }

        public void BlockUpdate(byte[] input, int inOff, int inLen)
        {
            m_digest.BlockUpdate(input, inOff, inLen);
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public void BlockUpdate(ReadOnlySpan<byte> input)
        {
            m_digest.BlockUpdate(input);
        }
#endif

        public int GetMaxSignatureSize() => m_signer.GetMaxSignatureSize();

        public byte[] GenerateSignature()
        {
            FinalizeDigest();
            return m_signer.GenerateSignature();
        }

        public bool VerifySignature(byte[] signature)
        {
            FinalizeDigest();
            return m_signer.VerifySignature(signature);
        }

        public void Reset()
        {
            m_signer.Reset();
            m_digest.Reset();
        }

        private void FinalizeDigest()
        {
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            int digestSize = m_digest.GetDigestSize();
            Span<byte> hash = digestSize <= 128
                ? stackalloc byte[digestSize]
                : new byte[digestSize];
            m_digest.DoFinal(hash);
            m_signer.BlockUpdate(hash);
#else
            byte[] hash = DigestUtilities.DoFinal(m_digest);
            m_signer.BlockUpdate(hash, 0, hash.Length);
#endif
        }
    }
}