http://stackoverflow.com/questions/1231178/load-an-x509-pem-file-into-windows-cryptoapi

I discovered the "magic" sequence of calls to import a RSA public key in PEM format. Here you go:

  1. decode the key into a binary blob with CryptStringToBinary; pass CRYPT_STRING_BASE64HEADER in dwFlags
  2. decode the binary key blob into a CERT_PUBLIC_KEY_INFO with CryptDecodeObjectEx; pass X509_ASN_ENCODING in dwCertEncodingType and X509_PUBLIC_KEY_INFO in lpszStructType
  3. decode the PublicKey blob from the CERT_PUBLIC_KEY_INFO into a RSA key blob with CryptDecodeObjectEx; pass X509_ASN_ENCODING in dwCertEncodingType and RSA_CSP_PUBLICKEYBLOB in lpszStructType
  4. import the RSA key blob with CryptImportKey

This sequence really helped me understand what's going on, but it didn't work for me as-is. The second call to CryptDecodeObjectEx gave me an error: "ASN.1 bad tag value met". After many attempts at understanding Microsoft documentation, I finally realized that the output of the fist decode cannot be decoded as ASN again, and that it is actually ready for import. With this understanding I found the answer in the following link:

http://www.ms-news.net/f2748/problem-importing-public-key-4052577.html

int main()
{
char pemPubKey[2048];
int readLen;
char derPubKey[2048];
size_t derPubKeyLen = 2048;
CERT_PUBLIC_KEY_INFO *publicKeyInfo;
int publicKeyInfoLen;
HANDLE hFile;
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0; /*
* Read the public key cert from the file
*/
hFile = CreateFileA( "c:\\pub.pem", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if ( hFile == INVALID_HANDLE_VALUE )
{
fprintf( stderr, "Failed to open file. error: %d\n", GetLastError() );
} if ( !ReadFile( hFile, pemPubKey, 2048, &readLen, NULL ) )
{
fprintf( stderr, "Failed to read file. error: %d\n", GetLastError() );
} /*
* Convert from PEM format to DER format - removes header and footer and decodes from base64
*/
if ( !CryptStringToBinaryA( pemPubKey, 0, CRYPT_STRING_BASE64HEADER, derPubKey, &derPubKeyLen, NULL, NULL ) )
{
fprintf( stderr, "CryptStringToBinary failed. Err: %d\n", GetLastError() );
} /*
* Decode from DER format to CERT_PUBLIC_KEY_INFO
*/
if ( !CryptDecodeObjectEx( X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO, derPubKey, derPubKeyLen,
CRYPT_ENCODE_ALLOC_FLAG, NULL, &publicKeyInfo, &publicKeyInfoLen ) )
{
fprintf( stderr, "CryptDecodeObjectEx 1 failed. Err: %p\n", GetLastError() );
return -1;
} /*
* Acquire context
*/
if( !CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) )
{
{
printf( "CryptAcquireContext failed - err=0x%x.\n", GetLastError() );
return -1;
}
} /*
* Import the public key using the context
*/
if ( !CryptImportPublicKeyInfo( hProv, X509_ASN_ENCODING, publicKeyInfo, &hKey ) )
{
fprintf( stderr, "CryptImportPublicKeyInfo failed. error: %d\n", GetLastError() );
return -1;
}
LocalFree( publicKeyInfo ); /*
* Now use hKey to encrypt whatever you need.
*/ return 0;
}

