|
|
终于使用Microsoft Enhanced Cryptographic Provider v1.0 实现了公钥加密和解密,但SafeSign CSP Version 1.0不能,不知为什么,有高手能解答吗? 另外dwBufLen 怎样计算才好,我取100,出编号234错,便取了200。 以下程序在VS2003下调试成功 #include "stdafx.h" #include <stdio.h> #include <windows.h> #include <wincrypt.h>
void HandleError(char *s);
#define SA_SIGN_PROV "SafeSign CSP Version 1.0"
int _tmain(int argc, _TCHAR* argv[]) { HCRYPTPROV hCryptProv; HCRYPTKEY hXchgKey; //交换密钥 BYTE pbData[1000]; DWORD cbData;
printf("A cryptographic provider will acquired. \n"); char ch;
//--------------------------------------------------------------------
//访问CSP if(CryptAcquireContext( &hCryptProv, NULL, //NULL表示使用默认密钥容器,默认密钥容器名为用户登陆名 MS_ENHANCED_PROV ,//SA_SIGN_PROV , //SA_SIGN_PROV , PROV_RSA_FULL, 0)) {
printf("A cryptographic provider has been acquired. \n"); } else { printf("Error in get cryptographic provider h. \n"); } //得到CSP参数 cbData = 10000; if(CryptGetProvParam( hCryptProv, PP_NAME, pbData, &cbData, CRYPT_FIRST )) { printf("CryptGetProvParam succeeded.\n"); printf("Provider name: %s\n", pbData); } else { printf("Error reading CSP name. \n"); //exit(1); }
//得到用户的密钥对 if(CryptGetUserKey( hCryptProv, AT_KEYEXCHANGE, &hXchgKey)) { printf("The user exchange key pair has been retrieved. \n");
BOOL bResult;
DWORD dwSecretLen; char bSecret[100]="I LOVE YOU"; //改了
dwSecretLen=strlen((char *) bSecret)+1; //使用公钥加密 if(!CryptEncrypt( hXchgKey, // 之前获得的密鈅对象 0, // 不散列数据 TRUE, // 最后的还是缓冲的数据 0, // 必须置0 (BYTE*)bSecret, // 数据缓冲区 &dwSecretLen, // 数据尺寸 200) // 数据块尺寸 ) { printf("Error during CryptEncrypt. \n"); HandleError("Error during CryptEncrypt. \n"); } else { printf("The CRYPTENCRYPT SUCESS. \n"); printf("Encrypt text:%s\n",bSecret); } //--------------------------------------------------------- //使用私钥解密 if(!CryptDecrypt(hXchgKey,0,TRUE,0,(BYTE*)bSecret,&dwSecretLen))//改了 { HandleError("Error during decrypt. \n"); } else { printf("CryptDecrypt sucess");
printf("Decrypt text:%s\n",bSecret); ch=getchar(); }
}
getchar();
return 0; }
void HandleError(char *s) { fprintf(stderr,"An error occurred in running the program. \n"); fprintf(stderr,"%s\n",s); fprintf(stderr, "Error number %d.\n", GetLastError()); fprintf(stderr, "Program terminating. \n"); getchar(); exit(1); } // End of HandleError
|
|