0

I have written the following C# code:

static void createSHA256KeyFile(string publicKeyPath, string privateKeyPath)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {
                    Console.WriteLine(rsa.KeySize);
                    rsa.PersistKeyInCsp = false;
                    byte[] publicKeyBytes = rsa.ExportCspBlob(false);
                    byte[] privateKeyBytes = rsa.ExportCspBlob(true);
                    File.WriteAllBytes(publicKeyPath, publicKeyBytes);
                    File.WriteAllBytes(privateKeyPath, privateKeyBytes);
                    Console.WriteLine("Base 64 Encodings");
                    Console.WriteLine($"\nPublic Key:\n{Convert.ToBase64String(publicKeyBytes)}");
                    Console.WriteLine($"\nPrivate Key:\n{Convert.ToBase64String(privateKeyBytes)}");
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

The above function generates a key pair, saves them on the disk drive, and then prints a base64 encoding of the keys on the console.

I have been able to use the key-pair to generate digital signatures.

Suppose that I have saved a keypair generated with the above code and I want to use it with the SubtleCrypto module in my browser. (https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto)

Specifically, I want to get the private key in an variable that I can pass to sign(algorithm, key, data).

How can I use either a byte array from the file or a string of the base64 encoding to get the value to pass as the key parameter?

Vivian River
  • 31,198
  • 62
  • 198
  • 313
  • 1
    You have to convert the proprietary MS key format (`PRIVATEKEYBLOB`) to a format supported by WebCrypto for private keys (PKCS#8 or JWK). An alternative to conversion is direct export in a suitable format. – Topaco Oct 08 '22 at 12:52
  • Yep, I would choose the latter and convert these keys. So unfortunate that Microsoft uses their own format for no reason at all. We've got perfectly good standards for this. – Maarten Bodewes Oct 08 '22 at 13:08

0 Answers0