Skip to content

Linux: HMAC instance creation/disposal regressed 29–33% between .NET 11 preview 4 and RC2 #135759

Open

Description

@DeagleGross

Creating and disposing a parameterless HMAC instance is approximately 29-33% slower in .NET 11 RC2 than in preview 4. Creating the instance, setting its key, hashing 64 bytes, and disposing it is approximately 29-41% slower. Managed allocations are unchanged.

This investigation originated from dotnet/aspnetcore#66536 and dotnet/aspnetcore#69789, but the reproduction does not reference or execute ASP.NET Core, Data Protection, antiforgery, AES, or a KDF. It only exercises System.Security.Cryptography.

Create/dispose Preview 4 RC2 Slowdown
HMACSHA256 911 ns 1,216 ns 33.4%
HMACSHA384 1,147 ns 1,482 ns 29.2%
HMACSHA512 1,150 ns 1,486 ns 29.2%

Environment:

  • Linux x64, Ubuntu under WSL2; AMD Ryzen 9 7950X3D.
  • OpenSSL 3.5.8, explicitly selected with a process-local LD_LIBRARY_PATH.
  • Baseline runtime: 11.0.0-preview.4.26215.118, commit 37d611a345239465f81d820e97e3113354a5f058.
  • Comparison runtime: 11.0.0-rc.2.26508.107, commit d147fa546aa7568a8e3f5e34be71388948ce415d.
  • BenchmarkDotNet 0.15.6, Release, InProcessEmitToolchain.

Repro

#:package BenchmarkDotNet@0.15.6
#:property TargetFramework=net10.0
#:property PublishAot=false
#:property Nullable=enable

using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkSwitcher.FromAssembly(typeof(ValidationAlgorithmBenchmarks).Assembly).Run(args);

[MemoryDiagnoser]
public class ValidationAlgorithmBenchmarks
{
    private Func<KeyedHashAlgorithm> _factory = null!;
    private Func<byte[], KeyedHashAlgorithm> _keyedFactory = null!;
    private byte[] _key = null!;
    private readonly byte[] _data = Enumerable.Range(0, 64).Select(i => (byte)i).ToArray();
    private byte[] _destination = null!;

    [Params("SHA256", "SHA512", "SHA384")]
    public string Algorithm { get; set; } = null!;

    [GlobalSetup]
    public void Setup()
    {
        (Func<KeyedHashAlgorithm> Factory, Func<byte[], KeyedHashAlgorithm> KeyedFactory, int DigestLength) configuration = Algorithm switch
        {
            "SHA256" => (() => new HMACSHA256(), key => new HMACSHA256(key), 32),
            "SHA512" => (() => new HMACSHA512(), key => new HMACSHA512(key), 64),
            "SHA384" => (() => new HMACSHA384(), key => new HMACSHA384(key), 48),
            _ => throw new InvalidOperationException($"Unsupported algorithm: {Algorithm}")
        };
        _factory = configuration.Factory;
        _keyedFactory = configuration.KeyedFactory;
        _key = Enumerable.Range(0, configuration.DigestLength).Select(i => (byte)i).ToArray();
        _destination = new byte[configuration.DigestLength];
        OneShot();
        var expected = _destination.ToArray();
        CreateSetKeyHashDispose();
        if (!_destination.AsSpan().SequenceEqual(expected))
        {
            throw new InvalidOperationException("Instance HMAC differs from the one-shot result.");
        }
        using var keyedAlgorithm = _keyedFactory(_key);
        if (!keyedAlgorithm.ComputeHash(_data).AsSpan().SequenceEqual(expected))
        {
            throw new InvalidOperationException("Explicit-key HMAC differs from the one-shot result.");
        }
        Console.WriteLine($"Runtime: {RuntimeInformation.FrameworkDescription}; cryptography: {typeof(HMACSHA256).Assembly.Location}");
        if (OperatingSystem.IsLinux())
        {
            foreach (var library in File.ReadLines("/proc/self/maps").Where(line => line.Contains("libcrypto.so")).Select(line => line[line.IndexOf('/')..]).Distinct())
            {
                Console.WriteLine($"Loaded OpenSSL: {library}");
            }
        }
    }

