Created
May 17, 2017 10:01
-
-
Save aguinet/6db17246be3f55205f44ae80c340f2fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _CRT_SECURE_NO_WARNINGS | |
#include "targetver.h" | |
#include <stdio.h> | |
#include <tchar.h> | |
#include <Windows.h> | |
#include <Wincrypt.h> | |
#include <string.h> | |
#define USER_RSA_KEY_LEN 2048 // 2048-bit | |
void dump_hex(const char* Name, BYTE const* Data, size_t const Len) | |
{ | |
printf("%s:", Name); | |
for (size_t i = 0; i < Len; ++i) { | |
if ((i % 16 == 0)) { | |
printf("\n"); | |
} | |
printf("%02X ", Data[i]); | |
} | |
printf("\n====\n"); | |
} | |
int main() | |
{ | |
HCRYPTPROV prov; | |
HCRYPTKEY keyUser; | |
if (!CryptAcquireContext(&prov, | |
NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, | |
CRYPT_VERIFYCONTEXT)) { | |
puts("error CryptAcquireContext"); | |
return 1; | |
} | |
if (!CryptGenKey(prov, AT_KEYEXCHANGE, | |
(USER_RSA_KEY_LEN << 16) | CRYPT_EXPORTABLE, &keyUser)) { | |
puts("error CryptGenKey"); | |
return 1; | |
} | |
BYTE keyData[4096]; | |
memset(keyData, 0xFE, sizeof(keyData)); | |
DWORD len = 4096; | |
if (!CryptExportKey(keyUser, 0, PRIVATEKEYBLOB, 0, &keyData[0], &len)) { | |
printf("error export!\n"); | |
return 1; | |
} | |
size_t idx = 0; | |
dump_hex("blob_header", &keyData[idx], 8); | |
idx += 8; | |
dump_hex("pub_key", &keyData[idx], 12); | |
idx += 12; | |
DWORD keyLen = *(((DWORD*)keyData) + 3) / 8; | |
DWORD subKeyLen = (keyLen + 1) / 2; | |
printf("Keylen: %d\n", keyLen); | |
dump_hex("N", &keyData[idx], keyLen); | |
idx += keyLen; | |
dump_hex("p", &keyData[idx], subKeyLen); | |
idx += subKeyLen; | |
dump_hex("q", &keyData[idx], subKeyLen); | |
printf("\n%p %p\n", keyData, keyData+4096); | |
printf("Key generated, press enter to zero export\n"); | |
getchar(); | |
SecureZeroMemory(keyData, 4096); | |
printf("Key generated, press enter to 'destroy' it\n"); | |
getchar(); | |
CryptDestroyKey(keyUser); | |
printf("Key destroyed!\n"); | |
printf("hKey: %p\n", keyUser); | |
getchar(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment