Search code examples
c#cryptographyblazor-webassemblyx509certificate2

Sign message with certificates in Blazor WASM


I am using Blazor WASM with .NET6. Given a X509Certificate2 certificate I want to sign a message.

Looking at code I from another (desktop) project I have

private static string GenerateSecret(string timestamp, string deviceName, string challenge, X509Certificate2 certificate)
{
    string message = timestamp + deviceName + challenge;
    byte[] originalData = Encoding.UTF8.GetBytes(message);

    var hashAlgorithm = HashAlgorithmName.SHA512;
    var rsaSignaturePadding = RSASignaturePadding.Pkcs1;

    var hash = certificate.GetRSAPrivateKey().SignData(originalData, hashAlgorithm, rsaSignaturePadding);
    return Convert.ToBase64String(hash);
}

But Visual Studio tells me both RSASignaturePadding.Pkcs1 and certificate.GetRSAPrivateKey().SignData() are not supported for my platform:

warning CA1416: This call site is reachable on all platforms. 'RSA.SignData(byte[], HashAlgorithmName, RSASignaturePadding)' is unsupported on: 'browser'.

Now my question is: Is it possible to sign a message in Blazor WASM or is this not possible at all in this context? What alternatives would I have for achieving this?


Solution

  • Given a X509Certificate2 certificate ... wasm

    In addition to RSA not being supported, X509Certificate2 is also not supported on wasm. Either we don't have warnings enabled for X509Certificate2 in .NET 6, or you haven't included a constructor call in your code yet, but all of the constructors are marked as [UnsupportedOSPlatform("browser")] in .NET 7.

    In .NET 6 the only cryptographic concept with support in wasm is hashing. In .NET 7 it will be hashing and HMAC. There's no encryption or signing support, and nothing with certificates.

    For "just RSA" you can look into doing interop directly with the Subtle Crypto intrinsic API. To my knowledge there's not a standard wasm notion of certificates.