From ceaebe902166d062635c444e2649c1a5849deaae Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Sat, 24 Jul 2021 16:38:43 +0700 Subject: Calculate HMAC without extracting TlsSecret --- crypto/src/tls/TlsUtilities.cs | 8 ++------ crypto/src/tls/crypto/TlsSecret.cs | 8 ++++++++ crypto/src/tls/crypto/impl/AbstractTlsSecret.cs | 13 +++++++++++++ 3 files changed, 23 insertions(+), 6 deletions(-) (limited to 'crypto/src') diff --git a/crypto/src/tls/TlsUtilities.cs b/crypto/src/tls/TlsUtilities.cs index 4cec13bae..52b554801 100644 --- a/crypto/src/tls/TlsUtilities.cs +++ b/crypto/src/tls/TlsUtilities.cs @@ -1491,14 +1491,10 @@ namespace Org.BouncyCastle.Tls : securityParameters.BaseKeyClient; TlsSecret finishedKey = DeriveSecret(securityParameters, baseKey, "finished", EmptyBytes); + int cryptoHashAlgorithm = TlsCryptoUtilities.GetHash(securityParameters.PrfHashAlgorithm); byte[] transcriptHash = GetCurrentPrfHash(handshakeHash); - TlsCrypto crypto = context.Crypto; - byte[] hmacKey = crypto.AdoptSecret(finishedKey).Extract(); - TlsHmac hmac = crypto.CreateHmacForHash(TlsCryptoUtilities.GetHash(securityParameters.PrfHashAlgorithm)); - hmac.SetKey(hmacKey, 0, hmacKey.Length); - hmac.Update(transcriptHash, 0, transcriptHash.Length); - return hmac.CalculateMac(); + return finishedKey.CalculateHmac(cryptoHashAlgorithm, transcriptHash, 0, transcriptHash.Length); } if (negotiatedVersion.IsSsl) diff --git a/crypto/src/tls/crypto/TlsSecret.cs b/crypto/src/tls/crypto/TlsSecret.cs index 0499d37c3..8c39c56f7 100644 --- a/crypto/src/tls/crypto/TlsSecret.cs +++ b/crypto/src/tls/crypto/TlsSecret.cs @@ -7,6 +7,14 @@ namespace Org.BouncyCastle.Tls.Crypto /// public interface TlsSecret { + /// Calculate an HMAC with this secret's data as the key. + /// the hash algorithm to instantiate HMAC with. See + /// for values. + /// array containing the input data. + /// offset into the input array the input starts at. + /// the length of the input data. + byte[] CalculateHmac(int cryptoHashAlgorithm, byte[] buf, int off, int len); + /// Return a new secret based on applying a PRF to this one. /// PRF algorithm to use. /// the label details. diff --git a/crypto/src/tls/crypto/impl/AbstractTlsSecret.cs b/crypto/src/tls/crypto/impl/AbstractTlsSecret.cs index e8298193f..1ea25344d 100644 --- a/crypto/src/tls/crypto/impl/AbstractTlsSecret.cs +++ b/crypto/src/tls/crypto/impl/AbstractTlsSecret.cs @@ -26,6 +26,19 @@ namespace Org.BouncyCastle.Tls.Crypto.Impl protected abstract AbstractTlsCrypto Crypto { get; } + public virtual byte[] CalculateHmac(int cryptoHashAlgorithm, byte[] buf, int off, int len) + { + lock (this) + { + CheckAlive(); + + TlsHmac hmac = Crypto.CreateHmacForHash(cryptoHashAlgorithm); + hmac.SetKey(m_data, 0, m_data.Length); + hmac.Update(buf, off, len); + return hmac.CalculateMac(); + } + } + public abstract TlsSecret DeriveUsingPrf(int prfAlgorithm, string label, byte[] seed, int length); public virtual void Destroy() -- cgit 1.5.1