Skip to content
This repository has been archived by the owner on Apr 1, 2024. It is now read-only.

Crypto Recipes

Andrew Arnott edited this page Sep 1, 2014 · 15 revisions

Introduction

Most of the API is modeled after the WinRT crypto API. If you're familiar with that, you'll immediately feel at home with PCLCrypto. Instead of reusing the Windows.Security.Cryptography namespace, PCLCrypto functionality is available through the PCLCrypto.WinRTCrypto class.

In some cases, a .NET Framework API is emulated, which is available under the PCLCrypto.NetFxCrypto class.

Create a buffer filled with cryptographically strong random data
// WinRT-like API
uint length = 15;
byte[] cryptoRandomBuffer = WinRTCrypto.CryptographicBuffer.GenerateRandom(length);

// .NET Framework-like API
byte[] cryptoRandomBuffer = new byte[15];
NetFxCrypto.RandomNumberGenerator.GetBytes(cryptoRandomBuffer);
Generate a random number
uint random = WinRTCrypto.CryptographicBuffer.GenerateRandomNumber();
uint randomFrom0To15 = WinRTCrypto.CryptographicBuffer.GenerateRandomNumber() % 16;
Derive a symmetric key from a password

To use crypto APIs with a user-supplied password, you must at least convert the password into a byte buffer. But it's more secure to run it through a key derivation algorithm, using this technique:

string password; // comes in from the user.
byte[] salt; // best initialized to a unique value for each user, and stored with the user record
int iterations = 5000; // higher makes brute force attacks more expensive
int keyLengthInBytes;
byte[] key = NetFxCrypto.DeriveBytes.GetBytes(password, salt, iterations, keyLengthInBytes);

// A similar technique is possible using WinRT-emulated API via the `WinRTCrypto.KeyDerivationAlgorithmProvider`.
Clone this wiki locally