    [Benchmark]
    public int CreateDispose()
    {
        using var validationAlgorithm = _factory();
        return validationAlgorithm.HashSize;
    }

    [Benchmark]
    public int CreateWithKeyDispose()
    {
        using var validationAlgorithm = _keyedFactory(_key);
        return validationAlgorithm.HashSize;
    }

    [Benchmark]
    public int CreateSetKeyDispose()
    {
        using var validationAlgorithm = _factory();
        validationAlgorithm.Key = _key;
        return validationAlgorithm.HashSize;
    }

    [Benchmark]
    public int CreateSetKeyHashDispose()
    {
        using var validationAlgorithm = _factory();
        validationAlgorithm.Key = _key;
        if (!validationAlgorithm.TryComputeHash(_data, _destination, out var bytesWritten))
        {
            throw new InvalidOperationException("HMAC destination is too small.");
        }
        return bytesWritten;
    }

    [Benchmark]
    public int OneShot()
    {
        return Algorithm switch
        {
            "SHA256" => HMACSHA256.HashData(_key, _data, _destination),
            "SHA512" => HMACSHA512.HashData(_key, _data, _destination),
            "SHA384" => HMACSHA384.HashData(_key, _data, _destination),
            _ => throw new InvalidOperationException($"Unsupported algorithm: {Algorithm}")
        };
    }
}

Activity

  1. added
    tenet-performance
    on Oct 14, 2026
  2. added
    untriaged
    on Oct 14, 2026
  3. DeagleGross commented on Oct 14, 2026

    @DeagleGross
    MemberAuthor
  4. dotnet-policy-service commented on Oct 14, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @bartonjs, @vcsjones, @dotnet/area-system-security
    See info in area-owners.md if you want to be subscribed.

  5. changed the title [-]Linux: HMAC instance creation/disposal regressed 29–33% between .NET 11 preview 4 and RC2 on OpenSSL 3.5.8[/-] [+]Linux: HMAC instance creation/disposal regressed 29–33% between .NET 11 preview 4 and RC2[/+] on Oct 14, 2026
  6. added this to the Future milestone on Oct 14, 2026
  7. removed
    untriaged
    on Oct 14, 2026
  8. vcsjones commented on Oct 14, 2026

    @vcsjones
    Member

    This is largely due to the change to use EVP_MAC_CTX APIs instead of HMAC_CTX APIs. This change was made for FIPS / compliance reasons as the latter APIs are deprecated.

    EVP_MAC_CTX_new and EVP_MAC_init is a bit slower with the new OpenSSL API. This is compounded by using the Key setter property.

    1. new HMACSHA256(key) creates an EVP_MAC_CTX with your key.
    2. Using the setter creates two contexts and immediately throws away the first one.
      HMACSHA256() mac = new(); // creates a new EVP_MAC_CTX with a random key
      mac.Key = key; // Disposes of the EVP_MAC_CTX and creates a new one with the new key.

    So the performance loss is compounded by using the setter approach because the context creation is slower, twice.

    We can try winning back some of this performance in the future.

  9. bartonjs commented on Oct 14, 2026

    @bartonjs
    Member

    @DeagleGross You'd probably gain the perf back by changing your side from set_Key to using the ctors

  10. DeagleGross commented on Oct 15, 2026

    @DeagleGross
    MemberAuthor

    Thanks, that makes sense. I'll try, however I doubt we will backport this to net11. I've already avoided ctor path at all for one-shot HMAC SHA256/SHA512 in dotnet/aspnetcore#69789, but we are still using ctor+setkey in the else path:

    using var validationAlgorithm = CreateValidationAlgorithm();
    validationAlgorithm.Key = validationSubkeyArray ?? validationSubkey.ToArray();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Securitytenet-performance

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions