Windows CryptoAPI

// win32-test.cpp : 定义控制台应用程序的入口点。
//
// Defines the entry point for the console
// application.

#include "stdafx.h"


#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#include <conio.h>
#include <atlenc.h>

#include "encrypt.h"

// Link with the Advapi32.lib file.
#pragma comment (lib, "advapi32")



typedef struct {
    BYTE * keyData;
    int keyDataLen;
} B_RSAW;

typedef struct
{
    char *keyData;
    int keDataLen;
} RSAW;

B_RSAW* RSA_key_w()
{
    HCRYPTPROV hCryptProv = NULL; // handle to a cryptographic service provider (CSP)
    //---------------------------------------------------------------
    // Get the handle to the default provider.
    // #param pszProvider  Cryptographic Provider Names
    //     MS_ENHANCED_PROV  "Microsoft Enhanced Cryptographic Provider v1.0"
    CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_DELETEKEYSET);
    if(CryptAcquireContext(
        &hCryptProv,
        NULL,
        MS_ENHANCED_PROV, // "Microsoft Enhanced Cryptographic Provider v1.0"
        PROV_RSA_FULL,
        CRYPT_NEWKEYSET))
    {
        _tprintf(
            TEXT("A cryptographic provider has been acquired. \n"));
    }
    else
    {
        return NULL;
    }

    HCRYPTKEY hKey;// handle of the key
    if(CryptGenKey(
          hCryptProv,
          AT_KEYEXCHANGE,
          CRYPT_EXPORTABLE,
          &hKey))
    {
         printf("A session key has been created.\n");
    }
    else
    {
          printf("Error during CryptGenKey.\n");
          exit(1);
    }

    DWORD dwTempPriLen;
    int r = CryptExportKey(hKey, NULL, PRIVATEKEYBLOB, NULL, NULL, &dwTempPriLen);


    BYTE *pbTempPriData = (BYTE *)malloc(dwTempPriLen+1);
    r = CryptExportKey(hKey, NULL, PRIVATEKEYBLOB, NULL, pbTempPriData, &dwTempPriLen);

    //-------------------------------------------------------------------
    //  The key created can be exported into a key BLOB that can be
    //  written to a file.
    //  ...
    //  When you have finished using the key, free the resource.
    if (!CryptDestroyKey(hKey))
    {
          printf("Error during CryptDestroyKey.\n");
          exit(1);
    }
    if (! CryptReleaseContext(hCryptProv, 0))
    {
        printf("Error during CryptReleaseContext.\n");
          exit(1);
    }
    B_RSAW *rsa = (B_RSAW *) malloc(sizeof(B_RSAW));
    rsa->keyData = pbTempPriData;
    rsa->keyDataLen = dwTempPriLen;
    return rsa;
}

void RSA_key_write_RSAPrivateKey_W(const char* fn, B_RSAW* rsa)
{
    FILE *fp = NULL;
    fp = fopen(fn, "wb");
    if (fp == NULL) {
        fprintf(stderr,"%s open error", fn);
    }
    printf("file %s opened...\n", fn);
    fwrite(rsa->keyData, 1, rsa->keyDataLen+1, fp);
    fclose(fp);
}

RSAW* RSA_key_base64_w(B_RSAW *rsa)
{
    //B_RSAW *rsa = RSA_key_w();
    int len = Base64EncodeGetRequiredLength(rsa->keyDataLen, ATL_BASE64_FLAG_NONE);
    LPSTR szDest = (LPSTR) malloc(len + 1);
    memset(szDest, 0, len + 1);
   
    Base64Encode(rsa->keyData, rsa->keyDataLen, szDest, &len, ATL_BASE64_FLAG_NONE );

   
   
    RSAW *_rsa = (RSAW *) malloc(sizeof(RSAW));
    _rsa->keyData = szDest;
    _rsa->keDataLen = len + 1;
    return _rsa;
}

void RSA_key_write_RSAPrivateKey_base64_W(const char* fn, RSAW* rsa)
{
    FILE *fp2 = NULL;

    fp2 = fopen(fn, "wb");
    if (fp2 == NULL) {
        fprintf(stderr,"%s open error", fn);
        return;
    }
    //fwrite(rsa->keyData, 1, rsa->keyDataLen+1, fp);
    fprintf(fp2, "%s", rsa->keyData);
    //fclose(fp);
    fclose(fp2);
}


int _tmain(int argc, _TCHAR* argv[])
{
    /*
    if(argc < 3)
    {
        _tprintf(TEXT("Usage: <example.exe> <source file> ")
            TEXT("<destination file> | <password>\n"));
        _tprintf(TEXT("<password> is optional.\n"));
        _tprintf(TEXT("Press any key to exit."));
        _gettch();
        return 1;
    }
    */

    B_RSAW *rsa = RSA_key_w();

    char *fn = "D:\\home\\workspace1\\tst_edit\\MFCActiveXControl1\\win32-test\\test-g-win.key";
    RSA_key_write_RSAPrivateKey_W(fn, rsa);

    RSAW *_rsa = RSA_key_base64_w(rsa);
    char *fn2 = "D:\\home\\workspace1\\tst_edit\\MFCActiveXControl1\\win32-test\\test-g-2-win.key";
    RSA_key_write_RSAPrivateKey_base64_W(fn2, _rsa);

    /*
    LPTSTR pszSource = NULL;
    LPTSTR pszDestination = NULL;
    LPTSTR pszPassword = NULL;

    pszSource = L"D:\\home\\workspace1\\tst_edit\\MFCActiveXControl1\\win32-test\\plain-text.txt";
    pszDestination = L"D:\\home\\workspace1\\tst_edit\\MFCActiveXControl1\\win32-test\\encrypt-text.txt";
    pszPassword = L"yihaodian";

    //---------------------------------------------------------------
    // Call EncryptFile to do the actual encryption.
    if(MyEncryptFile(pszSource, pszDestination, pszPassword))
    {
        _tprintf(
            TEXT("Encryption of the file %s was successful. \n"),
            pszSource);
        _tprintf(
            TEXT("The encrypted data is in file %s.\n"),
            pszDestination);
    }
    else
    {
        MyHandleError(
            TEXT("Error encrypting file!\n"),
            GetLastError());
    }
    */
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值