Cryptography

Algorithm, Key and Input

GPAL.Cryptography is the entry point and every call chains off it. WithAlgorithm picks the algorithm, and each operation takes the ones that apply to it. Encrypt and Decrypt take AES or RSA. Hash takes SHA256 or MD5. Sign and Verify take SHA256withRSA or ECDSA. GenerateKey takes PBKDF2 to derive from a password, or AES to make one. Naming an algorithm an operation does not do publishes a warning and the operation runs with its own default. WithKey supplies the key bytes and WithIV the initialization vector. For AES those are raw bytes; for RSA and ECDSA the key is its encoding, PKCS#8 for a private key and X.509 SubjectPublicKeyInfo for a public one, which is exactly what GenerateRsaKeyPair and GenerateEcdsaKeyPair hand back. WithMode picks the block cipher mode, GCM, CBC or ECB, and WithPadding the padding scheme, PKCS7, NoPadding or ISO10126. Both are AES settings and are ignored by RSA. WithSalt and WithIterationCount are the two PBKDF2 takes: the salt to derive against and how many rounds to run, 10000 without one. WithSalt also works on Hash, where it is mixed in ahead of the input. WithInputData sets the bytes the operation acts on, and WithSignature the signature Verify checks.

NOTE

A chain that says nothing about algorithm, mode or padding is AES in GCM with PKCS7, which are the field defaults. Name an algorithm when you want one of the others.

Examples

GPAL Fluent: High-level fluent C# API

//GenerateKey and GenerateIV hand back the bytes through out parameters and leave them set on the chain, so the next call encrypts with what was just generated. The key pair helpers are static and return the private key first. Both halves are already in the encoding the operations expect, so they go straight into WithKey: the private one to sign or decrypt, the public one to verify or encrypt.

byte[] key;

byte[] iv;


// symmetric: generate the key and iv, then keep them to decrypt with later

GPAL.Cryptography

.WithAlgorithm(CryptoAlgorithm.AES)

.WithMode(CryptoMode.GCM)

.GenerateKey(out key)

.GenerateIV(out iv);


// asymmetric: a key pair comes from the helper, already encoded the way WithKey wants it

(byte[] rsaPrivate, byte[] rsaPublic) = Cryptography.GenerateRsaKeyPair();

(byte[] ecPrivate, byte[] ecPublic) = Cryptography.GenerateEcdsaKeyPair();

💬 Ask GPAL