MSDN Community

Encryption in Windows IoT

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.

Getting Started with AES‑GCM (C#)

Sample Code
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;
    }
}

Using TPM for Key Protection (C++)

Sample Code
#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;
}

Best Practices

  1. Prefer AES‑GCM over CBC to get built‑in integrity.
  2. Store long‑term keys in TPM or use DPAPI protect.
  3. Rotate keys regularly and revoke compromised certificates.
  4. Validate certificate chains using CertVerifyCertificateChainPolicy.
  5. Use secure boot and device health attestation for end‑to‑end trust.