The following gists implement HMAC-based Extract-and-Expand Key Derivation Function (HKDF) in C# for Universal Windows Platform (UWP). The class should be portable to Windows 10, Windows 10 Mobile, and WinRT.
The implementation details are outlined in RFC 5869.
The HKDF class can be initialized with one of MacAlgorithmNames
outlined in https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.core.macalgorithmnames.aspx as the first arguement
string algorithm = MacAlgorithmNames.HmacSha256;
var hkdf = new HKDF(algorithm);
An IBuffer
containing your key materials that can be used for either SymmetricKeyProvider
or MacAlgorithmProvider
can then be derived as follows:
// The encoding to use
BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
// Initial key materials
IBuffer ikm = CryptographicBuffer.ConvertStringToBinary("ikm", encoding);
// The public info
IBuffer info = CryptographicBuffer.ConvertStringToBinary("public_info", encoding);
// The output size
uint keyByteSize = 16; // MacAlgorithmNames.HmacSha256 => 16
// keyMaterials contains the raw data
IBuffer keyMaterials = hkdf.deriveKey(ikm, info, keyByteSize);
The raw key materials can be viewed by outputting the IBuffer
System.Diagnostics.Debug.WriteLine(
CryptographicBuffer.EncodeToBase64String(keyMaterials);
);
To use for AES-CBC decryption, using with SymmetricKeyProvider
as follows:
// AES-CBC
SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC");
CryptographicKey key = provider.CreateSymmetricKey(keyMaterials);
IBuffer decryptedBuffer = CryptographicEngine.Decrypt(key, message, iv);
string data = CryptographicBuffer.ConvertBinaryToString(encoding, decryptedBuffer);