Skip to content

Instantly share code, notes, and snippets.

@dwizzzle
Last active May 5, 2023 02:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dwizzzle/a1c4cf4b669053dbeda4a4b24a9aca0f to your computer and use it in GitHub Desktop.
Save dwizzzle/a1c4cf4b669053dbeda4a4b24a9aca0f to your computer and use it in GitHub Desktop.
// KeyProtectionExample.cpp : Creates machine bound keys in Virtualization Based Security Enclave, see: https://docs.rs/winapi/0.3.8/winapi/um/ncrypt/constant.NCRYPT_USE_VIRTUAL_ISOLATION_FLAG.html
//
#include <iostream>
#include <Windows.h>
#include <ncrypt.h>
#pragma comment(lib, "Ncrypt.lib")
int main()
{
SECURITY_STATUS Status = S_OK;
NCRYPT_PROV_HANDLE hProv = NULL;
NCRYPT_KEY_HANDLE hKey = NULL;
const wchar_t* pwszKeyName = L"dwizzzle3KEY";
Status = NCryptOpenStorageProvider(&hProv,
MS_KEY_STORAGE_PROVIDER,
0);
if (FAILED(Status))
{
std::cout << "NCryptOpenStorageProvider Failed\n";
goto Cleanup;
}
Status = NCryptCreatePersistedKey(hProv,
&hKey,
NCRYPT_PBKDF2_ALGORITHM,
pwszKeyName,
0,
NCRYPT_MACHINE_KEY_FLAG | NCRYPT_USE_VIRTUAL_ISOLATION_FLAG);
if (FAILED(Status))
{
std::cout << "NCryptCreatePersistedKey Failed\n";
goto Cleanup;
}
Status = NCryptFinalizeKey(hKey,
NCRYPT_PROTECT_TO_LOCAL_SYSTEM | NCRYPT_SILENT_FLAG);
if (FAILED(Status))
{
std::cout << "NCryptFinalizeKey Failed\n";
goto Cleanup;
}
std::cout << "dwizzzleKEY store in KeyGuard!\n";
Cleanup:
if (hKey != NULL)
{
NCryptFreeObject(hKey);
}
if (hProv != NULL)
{
NCryptFreeObject(hProv);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment