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. 重定位shell

    http://www.tldp.org/LDP/abs/html/io-redirection.html http://unix.stackexchange.com/questions/20469/d ...

  2. xcrun: error: active developer path ("/Volumes/Xcode/Xcode6-Beta.app/Contents/Developer") does not exist, use xcode-select to change

    When using MacOS with xcode6.4, i always meet these error: xcrun: error: active developer path (&quo ...

  3. ZSDR101-跑成品MRP

    *&---------------------------------------------------------------------**& Report ZSDR101*&a ...

  4. HDU 4358 莫队算法+dfs序+离散化

    Boring counting Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 98304/98304 K (Java/Others)T ...

  5. SQL注入测试平台 SQLol -5.DELETE注入测试

    访问首页的delete模块,http://127.0.0.1/sql/delete.php,开始对delete模块进行测试. delete语法: DELETE FROM [users] WHERE [ ...

  6. python--列表生成式--8

    原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuewei/ 一.生成列表 要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],我 ...

  7. 本文使用springMVC和ajax,实现将JSON对象返回到页面

    一.引言 本文使用springMVC和ajax做的一个小小的demo,实现将JSON对象返回到页面,没有什么技术含量,纯粹是因为最近项目中引入了springMVC框架. 二.入门例子 ①. 建立工程, ...

  8. liunx之:rpm包安装

    使用rpm命令查询软件包: 1.查询系统中安装的所有RPM包 $ rpm -qa 查询当前linux系统中已经安装的软件包. 例:$ rpm -qa | grep -i x11 | head -3 察 ...

  9. 磁盘参数修订[转自vbird]

    某些时刻,你可能会希望修改一下目前文件系统的一些相关信息,举例来说,你可能要修改 Label name , 或者是 journal 的参数,或者是其他硬盘运行时的相关参数 (例如 DMA 启动与否-) ...

  10. UserDefault的使用,保存小数据到本地-iOS

    //保持到本地数据 NSArray *array=@[@"234",@"sdfe"]; NSUserDefaults *userDefault=[NSUserD ...