Cryptographic API selection
Cryptographic API selection
Cryptographic primitives serve distinct goals. A digest detects a change when compared with a trusted expected digest; a message authentication code proves integrity to parties sharing a secret; a digital signature can be verified using a public key; authenticated encryption protects confidentiality and integrity. Password verification uses specialized salted password hashing rather than a fast general digest.
Select a maintained API and protocol rather than inventing cryptography. SHA256.HashData creates a fixed-size digest; it cannot establish authorship without a trusted digest channel. HMACSHA256.HashData combines a secret key and message to create a tag; compare authentication tags using CryptographicOperations.FixedTimeEquals after enforcing the expected length. A signature uses a private signing key and a public verification key; it does not conceal the signed data. AES-GCM is authenticated encryption: a nonce must not repeat with the same key; the authentication tag must be checked before using plaintext. Use secure random generation, a reviewed nonce/key lifecycle and standard formats. Never use a fixed nonce/key from a tutorial as a production secret. RandomNumberGenerator supplies cryptographic randomness, unlike System.Random for general simulation. ASP.NET Core Data Protection is a higher-level purpose-bound protection system with key management and rotation, appropriate for framework tickets and suitable application payloads; it is not a universal long-term encryption or interoperability protocol. Persist and protect keys across authorized replicas and rotations as needed, or sessions can become unreadable. TLS protects transport; it does not replace storage encryption or access controls. Verify supported cryptographic platforms and organizational requirements. The examples use synthetic data, transient keys, and no printed secrets.
Baseline: .NET 10 / C# 14 with Microsoft.AspNetCore.App shared framework. All snippets are independent console fixtures, not ByteMind runner code. In an approved isolated environment with a reviewed installed SDK and targeting packs, use dotnet build and dotnet run --no-build in the fixture directory; restore only from approved sources if required. No external service, real user data, account or credential is needed. Expected results are reasoned, not executed; cryptographic random data is not printed.
Compare a digest against a public test vector
Compute SHA-256 for the known ASCII text abc. The expected digest is public and independently checkable.
using System.Security.Cryptography;using System.Text;var digest = SHA256.HashData(Encoding.UTF8.GetBytes("abc"));var expected = Convert.FromHexString("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD");Console.WriteLine(digest.Length);Console.WriteLine(CryptographicOperations.FixedTimeEquals(digest, expected));Expected output (not executed):
32TrueSHA-256 yields 32 bytes. This confirms a public test vector, not message authorship or password safety.
Verify an authenticated message tag
Create a fresh key for this one process. Compare tags for two distinct synthetic messages without revealing the key or tags.
using System.Security.Cryptography;using System.Text;byte[] key = RandomNumberGenerator.GetBytes(32);try { byte[] tag = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes("catalog:7")); byte[] correct = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes("catalog:7")); byte[] different = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes("catalog:8")); Console.WriteLine(CryptographicOperations.FixedTimeEquals(tag, correct)); Console.WriteLine(CryptographicOperations.FixedTimeEquals(tag, different));} finally { CryptographicOperations.ZeroMemory(key); }Expected output (not executed):
TrueFalseIdentical key and message give the same tag. A different message is expected to yield a different tag (collision probability is negligible). This is not a complete replay-resistant protocol.
Authenticate and decrypt a short synthetic message
Use one fresh key and one random nonce for one encryption operation. This local demonstration requires AesGcm.IsSupported.
using System.Security.Cryptography;using System.Text;if (!AesGcm.IsSupported) throw new PlatformNotSupportedException("AES-GCM required for this fixture");byte[] key = RandomNumberGenerator.GetBytes(32);try { byte[] nonce = RandomNumberGenerator.GetBytes(12); byte[] message = Encoding.UTF8.GetBytes("sample"); byte[] ciphertext = new byte[message.Length]; byte[] tag = new byte[16]; byte[] plaintext = new byte[message.Length]; using var aes = new AesGcm(key, tag.Length); aes.Encrypt(nonce, message, ciphertext, tag); aes.Decrypt(nonce, ciphertext, tag, plaintext); Console.WriteLine(Encoding.UTF8.GetString(plaintext)); tag[0] ^= 1; try { aes.Decrypt(nonce, ciphertext, tag, plaintext); Console.WriteLine("unexpected success"); } catch (AuthenticationTagMismatchException) { Console.WriteLine("rejected"); }} finally { CryptographicOperations.ZeroMemory(key); }Expected output (not executed):
samplerejectedThe valid tag allows recovery; the changed tag causes authentication failure. Never process plaintext from a failed decryption. This is one-shot learning code, not a storage format or key management system.
Apply the concept
Choose a primitive for four fictional needs: a downloaded public release checksum, two services authenticating a message with a shared key, a public release signature, and confidential stored records. State how keys or expected digests are trusted.
Use the manual practice and knowledge check to reason about the boundary. Do not deploy these fixtures as production security controls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cryptographic API selection — knowledge check
Apply the lesson concepts to the following scenarios.
What does SHA-256 alone provide?
Which primitive authenticates a message with a shared key?
What must not repeat for AES-GCM with the same key?
What should happen after an authentication tag mismatch?
Why use a password hasher instead of a single SHA-256 digest?