本文整理汇总了C++中CryptReleaseContext函数的典型用法代码示例。如果您正苦于以下问题:C++ CryptReleaseContext函数的具体用法?C++ CryptReleaseContext怎么用?C++ CryptReleaseContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CryptReleaseContext函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: CWE327_Use_Broken_Crypto__w32_RC5_11_bad
void CWE327_Use_Broken_Crypto__w32_RC5_11_bad()
{
if(globalReturnsTrue())
{
{
FILE *pFile;
HCRYPTPROV hCryptProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
char password[100];
size_t passwordLen;
char toBeDecrypted[100];
DWORD toBeDecryptedLen = sizeof(toBeDecrypted)-1;
/* Read the password from the console */
printLine("Enter the password: ");
if (fgets(password, 100, stdin) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
password[0] = '\0';
}
/* The next 3 lines remove the carriage return from the string that is
* inserted by fgets() */
passwordLen = strlen(password);
if (passwordLen > 0)
{
password[passwordLen-1] = '\0';
}
/* Read the data to be decrypted from a file */
pFile = fopen("encrypted.txt", "rb");
if (pFile == NULL)
{
exit(1);
}
if (fread(toBeDecrypted, sizeof(char), 100, pFile) != 100)
{
fclose(pFile);
exit(1);
}
toBeDecrypted[99] = '\0';
/* Try to get a context with and without a new key set */
if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
{
if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET))
{
printLine("Error in acquiring cryptographic context");
exit(1);
}
}
/* Create Hash handle */
if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
{
printLine("Error in creating hash");
exit(1);
}
/* Hash the password */
if(!CryptHashData(hHash, (BYTE *) password, passwordLen, 0))
{
printLine("Error in hashing password");
exit(1);
}
/* Derive a RC5 key from the Hashed password */
if(!CryptDeriveKey(hCryptProv, CALG_RC5, hHash, 0, &hKey))
{
printLine("Error in CryptDeriveKey");
exit(1);
}
/* FLAW: Decrypt using RC5 */
if(!CryptDecrypt(hKey, 0, 1, 0, (BYTE *)toBeDecrypted, &toBeDecryptedLen))
{
printLine("Error in decryption");
exit(1);
}
/* Ensure the plaintext is NUL-terminated */
toBeDecrypted[toBeDecryptedLen] = '\0';
printLine(toBeDecrypted);
/* Cleanup */
if (hKey)
{
CryptDestroyKey(hKey);
}
if (hHash)
{
CryptDestroyHash(hHash);
}
if (hCryptProv)
{
CryptReleaseContext(hCryptProv, 0);
}
if (pFile)
{
fclose(pFile);
}
}
}
}
示例2: rust_win32_rand_release
void
rust_win32_rand_release(HCRYPTPROV hProv) {
win32_require
(_T("CryptReleaseContext"), CryptReleaseContext(hProv, 0));
}
示例3: goodB2G1
/* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_TRUE to STATIC_CONST_FALSE */
static void goodB2G1()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
if(STATIC_CONST_TRUE)
{
{
FILE *pFile;
pFile = fopen("passwords.txt", "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read the password from a file */
if (fgets(data, 100, pFile) == NULL)
{
data[0] = '\0';
}
fclose(pFile);
}
else
{
data[0] = '\0';
}
}
}
if(STATIC_CONST_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
HANDLE pHandle;
char * username = "User";
char * domain = "Domain";
char hashData[100] = HASH_INPUT;
HCRYPTPROV hCryptProv = 0;
HCRYPTHASH hHash = 0;
HCRYPTKEY hKey = 0;
do
{
BYTE payload[(100 - 1) * sizeof(char)]; /* same size as data except for NUL terminator */
DWORD payloadBytes;
/* Hex-decode the input string into raw bytes */
payloadBytes = decodeHexChars(payload, sizeof(payload), data);
/* Wipe the hex string, to prevent it from being given to LogonUserA if
* any of the crypto calls fail. */
SecureZeroMemory(data, 100 * sizeof(char));
/* Aquire a Context */
if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
{
break;
}
/* Create hash handle */
if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
{
break;
}
/* Hash the input string */
if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
{
break;
}
/* Derive an AES key from the hash */
if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
{
break;
}
if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
{
break;
}
/* Copy back into data and NUL-terminate */
memcpy(data, payload, payloadBytes);
data[payloadBytes / sizeof(char)] = '\0';
}
while (0);
if (hKey)
{
CryptDestroyKey(hKey);
}
if (hHash)
{
CryptDestroyHash(hHash);
}
if (hCryptProv)
{
CryptReleaseContext(hCryptProv, 0);
}
/* FIX: Decrypt the password before using it for authentication */
if (LogonUserA(
username,
domain,
data,
LOGON32_LOGON_NETWORK,
LOGON32_PROVIDER_DEFAULT,
&pHandle) != 0)
{
//.........这里部分代码省略.........
示例4: CWE321_Hard_Coded_Cryptographic_Key__w32_char_61_bad
void CWE321_Hard_Coded_Cryptographic_Key__w32_char_61_bad()
{
char * cryptoKey;
char cryptoKeyBuffer[100] = "";
cryptoKey = cryptoKeyBuffer;
cryptoKey = CWE321_Hard_Coded_Cryptographic_Key__w32_char_61b_badSource(cryptoKey);
{
HCRYPTPROV hCryptProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
char toBeEncrypted[] = "String to be encrypted";
DWORD encryptedLen = strlen(toBeEncrypted)*sizeof(char);
BYTE encrypted[200]; /* buffer should be larger than toBeEncrypted to have room for IV and padding */
/* Copy plaintext (without NUL terminator) into byte buffer */
memcpy(encrypted, toBeEncrypted, encryptedLen);
/* Try to get a context with and without a new key set */
if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0))
{
if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET))
{
printLine("Error in acquiring cryptographic context");
exit(1);
}
}
/* Create Hash handle */
if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
{
printLine("Error in creating hash");
exit(1);
}
/* Hash the cryptoKey */
if(!CryptHashData(hHash, (BYTE *) cryptoKey, strlen(cryptoKey)*sizeof(char), 0))
{
printLine("Error in hashing cryptoKey");
exit(1);
}
/* Derive an AES key from the Hashed cryptoKey */
if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
{
printLine("Error in CryptDeriveKey");
exit(1);
}
/* POTENTIAL FLAW: Possibly using a hardcoded crypto key */
/* Use the derived key to encrypt something */
if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted)))
{
printLine("Error in CryptEncrypt");
exit(1);
}
/* use encrypted block */
printBytesLine(encrypted, encryptedLen);
if (hKey)
{
CryptDestroyKey(hKey);
}
if (hHash)
{
CryptDestroyHash(hHash);
}
if (hCryptProv)
{
CryptReleaseContext(hCryptProv, 0);
}
}
}
示例5: KSI_PKITruststore_verifyRawSignature
int KSI_PKITruststore_verifyRawSignature(KSI_CTX *ctx, const unsigned char *data, unsigned data_len, const char *algoOid, const unsigned char *signature, unsigned signature_len, const KSI_PKICertificate *certificate) {
int res = KSI_UNKNOWN_ERROR;
ALG_ID algorithm=0;
HCRYPTPROV hCryptProv = 0;
PCCERT_CONTEXT subjectCert = NULL;
HCRYPTKEY publicKey = 0;
DWORD i=0;
BYTE *little_endian_pkcs1= NULL;
DWORD pkcs1_len = 0;
HCRYPTHASH hash = 0;
char buf[1024];
KSI_ERR_clearErrors(ctx);
if (ctx == NULL || data == NULL || signature == NULL ||
signature_len >= UINT_MAX || algoOid == NULL || certificate == NULL){
res = KSI_INVALID_ARGUMENT;
goto cleanup;
}
algorithm = algIdFromOID(algoOid);
if (algorithm == 0) {
KSI_pushError(ctx, res = KSI_UNAVAILABLE_HASH_ALGORITHM, NULL);
goto cleanup;
}
// Get the CSP context
if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){
KSI_LOG_debug(ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf)));
KSI_pushError(ctx, res = KSI_CRYPTO_FAILURE, "Unable to get cryptographic provider.");
goto cleanup;
}
// Get the public key from the issuer certificate
subjectCert = certificate->x509;
if (!CryptImportPublicKeyInfo(hCryptProv, X509_ASN_ENCODING,&subjectCert->pCertInfo->SubjectPublicKeyInfo,&publicKey)){
KSI_LOG_debug(ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf)));
KSI_pushError(ctx, res = KSI_PKI_CERTIFICATE_NOT_TRUSTED, "Failed to read PKI public key.");
goto cleanup;
}
/*Convert big-endian to little-endian PKCS#1 signature*/
pkcs1_len = signature_len;
little_endian_pkcs1 = (BYTE*)KSI_malloc(pkcs1_len);
if (little_endian_pkcs1 == NULL){
KSI_pushError(ctx, res = KSI_OUT_OF_MEMORY, NULL);
goto cleanup;
}
for (i=0; i<pkcs1_len; i++){
little_endian_pkcs1[pkcs1_len-1-i] = signature[i];
}
// Create the hash object and hash input data.
if (!CryptCreateHash(hCryptProv, algorithm, 0, 0, &hash)){
KSI_LOG_debug(ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf)));
KSI_pushError(ctx, res = KSI_CRYPTO_FAILURE, "Unable to create hasher.");
goto cleanup;
}
if (!CryptHashData(hash, (BYTE*)data, data_len,0)){
KSI_LOG_debug(ctx, "%s", getMSError(GetLastError(), buf, sizeof(buf)));
KSI_pushError(ctx, res = KSI_CRYPTO_FAILURE, "Unable to hash data.");
goto cleanup;
}
/*Verify the signature. The format MUST be PKCS#1*/
if (!CryptVerifySignature(hash, (BYTE*)little_endian_pkcs1, pkcs1_len, publicKey, NULL, 0)){
DWORD error = GetLastError();
const char *errmsg = getMSError(GetLastError(), buf, sizeof(buf));
KSI_LOG_debug(ctx, "%s", errmsg);
if (error == NTE_BAD_SIGNATURE)
KSI_pushError(ctx, res = KSI_PKI_CERTIFICATE_NOT_TRUSTED, "Invalid PKI signature.");
else if (error == NTE_NO_MEMORY)
KSI_pushError(ctx, res = KSI_OUT_OF_MEMORY, "Unable to verify PKI signature. CSP out of memory.");
else
KSI_pushError(ctx, res = KSI_PKI_CERTIFICATE_NOT_TRUSTED, errmsg);
goto cleanup;
}
KSI_LOG_debug(certificate->ctx, "CryptoAPI: PKI signature verified successfully.");
res = KSI_OK;
cleanup:
KSI_free(little_endian_pkcs1);
if (hCryptProv) CryptReleaseContext(hCryptProv, 0);
if (hash) CryptDestroyHash(hash);
return res;
}
示例6: modmd5
HRESULT
modmd5(LPSTR *hexhash)
{
HRESULT hRes;
HANDLE hFile = NULL;
DEBUG_MODULE_PARAMETERS ModParams;
HCRYPTPROV hCryptProv = NULL;
HCRYPTHASH hHash = NULL;
BYTE *pbHashData = NULL;
BYTE buffer[BUFSIZE];
DWORD cbHash;
DWORD cbRead = 0;
BOOL bResult = FALSE;
/*
msdn: returns parameters for modules in the target.
*/
hRes=g_ExtSymbols->GetModuleParameters(1, &g_Base, 0, &ModParams);
if(FAILED(hRes))
{
dprintf("[sync] modcheck: failed get module parameters\n");
return E_FAIL;
}
dprintf("[sync] modcheck:\n"
" File: %s\n"
" Size: 0x%x\n"
" TimeDateStamp: 0x%x\n", g_NameBuffer, ModParams.Size, ModParams.TimeDateStamp);
hRes=E_FAIL;
hFile = CreateFile(g_NameBuffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
dprintf("[sync] failed at opening file: %d\n", GetLastError());
return hRes;
}
if (!(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)))
{
dprintf("[sync] CryptAcquireContext failed\n");
goto Exit;
}
if (!(CryptCreateHash(hCryptProv, CALG_MD5, NULL, NULL, &hHash)))
{
dprintf("[sync] CryptCreateHash failed\n");
goto Exit;
}
while (bResult = ReadFile(hFile, buffer, BUFSIZE, &cbRead, NULL))
{
if (cbRead == 0)
break;
if (!(CryptHashData(hHash, buffer, cbRead, NULL)))
{
dprintf("[sync] CryptHashData failed\n");
goto Exit;
}
}
if (!bResult)
{
dprintf("[sync] ReadFile failed\n");
goto Exit;
}
if (!(CryptGetHashParam(hHash, HP_HASHVAL, NULL, &cbHash, 0)))
{
dprintf("[sync] CryptGetHashParam failed\n");
goto Exit;
}
pbHashData = (BYTE *) malloc(cbHash);
if (pbHashData==NULL){
dprintf("[sync] failed at allocate buffer: %d\n", GetLastError());
goto Exit;
}
if (!(CryptGetHashParam(hHash, HP_HASHVAL, pbHashData, &cbHash, 0)))
{
dprintf("[sync] CryptGetHashParam failed\n");
goto Exit;
}
hRes = ToHexString((const byte *)pbHashData, (unsigned int)cbHash, hexhash);
Exit:
if (hFile)
CloseHandle(hFile);
if (pbHashData)
free(pbHashData);
if (hHash)
CryptDestroyHash(hHash);
if (hCryptProv)
CryptReleaseContext(hCryptProv,0);
return hRes;
}
示例7: SfcIsFileLegit
//.........这里部分代码省略.........
*
* 8. Use result MD5 as hash value;
*
* 9. Verify embedded signature.
*
* If anything from the above fail - file is not legit by ZeroAccess opinion.
*
* If you copy ZeroAccess downloaded files without copying EA data, it cannot be verified.
*
*/
NTSTATUS SfcIsFileLegit(
_In_ LPWSTR lpFileName,
_In_ PBYTE BotKey,
_In_ DWORD BotKeySize
)
{
BOOL cond = FALSE;
PVOID pBuffer;
MD5_CTX context;
ZA_FILEHEADER zaHeader;
HCRYPTPROV lh_prov = 0;
HCRYPTKEY lh_key = 0;
HANDLE hFile = NULL;
NTSTATUS status = STATUS_UNSUCCESSFUL;
OBJECT_ATTRIBUTES ObjectAttributes;
IO_STATUS_BLOCK IoStatusBlock;
UNICODE_STRING usFileName;
SIZE_T memIO = 0;
if (
(lpFileName == NULL) ||
(BotKey == NULL) ||
(BotKeySize == 0)
)
{
return status;
}
RtlSecureZeroMemory(&usFileName, sizeof(usFileName));
do {
if (RtlDosPathNameToNtPathName_U(lpFileName, &usFileName, NULL, NULL) == FALSE)
break;
InitializeObjectAttributes(&ObjectAttributes, &usFileName, OBJ_CASE_INSENSITIVE, NULL, NULL);
status = NtOpenFile(&hFile, FILE_GENERIC_READ, &ObjectAttributes, &IoStatusBlock,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT
);
if (!NT_SUCCESS(status))
break;
RtlFreeUnicodeString(&usFileName);
RtlSecureZeroMemory(&zaHeader, sizeof(zaHeader));
if (!SfNtfsQueryFileHeaderFromEa(hFile, &zaHeader)) {
status = STATUS_EA_LIST_INCONSISTENT;
break;
}
status = STATUS_UNSUCCESSFUL;
memIO = zaHeader.Size;
pBuffer = NULL;
if (
(NT_SUCCESS(NtAllocateVirtualMemory(NtCurrentProcess(), &pBuffer, 0, &memIO, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) &&
(pBuffer != NULL)
)
{
if (NT_SUCCESS(NtReadFile(hFile, NULL, NULL, NULL, &IoStatusBlock, pBuffer, zaHeader.Size, NULL, NULL))) {
if (CryptAcquireContext(&lh_prov, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
if (CryptImportKey(lh_prov, (const BYTE *)BotKey, BotKeySize, 0, 0, &lh_key)) {
RtlSecureZeroMemory(&context, sizeof(context));
MD5Init(&context);
MD5Update(&context, (UCHAR*)&zaHeader, (UINT)3 * sizeof(ULONG)); //note: ZA_FILEHEADER without signature
if (SfcVerifyFile(lh_prov, lh_key, &context, pBuffer, zaHeader.Size))
status = STATUS_SUCCESS;
CryptDestroyKey(lh_key);
}
CryptReleaseContext(lh_prov, 0);
}
}
memIO = 0;
NtFreeVirtualMemory(NtCurrentProcess(), &pBuffer, &memIO, MEM_RELEASE);
}
NtClose(hFile);
hFile = NULL;
} while (cond);
if (hFile != NULL) NtClose(hFile);
if (usFileName.Buffer != NULL) {
RtlFreeUnicodeString(&usFileName);
}
return status;
}
示例8: goodG2B
/* goodG2B() - use goodsource and badsink by changing the conditions on the for statements */
static void goodG2B()
{
int h;
wchar_t * cryptoKey;
wchar_t cryptoKeyBuffer[100] = L"";
cryptoKey = cryptoKeyBuffer;
for(h = 0; h < 1; h++)
{
{
size_t cryptoKeyLen = wcslen(cryptoKey);
/* if there is room in cryptoKey, read into it from the console */
if(100-cryptoKeyLen > 1)
{
/* FIX: Obtain the hash input from the console */
if (fgetws(cryptoKey+cryptoKeyLen, (int)(100-cryptoKeyLen), stdin) == NULL)
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
cryptoKey[cryptoKeyLen] = L'\0';
}
/* The next 3 lines remove the carriage return from the string that is
* inserted by fgetws() */
cryptoKeyLen = wcslen(cryptoKey);
if (cryptoKeyLen > 0)
{
cryptoKey[cryptoKeyLen-1] = L'\0';
}
}
}
}
{
HCRYPTPROV hCryptProv;
HCRYPTKEY hKey;
HCRYPTHASH hHash;
wchar_t toBeEncrypted[] = L"String to be encrypted";
DWORD encryptedLen = wcslen(toBeEncrypted)*sizeof(wchar_t);
BYTE encrypted[200]; /* buffer should be larger than toBeEncrypted to have room for IV and padding */
/* Copy plaintext (without NUL terminator) into byte buffer */
memcpy(encrypted, toBeEncrypted, encryptedLen);
/* Try to get a context with and without a new key set */
if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0))
{
if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET))
{
printLine("Error in acquiring cryptographic context");
exit(1);
}
}
/* Create Hash handle */
if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
{
printLine("Error in creating hash");
exit(1);
}
/* Hash the cryptoKey */
if(!CryptHashData(hHash, (BYTE *) cryptoKey, wcslen(cryptoKey)*sizeof(wchar_t), 0))
{
printLine("Error in hashing cryptoKey");
exit(1);
}
/* Derive an AES key from the Hashed cryptoKey */
if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
{
printLine("Error in CryptDeriveKey");
exit(1);
}
/* POTENTIAL FLAW: Possibly using a hardcoded crypto key */
/* Use the derived key to encrypt something */
if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted)))
{
printLine("Error in CryptEncrypt");
exit(1);
}
/* use encrypted block */
printBytesLine(encrypted, encryptedLen);
if (hKey)
{
CryptDestroyKey(hKey);
}
if (hHash)
{
CryptDestroyHash(hHash);
}
if (hCryptProv)
{
CryptReleaseContext(hCryptProv, 0);
}
}
}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:90,代码来源:CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_17.c
示例9: KSI_DataHasher_open
int KSI_DataHasher_open(KSI_CTX *ctx, KSI_HashAlgorithm algo_id, KSI_DataHasher **hasher) {
int res = KSI_UNKNOWN_ERROR;
KSI_DataHasher *tmp_hasher = NULL;
CRYPTO_HASH_CTX *tmp_cryptoCTX = NULL;
HCRYPTPROV tmp_CSP = 0;
KSI_ERR_clearErrors(ctx);
if (ctx == NULL || hasher == NULL){
res = KSI_INVALID_ARGUMENT;
goto cleanup;
}
/*Test if hash algorithm is valid*/
if (!KSI_isHashAlgorithmSupported(algo_id)) {
KSI_pushError(ctx, res = KSI_UNAVAILABLE_HASH_ALGORITHM, NULL);
goto cleanup;
}
/*Create new abstract data hasher object*/
tmp_hasher = KSI_new(KSI_DataHasher);
if (tmp_hasher == NULL) {
KSI_pushError(ctx, res = KSI_OUT_OF_MEMORY, NULL);
goto cleanup;
}
tmp_hasher->hashContext = NULL;
tmp_hasher->ctx = ctx;
tmp_hasher->algorithm = algo_id;
tmp_hasher->closeExisting = closeExisting;
/*Create new helper context for crypto api*/
res = CRYPTO_HASH_CTX_new(&tmp_cryptoCTX);
if (res != KSI_OK) {
KSI_pushError(ctx, res, NULL);
goto cleanup;
}
/*Create new crypto service provider (CSP)*/
if (!CryptAcquireContext(&tmp_CSP, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){
char errm[1024];
KSI_snprintf(errm, sizeof(errm), "Wincrypt Error (%d)", GetLastError());
KSI_pushError(ctx, res = KSI_CRYPTO_FAILURE, errm);
goto cleanup;
}
/*Set CSP in helper struct*/
tmp_cryptoCTX->pt_CSP = tmp_CSP;
/*Set helper struct in abstract struct*/
tmp_hasher->hashContext = tmp_cryptoCTX;
res = KSI_DataHasher_reset(tmp_hasher);
if (res != KSI_OK) {
KSI_pushError(ctx, res, NULL);
goto cleanup;
}
*hasher = tmp_hasher;
tmp_hasher = NULL;
tmp_cryptoCTX = NULL;
tmp_CSP = 0;
res = KSI_OK;
cleanup:
KSI_DataHasher_free(tmp_hasher);
if (tmp_CSP) CryptReleaseContext(tmp_CSP, 0);
CRYPTO_HASH_CTX_free(tmp_cryptoCTX);
return res;
}
示例10: ntru_rand_wincrypt_release
uint8_t ntru_rand_wincrypt_release(NtruRandContext *rand_ctx) {
HCRYPTPROV *hCryptProv = (HCRYPTPROV*)rand_ctx->state;
uint8_t result = CryptReleaseContext(*hCryptProv, 0);
free(hCryptProv);
return result;
}
示例11: main
void _cdecl main(void)
{
INT iReturn = 0;
HCRYPTPROV hProv = 0;
LPSTR pszContainerName = NULL;
DWORD cbContainerName = 0;
HCRYPTKEY hKey;
// Attempt to acquire a handle to the default key container.
if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) {
if(GetLastError() != NTE_BAD_KEYSET) {
// Some sort of error occured.
printf("Error opening default key container!\n");
goto Error;
}
// Create default key container.
if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
printf("Error creating default key container!\n");
goto Error;
}
// Get size of the name of the default key container name.
if(CryptGetProvParam(hProv, PP_CONTAINER, NULL, &cbContainerName, 0)) {
// Allocate buffer to receive default key container name.
pszContainerName = malloc(cbContainerName);
if(pszContainerName) {
// Get name of default key container name.
if(!CryptGetProvParam(hProv, PP_CONTAINER, (PBYTE)pszContainerName, &cbContainerName, 0)) {
// Error getting default key container name.
pszContainerName[0] = 0;
}
}
}
printf("Create key container '%s'\n", pszContainerName ? pszContainerName : "");
// Free container name buffer (if created)
if(pszContainerName) {
free(pszContainerName);
}
}
// Attempt to get handle to signature key.
if(!CryptGetUserKey(hProv, AT_SIGNATURE, &hKey)) {
if(GetLastError() != NTE_NO_KEY) {
printf("Error %x during CryptGetUserKey!\n", GetLastError());
goto Error;
}
// Create signature key pair.
printf("Create signature key pair\n");
if(!CryptGenKey(hProv, AT_SIGNATURE, 0, &hKey)) {
printf("Error %x during CryptGenKey!\n", GetLastError());
goto Error;
}
}
// Close key handle
CryptDestroyKey(hKey);
// Attempt to get handle to exchange key.
if(!CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hKey)) {
if(GetLastError() != NTE_NO_KEY) {
printf("Error %x during CryptGetUserKey!\n", GetLastError());
goto Error;
}
// Create key exchange key pair.
printf("Create key exchange key pair\n");
if(!CryptGenKey(hProv, AT_KEYEXCHANGE, 0, &hKey)) {
printf("Error %x during CryptGenKey!\n", GetLastError());
goto Error;
}
}
// Close key handle
CryptDestroyKey(hKey);
printf("OK\n");
Exit:
// Close the context (if open)
if(hProv) {
CryptReleaseContext(hProv, 0);
}
exit(iReturn);
Error:
//.........这里部分代码省略.........
示例12: CreateSignatureHMACSHA1
//.........这里部分代码省略.........
DWORD base64Size = 0;
if ( CryptAcquireContext(&cryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE ){
goto Err_End;
}
if( hashKey.size() > 64 ){
if ( CryptCreateHash(cryptProv, CALG_SHA1, 0, 0, &cryptHash) == FALSE ){
goto Err_End;
}
if( CryptHashData(cryptHash, (BYTE*)hashKey.c_str(), (DWORD)hashKey.length(), 0) == FALSE ){
goto Err_End;
}
if( CryptGetHashParam(cryptHash, HP_HASHVAL, NULL, &keySize, 0 ) == FALSE ){
goto Err_End;
}
if( CryptGetHashParam(cryptHash, HP_HASHVAL, key, &keySize, 0 ) == FALSE ){
goto Err_End;
}
CryptDestroyHash(cryptHash);
cryptHash = NULL;
}else{
keySize = (DWORD)hashKey.size();
memcpy(key, hashKey.c_str(), keySize);
}
memcpy(ipad, key, keySize);
memcpy(opad, key, keySize);
for( int i=0; i<64; i++ ){
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
if ( CryptCreateHash(cryptProv, CALG_SHA1, 0, 0, &cryptHash) == FALSE ){
goto Err_End;
}
if( CryptHashData(cryptHash, ipad, 64, 0) == FALSE ){
goto Err_End;
}
if( CryptHashData(cryptHash, (BYTE*)hashSrc.c_str(), (DWORD)hashSrc.size(), 0) == FALSE ){
goto Err_End;
}
if( CryptGetHashParam(cryptHash, HP_HASHVAL, NULL, &firstHashSize, 0 ) == FALSE ){
goto Err_End;
}
firstHash = new BYTE[firstHashSize];
if( CryptGetHashParam(cryptHash, HP_HASHVAL, firstHash, &firstHashSize, 0 ) == FALSE ){
goto Err_End;
}
CryptDestroyHash(cryptHash);
cryptHash = NULL;
if ( CryptCreateHash(cryptProv, CALG_SHA1, 0, 0, &cryptHash) == FALSE ){
goto Err_End;
}
if( CryptHashData(cryptHash, opad, 64, 0) == FALSE ){
goto Err_End;
}
if( CryptHashData(cryptHash, firstHash, firstHashSize, 0) == FALSE ){
goto Err_End;
}
if( CryptGetHashParam(cryptHash, HP_HASHVAL, NULL, &secondHashSize, 0 ) == FALSE ){
goto Err_End;
}
secondHash = new BYTE[secondHashSize];
if( CryptGetHashParam(cryptHash, HP_HASHVAL, secondHash, &secondHashSize, 0 ) == FALSE ){
goto Err_End;
}
CryptDestroyHash(cryptHash);
cryptHash = NULL;
//Base64
if( CryptBinaryToString( secondHash, secondHashSize, CRYPT_STRING_BASE64, NULL, &base64Size ) == FALSE){
goto Err_End;
}
base64 = new WCHAR[ base64Size + 1 ];
if( CryptBinaryToString( secondHash, secondHashSize, CRYPT_STRING_BASE64, base64, &base64Size ) == FALSE ){
goto Err_End;
}
signature = base64;
//最後に\r\n入ってしまうみたいなので除去
Replace(signature, L"\r\n", L"");
Err_End:
SAFE_DELETE_ARRAY(base64);
SAFE_DELETE_ARRAY(secondHash);
SAFE_DELETE_ARRAY(firstHash);
if( cryptHash !=NULL ){
CryptDestroyHash(cryptHash);
}
if( cryptProv != NULL ){
CryptReleaseContext(cryptProv, 0);
}
if( signature.size() > 0 ){
return TRUE;
}else{
return FALSE;
}
}
示例13: swCryptTerm
//-----------------------------------------------------------------------------
// swCryptTerm()
//-----------------------------------------------------------------------------
// Libération du CSP
//-----------------------------------------------------------------------------
void swCryptTerm()
{
TRACE((TRACE_ENTER,_F_,""));
if (ghProv!=NULL) { CryptReleaseContext(ghProv,0); ghProv=NULL; }
TRACE((TRACE_LEAVE,_F_,""));
}
示例14: mit_krb5_pkinit_cert_hash_str
char *
mit_krb5_pkinit_cert_hash_str(const mit_krb5_data *cert)
{
#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H
CC_SHA1_CTX ctx;
char *outstr, *cpOut;
unsigned char digest[CC_SHA1_DIGEST_LENGTH];
unsigned i;
LOG_ENTRY();
CC_SHA1_Init(&ctx);
CC_SHA1_Update(&ctx, cert->data, cert->length);
CC_SHA1_Final(digest, &ctx);
cpOut = outstr = (char *)malloc((2 * CC_SHA1_DIGEST_LENGTH) + 1);
if(outstr == NULL)
return NULL;
for(i = 0; i < CC_SHA1_DIGEST_LENGTH; i++, cpOut += 2)
sprintf(cpOut, "%02X", (unsigned)digest[i]);
*cpOut = '\0';
return outstr;
#elif defined(_WIN32)
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
char *outstr = NULL;
char *outpos;
size_t cch_left;
BYTE *hash = NULL;
DWORD hashSize = 0;
DWORD len, i;
LOG_ENTRY();
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_SIG, CRYPT_VERIFYCONTEXT)) {
LOG_LASTERROR("CryptAcquireContext failed");
goto done;
}
if (!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash)) {
LOG_LASTERROR("CryptCreateHash failed");
goto done;
}
if (!CryptHashData(hHash, (BYTE *) cert->data, cert->length, 0)) {
LOG_LASTERROR("CryptHashData failed");
goto done;
}
len = sizeof(hashSize);
if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *) &hashSize, &len, 0)) {
LOG_LASTERROR("CryptGetHashParam failed while getting hash size");
goto done;
}
hash = malloc(hashSize);
if (hash == NULL) {
goto done;
}
len = hashSize;
if (!CryptGetHashParam(hHash, HP_HASHVAL, hash, &len, 0)) {
LOG_LASTERROR("CryptGetHashParam failed while getting hash");
goto done;
}
outstr = malloc(hashSize * 2 + 1);
if (outstr == NULL) {
goto done;
}
outpos = outstr;
cch_left = hashSize * 2 + 1;
for (i = 0; i < hashSize; i++) {
StringCchPrintfExA(outpos, cch_left, &outpos, &cch_left, STRSAFE_FILL_ON_FAILURE,
"%02X", (unsigned) hash[i]);
}
*outpos = '\0';
done:
if (hHash != 0)
CryptDestroyHash(hHash);
if (hProv != 0)
CryptReleaseContext(hProv, 0);
if (hash != NULL)
free(hash);
return outstr;
#endif
}
示例15: isc_entropy_createfilesource
isc_result_t
isc_entropy_createfilesource(isc_entropy_t *ent, const char *fname) {
isc_result_t ret;
isc_entropysource_t *source;
HCRYPTPROV hcryptprov;
DWORD errval;
BOOL err;
REQUIRE(VALID_ENTROPY(ent));
REQUIRE(fname != NULL);
LOCK(&ent->lock);
source = NULL;
/*
* The first time we just try to acquire the context
*/
err = CryptAcquireContext(&hcryptprov, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT);
if (!err){
errval = GetLastError();
ret = ISC_R_IOERROR;
goto errout;
}
source = isc_mem_get(ent->mctx, sizeof(isc_entropysource_t));
if (source == NULL) {
ret = ISC_R_NOMEMORY;
goto closecontext;
}
/*
* From here down, no failures can occur.
*/
source->magic = SOURCE_MAGIC;
source->type = ENTROPY_SOURCETYPE_FILE;
source->ent = ent;
source->total = 0;
source->bad = ISC_FALSE;
memset(source->name, 0, sizeof(source->name));
ISC_LINK_INIT(source, link);
source->sources.file.handle = hcryptprov;
/*
* Hook it into the entropy system.
*/
ISC_LIST_APPEND(ent->sources, source, link);
ent->nsources++;
UNLOCK(&ent->lock);
return (ISC_R_SUCCESS);
closecontext:
CryptReleaseContext(hcryptprov, 0);
errout:
if (source != NULL)
isc_mem_put(ent->mctx, source, sizeof(isc_entropysource_t));
UNLOCK(&ent->lock);
return (ret);
}