Secure data at rest and in transit is essential for IoT solutions. Windows IoT offers a rich set of cryptographic APIs that integrate with hardware security modules such as TPM 2.0, and support industry‑standard algorithms.
using System;
using System.Security.Cryptography;
public static class AesGcmExample
{
public static byte[] Encrypt(byte[] plaintext, byte[] key, out byte[] nonce, out byte[] tag)
{
using var aes = new AesGcm(key);
nonce = RandomNumberGenerator.GetBytes(12);
tag = new byte[16];
byte[] ciphertext = new byte[plaintext.Length];
aes.Encrypt(nonce, plaintext, ciphertext, tag);
return ciphertext;
}
public static byte[] Decrypt(byte[] ciphertext, byte[] key, byte[] nonce, byte[] tag)
{
using var aes = new AesGcm(key);
byte[] plaintext = new byte[ciphertext.Length];
aes.Decrypt(nonce, ciphertext, tag, plaintext);
return plaintext;
}
}
#include <windows.h>
#include <tbs.h>
#include <wincrypt.h>
BOOL CreateAndStoreKey()
{
BCRYPT_ALG_HANDLE hAlg = nullptr;
BCRYPT_KEY_HANDLE hKey = nullptr;
NTSTATUS status;
status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_RSA_ALGORITHM, nullptr, 0);
if (!BCRYPT_SUCCESS(status)) return FALSE;
status = BCryptGenerateKeyPair(hAlg, &hKey, 2048, 0);
if (!BCRYPT_SUCCESS(status)) return FALSE;
// Persist the key in TPM (key storage provider)
status = BCryptFinalizeKeyPair(hKey, 0);
if (!BCRYPT_SUCCESS(status)) return FALSE;
// Clean up
BCryptDestroyKey(hKey);
BCryptCloseAlgorithmProvider(hAlg, 0);
return TRUE;
}