Load an X509 PEM file into Windows CryptoApi的更多相关文章

  1. No redirect found in host configuration file (C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet.config).

    Configuration Error Description: An error occurred during the processing of a configuration file req ...

  2. pk8和x509.pem转换成keystore

    转自:http://www.cnblogs.com/platte/p/3511814.html 一 在github上下载工具 https://github.com/getfatday/keytool- ...

  3. android初级篇之apk签名key keystore格式转pk8+x509.pem

    转自:http://www.jianshu.com/p/3bd5c68cc44d 常用的android的签名工具有两个即jarsigner 和apksigner.这两种使用的key格式不一样,keys ...

  4. wordpress无法安装这个包。: PCLZIP_ERR_MISSING_FILE (-4) : Missing archive file 'C:\WINDOWS\TEMP/wordpress-4.tmp'

    朋友的wp博客好久没管理了,让ytkah帮忙打理一下,进到后台发现版本还是3.9的,那是比较早以前的版本了,早该升级了. 在升级wordpress时出现以下错误: 无法安装这个包: PCLZIP_ER ...

  5. server error in '/' applecation----Compiler Error Message: CS0016: Could not write to output file 'c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\xx' -- 'Access is denied

    今天在阿里云虚拟机上部署新站点后出现下面的错误:server error in '/' applecation Compiler Error Message: CS0016: Could not wr ...

  6. How to create .gitignore file in Windows Explorer

    How to create .gitignore file I need to add some rules to my .gitignore file, however, I can't find ...

  7. Unreal: Dynamic load map from Pak file

    Unreal: Dynamic load map from Pak file 目标:在程序运行时加载自定义 Pak 文件,并打开指定关卡,显示其中的完整 map 内容 Unreal 的 Pak 文件内 ...

  8. How to load a local .CSS file & JavaScript resources using iPhone UIWebView Class

    This post will cover the basic setup and creation of an application with web content for iPhone that ...

  9. Launch a Batch File With Windows Installer

    Quote from: http://flexerasoftware.force.com/articles/en_US/HOWTO/Q111515 Synopsis This article desc ...

随机推荐

  1. PHP 转换snmp的时间格式

    function convert_snmp_timeticks($timeticks) { if(!is_numeric($timeticks)) { return FALSE; } //如果是字符串 ...

  2. SFTP 上传文件夹

    使用sftp上传文件夹时若使用如下命令并不work: put /media/Research/GWAS_Class/* Desktop/ 此时,需要添加一个参数 -r, 另外在目标文件夹下面建立一个同 ...

  3. [转载] 动态链接库dll的 静态加载 与 动态加载

    转载自:http://blog.csdn.net/youxin2012/article/details/11538491 dll 两种链接方式  : 动态链接和静态链接(链接亦称加载)   动态链接是 ...

  4. 用Python对excel文件的简单操作

    #-*-coding:utf8-*- import xlrd #代开excel文件读取数据 data = xlrd.open_workbook("C:\\Users\\hyl\\Deskto ...

  5. ZOJ 1048 Financial Management

    原题链接 题目大意:给出12个月的收入,求一个平均值. 解法:没什么好说的,就是一个除法. 参考代码: #include<stdio.h> int main(){ int i; float ...

  6. c#---部分;把数组或者结构体存入集合里,然后再从集合中取出之后,输出;foreach既可以用到提取数组重点额数据,也可以提取集合中的数据(前提是集合中的元素是相同数据类型)

    1.输入班级人数,统计每个人的姓名,性别,年龄:集合与数组 //Console.Write("请输入班级人数:"); //int a = int.Parse(Console.Rea ...

  7. ctypes 模块

    ctypes赋予了python类似于C语言一样的底层操作能力,通过ctypes模块可以调用动态链接库中的导出函数.构建复杂的c数据类型. ctypes提供了三种不同的动态链接库加载方式:cdll(), ...

  8. nginx的HA集群及配置

    一.服务器环境 master服务器: ip:192.168.11.155 系统环境:CentOS release 6.5 (Final) 内核版本:2.6.32-431.el6.x86_64 防火墙和 ...

  9. VC线程中操作控件,引起程序卡死的问题。

    [问题还原] 线程中操作控件,具体为控制一个按键的使能,使能后结束线程. 主程序中有一个死循环,等待线程结束. 然后,就没有然后了-- [解决方案] 在主程序死循环中,如果检测到界面消息,优先处理掉.

  10. 【转】详解使用tcpdump、wireshark对Android应用程序进行抓包并分析

    原文网址:http://blog.csdn.net/gebitan505/article/details/19044857 本文主要介绍如何使用tcpdump和wireshark对Android应用程 ...