SpawnDev.SpawnJS.Cryptography
2.2.1
Prefix Reserved
See the version list below for details.
dotnet add package SpawnDev.SpawnJS.Cryptography --version 2.2.1
NuGet\Install-Package SpawnDev.SpawnJS.Cryptography -Version 2.2.1
<PackageReference Include="SpawnDev.SpawnJS.Cryptography" Version="2.2.1" />
<PackageVersion Include="SpawnDev.SpawnJS.Cryptography" Version="2.2.1" />
<PackageReference Include="SpawnDev.SpawnJS.Cryptography" />
paket add SpawnDev.SpawnJS.Cryptography --version 2.2.1
#r "nuget: SpawnDev.SpawnJS.Cryptography, 2.2.1"
#:package SpawnDev.SpawnJS.Cryptography@2.2.1
#addin nuget:?package=SpawnDev.SpawnJS.Cryptography&version=2.2.1
#tool nuget:?package=SpawnDev.SpawnJS.Cryptography&version=2.2.1
SpawnDev.SpawnJS.Cryptography
.Net cryptography library for .Net, .Net Web APIs, and .Net apps. Supports browser and non-browser platforms.
The problem this library solves
Most of Microsoft's System.Security.Cryptography library is marked [UnsupportedOSPlatform("browser")]. To work around this limitation, the browser's built in SubtleCrypto API is used when running in the browser and Microsoft's System.Security.Cryptography libraries are used when running on non-browser platforms.
Features
- AES-GCM - symmetric encryption and decryption
- AES-CBC - symmetric encryption and decryption
- ECDH - shared secret generation (enables asymmetric encryption)
- ECDSA - data signing and verification
- Ed25519 - data signing and verification (EdDSA, RFC 8032)
- SHA - data hashing
- Key persistence - save an Ed25519 key (a device identity) and load it after a restart, non-extractable keys included
PortableCrypto Classes
The classes DotNetCrypto, BrowserWASMCrypto, and BrowserWASMCrypto all inherit from PortableCrypto to provide a shared interface to common cryptography methods regardless of the platform the app is being executed on.
IPortableCrypto Interface
PortableCrypto implements the IPortableCrypto interface. Therefore all implementing classes, DotNetCrypto, BrowserWASMCrypto, and BrowserWASMCrypto, implement it also.
DotNetCrypto
- Uses .Net System.Security.Cryptography on the executing platform
- Browser platform not supported
- Supports non-browser platforms (windows, linux, etc)
- Targets .Net server, .Net Web APIs, any non-browser platform .Net Apps
BrowserWASMCrypto
- Uses SpawnJSRuntime to access the browser's SubtleCrypto API
- Supports only WebAssembly rendering
- Targets the browser via .Net WebAssembly
Getting started
Add the Nuget package
dotnet add package SpawnDev.SpawnJS.Cryptography
.Net Server Project
.Net Server Program.cs
// Crypto for the server. Uses System.Security.Cryptography.
builder.Services.AddSingleton<DotNetCrypto>();
.Net WebAssembly
WebAssembly Program.cs
// Add SpawnJSRuntime service
builder.Services.AddSpawnJSRuntime();
// Crypto for the browser. Uses the browser's SubtleCrypto API via IJSInProcessRuntime.
// Supports only WebAssembly rendering
builder.Services.AddScoped<BrowserWASMCrypto>();
SHA Example
- The below example, taken from the demo project, runs in .Net server side rendering to test SHA hashing using the DotNetCrypto on the server and BrowserWASMCrypto using SpawnJSRuntime to run on the client browser.
var data = new byte[] { 0, 1, 2 };
// - Server
// DotNetCrypto indicated by the appended D, executes on the server using Microsoft.Security.Cryptography
var hashD = await DotNetCrypto.Digest("SHA-512", data);
// - Browser
// BrowserWASMCrypto indicated by the appended B, executes on the browser using Javascript's SubtleCrypto APIs
var hashB = await BrowserWASMCrypto.Digest("SHA-512", data);
// verify the hashes match
if (!hashB.SequenceEqual(hashD))
{
throw new Exception("Hash mismatch");
}
ECDH Example
- The below example, taken from the demo project, runs in .Net server side rendering to test ECDH using the DotNetCrypto on the server and BrowserWASMCrypto using IJSRuntime to run on the client browser.
// - Server
// generate server ECDH key
var ecdhD = await DotNetCrypto.GenerateECDHKey();
// export ecdhD public key for browser to use
var ecdhDPublicKeyBytes = await DotNetCrypto.ExportPublicKeySpki(ecdhD);
// - Browser
// generate browser ECDH key
var ecdhB = await BrowserWASMCrypto.GenerateECDHKey();
// export ecdhB public key for server to use
var ecdhBPublicKeyBytes = await BrowserWASMCrypto.ExportPublicKeySpki(ecdhB);
// - Server
// import the browser's ECDH public key using DotNetCrypto so DotNetCrypto can work with it
var ecdhBPublicKeyD = await DotNetCrypto.ImportECDHKey(ecdhBPublicKeyBytes);
// create shared secret
var sharedSecretD = await DotNetCrypto.DeriveBits(ecdhD, ecdhBPublicKeyD);
// - Browser
// import the server's ECDH public key using BrowserWASMCrypto so BrowserWASMCrypto can work with it
var ecdhDPublicKeyB = await BrowserWASMCrypto.ImportECDHKey(ecdhDPublicKeyBytes);
// create shared secret
var sharedSecretB = await BrowserWASMCrypto.DeriveBits(ecdhB, ecdhDPublicKeyB);
// verify the shared secrets match
if (!sharedSecretB.SequenceEqual(sharedSecretD))
{
throw new Exception("Shared secret mismatch");
}
PortableCrypto Abstract Class
SHA - Data Hashing
Task<byte[]> Digest(string hashName, byte[] data)
- Hash the specified data using the specified hash algorithm
ECDH - Shared secret generation
Task<PortableECDHKey> GenerateECDHKey(string namedCurve = NamedCurve.P521, bool extractable = true)
- Generate a new ECDH crypto key
Task<byte[]> ExportPublicKeySpki(PortableECDHKey key)
- Export the ECDH public key in Spki format
Task<byte[]> ExportPrivateKeyPkcs8(PortableECDHKey key)
- Export the ECDH private key in Pkcs8 format
Task<PortableECDHKey> ImportECDHKey(byte[] publicKeySpki, string namedCurve = NamedCurve.P521, bool extractable = true)
- Import the ECDH public key
Task<PortableECDHKey> ImportECDHKey(byte[] publicKeySpki, byte[] privateKeyPkcs8, string namedCurve = NamedCurve.P521, bool extractable = true)
- Import the ECDH private key
Task<byte[]> DeriveBits(PortableECDHKey localPartyKey, PortableECDHKey otherPartyKey, int bitLength)
- Create a shared secret that is cross-platform compatible
Task<byte[]> DeriveBits(PortableECDHKey localPartyKey, PortableECDHKey otherPartyKey)
- Create a shared secret that is cross-platform compatible
ECDSA - Data Signing
Task<PortableECDSAKey> GenerateECDSAKey(string namedCurve = NamedCurve.P521, bool extractable = true)
- Generate a new ECDSA key
Task<byte[]> ExportPublicKeySpki(PortableECDSAKey key)
- Exports the ECDSA public key in Spki format
Task<byte[]> ExportPrivateKeyPkcs8(PortableECDSAKey key)
- Exports the ECDSA private key in Pkcs8 format
Task<PortableECDSAKey> ImportECDSAKey(byte[] publicKeySpkiData, string namedCurve = NamedCurve.P521, bool extractable = true)
- Import an ECDSA public key
Task<PortableECDSAKey> ImportECDSAKey(byte[] publicKeySpkiData, byte[] privateKeyPkcs8Data, string namedCurve = NamedCurve.P521, bool extractable = true)
- Import an ECDSA public and private key
Task<bool> Verify(PortableECDSAKey key, byte[] data, byte[] signature, string hashName = HashName.SHA512)
- Verify a data signature
Task<byte[]> Sign(PortableECDSAKey key, byte[] data, string hashName = HashName.SHA512)
- Sign data using an ECDSA key
Ed25519 - Data Signing (EdDSA, RFC 8032)
Ed25519 uses a fixed curve (Curve25519) and fixed hash (SHA-512). No curve or hash parameters needed. Browser backends use WebCrypto when available (Chrome 137+, Firefox 129+, Safari 17+), with automatic fallback to a pure managed C# implementation on older browsers.
Task<PortableEd25519Key> GenerateEd25519Key(bool extractable = true)
- Generate a new Ed25519 key pair
Task<byte[]> ExportPublicKeySpki(PortableEd25519Key key)
- Export the Ed25519 public key in SPKI format
Task<byte[]> ExportPrivateKeyPkcs8(PortableEd25519Key key)
- Export the Ed25519 private key in PKCS8 format
Task<PortableEd25519Key> ImportEd25519Key(byte[] publicKeySpkiData, bool extractable = true)
- Import an Ed25519 public key
Task<PortableEd25519Key> ImportEd25519Key(byte[] publicKeySpkiData, byte[] privateKeyPkcs8Data, bool extractable = true)
- Import an Ed25519 public and private key
Task<byte[]> Sign(PortableEd25519Key key, byte[] data)
- Sign data using an Ed25519 key
Task<bool> Verify(PortableEd25519Key key, byte[] data, byte[] signature)
- Verify an Ed25519 signature
bool PortableEd25519Key.HasPrivateKey
- True when the key holds a private key (it can sign); false for a public-only key (for example a peer's key imported from its SPKI), which can only verify. Independent of
Extractable: a non-extractable key has a private key that cannot be exported.
Key persistence - Ed25519
Keep a device's Ed25519 key across restarts without making it extractable.
Task SaveEd25519KeyAsync(PortableEd25519Key key, string name)
- Saves the key in this platform's key store under
name, replacing any key saved under that name. The write is atomic: a reader sees the old key or the new one, never a partial one. - A public-only key (
HasPrivateKeyfalse) can be saved too, for example to pin a peer's public key.
Task<PortableEd25519Key?> LoadEd25519KeyAsync(string name)
- Loads the key saved under
namewith the extractability and the private / public-only state it was saved with. Returnsnullwhen nothing is saved under that name. The caller owns (and disposes) the key.
Task<bool> DeleteKeyAsync(string name)
- Deletes the key saved under
name. Returnstruewhen a key was deleted,falsewhen none was saved under that name.
Names are 1 to 100 characters from A-Z a-z 0-9 . _ -, must not start with ., and are case-sensitive on every platform. Anything else throws ArgumentException.
// first run: create the device key, non-extractable, and keep it
var key = await crypto.LoadEd25519KeyAsync("device");
if (key == null)
{
key = await crypto.GenerateEd25519Key(extractable: false);
await crypto.SaveEd25519KeyAsync(key, "device");
}
// every later run loads the same key; it still cannot be exported
var signature = await crypto.Sign(key, data);
Security model
Browser (BrowserWASMCrypto, WebCrypto Ed25519)
- The key is stored as its
CryptoKeyobjects, by structured clone, in IndexedDB (databaseSpawnDev.SpawnJS.Cryptography.Keys, object storeed25519, keyed by name), in one readwrite transaction with strict durability. It is never exported. - A key created with
extractable: falseis still non-extractable after it is loaded: the browser does not let any script, this library included, read its private key bytes, from memory or from the store. - The store belongs to the origin. Any script running on the same origin can open it, load the stored
CryptoKeyand sign with it; it cannot export it. Keep untrusted script off the origin that holds the key. - At rest the browser keeps IndexedDB in its profile folder on disk; protecting that folder is up to the browser and the OS.
- Clearing the site's data (or a private window closing) deletes the store, and with it the key.
- Where there is no
indexedDB(for example a .NET WebAssembly app running under Node), save, load and delete throwNotSupportedException.
Browser without WebCrypto Ed25519 (the managed fallback)
- The key is a managed
DotNetEd25519Key; there is noCryptoKeyto clone, so the only way to store it is as its SPKI and PKCS#8 bytes, which any script on the origin could read. - So only a key created with
extractable: trueis saved (its owner can export those bytes anyway); a non-extractable managed key is refused withInvalidOperationException(BrowserWASMCrypto.ManagedNonExtractableSaveMessage). A public-only managed key stores its SPKI only. - Loading a managed record imports it through the loading instance (extractable), so it becomes a WebCrypto key in a browser that has WebCrypto Ed25519.
IsWebCryptoEd25519SupportedAsync()tells you which case you are in.
Desktop (DotNetCrypto)
- One file per key:
<KeyStoreDirectory>/ed25519/<hex of the UTF-8 name>.key(hex so names that differ only in case stay distinct on case-insensitive file systems).KeyStoreDirectorydefaults toDotNetCrypto.DefaultKeyStoreDirectory,SpawnDev.SpawnJS.Cryptography/Keysunder the user's local application data folder (Windows%LOCALAPPDATA%, Linux~/.local/share, macOS~/Library/Application Support); set it per instance to keep an app's keys apart. - The file holds the key's SPKI and PKCS#8. It is written to a temporary file in the same folder, flushed to disk and renamed over the old one.
- Windows: the SPKI and PKCS#8 are encrypted with DPAPI (
ProtectedData, CurrentUser scope, the key name as entropy). Only the same Windows user account can decrypt them (DPAPI CurrentUser); a file copied or renamed to another key name does not load; a file that claims no protection is refused. - Linux and macOS: the file is created owner-only (0600) in an owner-only (0700) folder. It is protected by those file permissions alone: root, anyone who can act as that user, and anyone who can read the disk (unless the disk is encrypted) can read the key.
- On every OS the boundary is the user account: any process running as that user can load the key (on Windows DPAPI CurrentUser decrypts for any process of that user), just as it could read the key from the memory of the process that holds it.
- Non-extractable keys ARE saved. Saving into the library's own store is not an export: the private key bytes never reach the caller, and the loaded key is again non-extractable (
ExportPrivateKeyPkcs8throws, as in 2.1.5). That is the same thing a browser does with a non-extractableCryptoKeysaved to IndexedDB. Requiringextractable: trueinstead would make the device key exportable by any code that holds it, which is weaker than storing it. - A corrupt or tampered file, or one whose private key does not match its public key, throws
CryptographicExceptionon load.
AES-GCM - Data Encryption
Task<PortableAESGCMKey> GenerateAESGCMKey(byte[] secret, int iterations = 25000, string hashName = HashName.SHA256, int keySizeBytes = 32, int tagSizeBytes = 16, int nonceSizeBytes = 12, bool extractable = true)
- Generate an AES-GCM key using a secret byte array
Task<PortableAESGCMKey> GenerateAESGCMKey(byte[] secret, byte[] salt, int iterations = 25000, string hashName = HashName.SHA256, int keySizeBytes = 32, int tagSizeBytes = 16, int nonceSizeBytes = 12, bool extractable = true)
- Generate an AES-GCM key using a secret byte array and a salt
Task<byte[]> Encrypt(PortableAESGCMKey key, byte[] plainBytes)
- Encrypt data using an AES-GCM key
Task<byte[]> Decrypt(PortableAESGCMKey key, byte[] encryptedData)
- Decrypt data using an AES-GCM key
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- SpawnDev.SpawnJS (>= 3.0.12)
- System.Security.Cryptography.ProtectedData (>= 10.0.0)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on SpawnDev.SpawnJS.Cryptography:
| Package | Downloads |
|---|---|
|
SpawnDev.WebTorrent
Pure C# BitTorrent/WebTorrent client. 18 BEPs including BEP 52 v2 (SHA-256 + Merkle + hybrid + pure-v2 end-to-end), real WebRTC P2P (browser + desktop via SpawnDev.RTC), DHT with mutable items (BEP 46 — AI agent communication), web seeds, media streaming with seeking via service worker, OPFS storage. Includes webtorrent-sw.js for COI headers + torrent streaming. No JavaScript dependencies. Runs on desktop (.NET + SIPSorcery) and browser (Blazor WASM + SpawnDev.SpawnJS). 468+ shared test methods running on both browser and desktop runtimes + libtorrent 2.0 external-interop fixtures. |
|
|
SpawnDev.RTC
Cross-platform WebRTC for .NET. Browser (Blazor WASM) and desktop from a single API. Data channels, audio, video, media streams, tracks, transceivers, ICE, DTLS, SCTP. Zero-copy JS types in WASM. Serverless signaling via WebTorrent tracker protocol. Powered by SpawnDev.SpawnJS (browser) and SipSorcery (desktop). |
|
|
SpawnDev.Swarm
Membership, identity, authority and transport for a swarm of trusted devices on WebRTC. Browser and desktop .NET. |
GitHub repositories
This package is not used by any popular GitHub repositories.
v2.2.1 - PACKAGING FIX: the 2.2.0 DLL carried assembly and file version 2.1.6.0 (a stale generated AssemblyInfo), so 2.1.6 and 2.2.0 shared one assembly identity with different APIs. 2.2.1 is the same code as 2.2.0, packed from a clean build with assembly version 2.2.1.0. v2.2.0 - NEW: Ed25519 key persistence. SaveEd25519KeyAsync / LoadEd25519KeyAsync / DeleteKeyAsync on IPortableCrypto and PortableCrypto. Browser: the CryptoKeyPair is stored by structured clone in the library's IndexedDB store and never exported, so a non-extractable key reloads non-extractable and still signs (a managed-fallback key is stored only if it was created extractable). Desktop: a per-user file under local app data, DPAPI-protected on Windows, owner-only file permissions elsewhere; atomic writes. NEW: PortableEd25519Key.HasPrivateKey. NOTE: these are new abstract members on PortableCrypto / PortableEd25519Key and new IPortableCrypto members, so a custom subclass or implementation outside this library must add them. v2.1.6 - FIX (browser, security): a malformed Ed25519 key from a remote peer could permanently switch the whole runtime to the managed Ed25519 fallback, so every later key (non-extractable device keys included) was a managed key instead of a WebCrypto key. WebCrypto Ed25519 support is now decided by one explicit probe (IsWebCryptoEd25519SupportedAsync); operation errors propagate and never change it. Malformed SPKI / PKCS8 Ed25519 keys throw the same CryptographicException on desktop and in the browser (Firefox accepted X25519-OID keys as Ed25519). Ed25519Managed.Verify no longer turns an internal error into "invalid signature". v2.1.5 - FIX (desktop, security): a key created or imported with extractable: false can no longer export its secret or private key (AES-CBC raw, PKCS#8 for ECDH / ECDSA / Ed25519); the export throws InvalidOperationException with the same message on desktop and in the browser (the browser threw a JSException; desktop exported). Note: the public DotNet*Key.Key properties still expose the raw .NET objects, which bypass this; they become internal at the next major. v2.1.4 - Depends on SpawnDev.SpawnJS 3.0.12: SpawnJSRuntime.AppBaseUri works under Node (a .NET WebAssembly console app); it was empty there. v2.1.3 - Depends on SpawnDev.SpawnJS 3.0.10 (was 3.0.5): WebAuthn JSON converters, trimmed apps about 630 KB smaller (a narrower trim descriptor) and the 3.0.6 - 3.0.8 fixes (see SpawnDev.SpawnJS's CHANGELOG). An app that got SpawnJS only through this package stayed on 3.0.5. No change of its own. v2.1.2 - Depends on SpawnDev.SpawnJS 3.0.5 (was 3.0.0): its JSTape no longer allocates memory quadratic in the size of a big call. No change of its own; the 29-test browser suite passes.