您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ CryptEncrypt函数代码示例

51自学网 2021-06-01 20:15:38
  C++
这篇教程C++ CryptEncrypt函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中CryptEncrypt函数的典型用法代码示例。如果您正苦于以下问题:C++ CryptEncrypt函数的具体用法?C++ CryptEncrypt怎么用?C++ CryptEncrypt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了CryptEncrypt函数的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: exsltCryptoCryptoApiRc4Encrypt

voidexsltCryptoCryptoApiRc4Encrypt (xmlXPathParserContextPtr ctxt,				const unsigned char *key,				const unsigned char *msg, int msglen,				unsigned char *dest, int destlen) {    HCRYPTPROV hCryptProv;    HCRYPTKEY hKey;    HCRYPTHASH hHash;    DWORD dwDataLen;    unsigned char hash[HASH_DIGEST_LENGTH];    if (msglen > destlen) {	xsltTransformError (xsltXPathGetTransformContext (ctxt), NULL,			    NULL,			    "exslt:crypto : internal error exsltCryptoCryptoApiRc4Encrypt dest buffer too small./n");	return;    }    if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL,			      CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {	exsltCryptoCryptoApiReportError (ctxt, __LINE__);	return;    }    hHash = exsltCryptoCryptoApiCreateHash (ctxt, hCryptProv,					    CALG_SHA1, key,					    RC4_KEY_LENGTH, hash,					    HASH_DIGEST_LENGTH);    if (!CryptDeriveKey	(hCryptProv, CALG_RC4, hHash, 0x00800000, &hKey)) {	exsltCryptoCryptoApiReportError (ctxt, __LINE__);	goto fail;    }/* Now encrypt data. */    dwDataLen = msglen;    memcpy (dest, msg, msglen);    if (!CryptEncrypt (hKey, 0, TRUE, 0, dest, &dwDataLen, msglen)) {	exsltCryptoCryptoApiReportError (ctxt, __LINE__);	goto fail;    }  fail:    if (0 != hHash) {	CryptDestroyHash (hHash);    }    CryptDestroyKey (hKey);    CryptReleaseContext (hCryptProv, 0);}
开发者ID:ArielleBassanelli,项目名称:gempak,代码行数:50,


示例2: crypto_cipher_encrypt

int crypto_cipher_encrypt(struct crypto_cipher *ctx, const u8 *plain,			  u8 *crypt, size_t len){	DWORD dlen;	os_memcpy(crypt, plain, len);	dlen = len;	if (!CryptEncrypt(ctx->key, 0, FALSE, 0, crypt, &dlen, len)) { 		cryptoapi_report_error("CryptEncrypt");		os_memset(crypt, 0, len);		return -1;	}	return 0;}
开发者ID:09sea98,项目名称:rtl8188eu,代码行数:15,


示例3: CreateCryptBlock

// Create or update a cryptographic context for a pager.// This function will automatically determine if the encryption algorithm requires// extra padding, and if it does, will create a temp buffer big enough to provide// space to hold it.static LPCRYPTBLOCK CreateCryptBlock(HCRYPTKEY hKey, Pager *pager, int pageSize, LPCRYPTBLOCK pExisting){  LPCRYPTBLOCK pBlock;  if (!pExisting) // Creating a new cryptblock  {    pBlock = sqlite3_malloc(sizeof(CRYPTBLOCK));    if (!pBlock) return NULL;    ZeroMemory(pBlock, sizeof(CRYPTBLOCK));    pBlock->hReadKey = hKey;    pBlock->hWriteKey = hKey;  }  else // Updating an existing cryptblock  {    pBlock = pExisting;  }  if (pageSize == -1)    pageSize = pager->pageSize;  pBlock->pPager = pager;  pBlock->dwPageSize = (DWORD)pageSize;  pBlock->dwCryptSize = pBlock->dwPageSize;  // Existing cryptblocks may have a buffer, if so, delete it  if (pBlock->pvCrypt)  {    sqlite3_free(pBlock->pvCrypt);    pBlock->pvCrypt = NULL;  }  // Figure out how big to make our spare crypt block  CryptEncrypt(hKey, 0, TRUE, 0, NULL, &pBlock->dwCryptSize, pBlock->dwCryptSize * 2);  pBlock->pvCrypt = sqlite3_malloc(pBlock->dwCryptSize + (CRYPT_OFFSET * 2));  if (!pBlock->pvCrypt)  {    // We created a new block in here, so free it.  Otherwise leave the original intact    if (pBlock != pExisting)       sqlite3_free(pBlock);    return NULL;  }  return pBlock;}
开发者ID:AugustoAngeletti,项目名称:blockspaces,代码行数:50,


示例4: create_des_key

static HCRYPTKEY create_des_key(unsigned char *key) {    HCRYPTKEY hSessionKey, hPrivateKey;    DWORD dlen = 8;    BLOBHEADER *pbh;    char buf[sizeof(BLOBHEADER) + sizeof(ALG_ID) + 256];    /*     * Need special private key to encrypt session key so we can     * import session key, since only encrypted session keys can be     * imported     */    if(CryptImportKey(hCryptProv, PrivateKeyWithExponentOfOne,		      sizeof(PrivateKeyWithExponentOfOne),		      0, 0, &hPrivateKey) == 0)	return 0;    /* now encrypt session key using special private key */    memcpy(buf + sizeof(BLOBHEADER) + sizeof(ALG_ID), key, 8);    if(CryptEncrypt(hPrivateKey, 0, TRUE, 0,		    buf + sizeof(BLOBHEADER) + sizeof(ALG_ID),		    &dlen, 256) == 0)	return 0;    /* build session key blob */    pbh = (BLOBHEADER*)buf;    pbh->bType = SIMPLEBLOB;    pbh->bVersion = 0x02;    pbh->reserved = 0;    pbh->aiKeyAlg = CALG_DES;    *((ALG_ID*)(buf+sizeof(BLOBHEADER))) = CALG_RSA_KEYX;    /* import session key into key container */    if(CryptImportKey(hCryptProv, buf,		      dlen + sizeof(BLOBHEADER) + sizeof(ALG_ID),		      hPrivateKey, 0, &hSessionKey) == 0)	return 0;    if(hPrivateKey)	CryptDestroyKey(hPrivateKey);    return hSessionKey;}
开发者ID:rdebath,项目名称:sgt,代码行数:44,


示例5: DWORD

std::string CStringUtils::Encrypt(const std::string& s, const std::string& password){    std::string encryptedstring;    HCRYPTPROV hProv = NULL;    // Get handle to user default provider.    if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))    {        HCRYPTHASH hHash = NULL;        // Create hash object.        if (CryptCreateHash(hProv, CALG_SHA_512, 0, 0, &hHash))        {            // Hash password string.            DWORD dwLength = DWORD(sizeof(WCHAR)*password.size());            if (CryptHashData(hHash, (BYTE *)password.c_str(), dwLength, 0))            {                // Create block cipher session key based on hash of the password.                HCRYPTKEY hKey = NULL;                if (CryptDeriveKey(hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey))                {                    // Determine number of bytes to encrypt at a time.                    std::string starname = "*";                    starname += s;                    dwLength = (DWORD)starname.size();                    std::unique_ptr<BYTE[]> buffer(new BYTE[dwLength + 1024]);                    memcpy(buffer.get(), starname.c_str(), dwLength);                    // Encrypt data                    if (CryptEncrypt(hKey, 0, true, 0, buffer.get(), &dwLength, dwLength + 1024))                    {                        encryptedstring = CStringUtils::ToHexString(buffer.get(), dwLength);                    }                    CryptDestroyKey(hKey);  // Release provider handle.                }            }            CryptDestroyHash(hHash);        }        CryptReleaseContext(hProv, 0);    }    else        DebugBreak();    return encryptedstring;}
开发者ID:Kasper8660,项目名称:tortoisesvn,代码行数:43,


示例6: CryptEncrypt

bool Crypt::Encrypt( PBYTE data, DWORD length ){	// Encrypt the data.	DWORD dwLength = length;	BOOL fReturn = CryptEncrypt(		m_SessionKeyEn,		0,		TRUE,		0,		data,		&length,		length );	if ( !fReturn )	{		printf( "Encrypt error : %d/n", GetLastError() );		ReleaseResources();		return false;	}	return true;}
开发者ID:wooq17,项目名称:NHNNEXT_2014_GAME_SERVER,代码行数:21,


示例7: memset

CString Crytography ::Encrypt(CString mes){				CString m_cipher;		unsigned long length = mes.GetLength() +1;		unsigned char * cipherBlock = (unsigned char*)malloc(length);		memset(cipherBlock, 0, length);		memcpy(cipherBlock, mes, length -1);			if (!CryptEncrypt(hKey, 0, TRUE, 0, cipherBlock, &length, length))		{			//dwResult = GetLastError();			AfxMessageBox("Error CryptEncrypt() failed.", MB_OK);			return "";		}		m_cipher = cipherBlock;		//m_clear = "";		free(cipherBlock);		//		return m_cipher;}
开发者ID:hksonngan,项目名称:mytesgnikrow,代码行数:23,


示例8: RSA_encrypt

/** * Encrypts a small block of data with an RSA public key. * Output buffer must be at least the key size. */int RSA_encrypt(RSA_key_t rsa, const unsigned char *from, int fromlen,                unsigned char *to, int *tolen){    DWORD _tolen;    int flags;    unsigned int i;    unsigned char *outbuf;    if (RSA_keylen(rsa) * 8 < 768) {        flags = 0;    } else {        flags = CRYPT_OAEP;    }    outbuf = calloc(RSA_keylen(rsa), 1);    if (outbuf == NULL) {        syserror(0, 0, "calloc failed!");        exit(1);    }    memcpy(outbuf, from, fromlen);    _tolen = fromlen;    if (!CryptEncrypt(rsa, 0, 1, flags, outbuf, &_tolen, RSA_keylen(rsa))) {        mserror("CryptEncrypt failed");        free(outbuf);        return 0;    }    *tolen = _tolen;    // CryptoAPI returns ciphertext in little endian, so reverse the bytes    for (i = 0; i < _tolen; i++) {        to[i] = outbuf[_tolen - i - 1];    }    free(outbuf);    return 1;}
开发者ID:b-cuts,项目名称:uftp,代码行数:40,


示例9: good1

/* good1() uses the GoodSinkBody in the for statements */static void good1(){    int k;    for(k = 0; k < 1; k++)    {        {            BYTE payload[100];            DWORD payloadLen = strlen(PAYLOAD);            HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL;            HCRYPTHASH hHash = (HCRYPTHASH)NULL;            HCRYPTKEY hKey = (HCRYPTKEY)NULL;            char hashData[100] = HASH_INPUT;            do            {                /* Copy plaintext into payload buffer */                memcpy(payload, PAYLOAD, payloadLen);                /* 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;                }                /* FIX: All required steps are present */                /* 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;                }                /* Encrypt the payload */                if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload)))                {                    break;                }            }            while (0);            if (hKey)            {                CryptDestroyKey(hKey);            }            if (hHash)            {                CryptDestroyHash(hHash);            }            if (hCryptProv)            {                CryptReleaseContext(hCryptProv, 0);            }            /* Do something with the encrypted data */            printBytesLine(payload, payloadLen);        }    }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:62,


示例10: WriteDebugInfo

//.........这里部分代码省略.........for(i=0;i<dwCount;i++) printf("%2.2x ",pbData[i]);printf("/n");// Read the initialization vector.dwCount = 16;if(!CryptGetKeyParam(hKey, KP_IV, pbData, &dwCount, 0)) {    printf("Error %x during CryptGetKeyParam!/n", GetLastError());    return 1;}// Print out the initialization vector.printf("Default IV:");for(i=0;i<dwCount;i++) printf("%2.2x ",pbData[i]);printf("/n");// Set the cipher mode.dwMode = CRYPT_MODE_OFB;if(!CryptSetKeyParam(hKey, KP_MODE, (BYTE *)&dwMode, 0)) {    printf("Error %x during CryptSetKeyParam!/n", GetLastError());    return 1;}// Read the cipher mode.dwCount = sizeof(DWORD);if(!CryptGetKeyParam(hKey, KP_MODE, (BYTE *)&dwMode, &dwCount, 0)) {    printf("Error %x during CryptGetKeyParam!/n", GetLastError());    return 1;}// Print out the cipher mode.printf("Default cipher mode: %d/n", dwMode);dwCount = 16;BYTE pbIV[17];CryptGenRandom(hProvider, dwCount, pbIV);if(!CryptSetKeyParam(hKey, KP_IV, pbIV, 0)) {    printf("Error %x during CryptGetKeyParam!/n", GetLastError());    return 1;}// Read the initialization vector.dwCount = 16;if(!CryptGetKeyParam(hKey, KP_IV, pbData, &dwCount, 0)) {    printf("Error %x during CryptGetKeyParam!/n", GetLastError());    return 1;}// Print out the initialization vector.printf("Default IV:");for(i=0;i<dwCount;i++) printf("%2.2x ",pbData[i]);printf("/n");if(!CryptSetKeyParam(hKey, KP_SALT, pbIV, 0)) {    printf("Error %x during CryptGetKeyParam!/n", GetLastError());    return 1;}// Read the salt.dwCount = 16;if(!CryptGetKeyParam(hKey, KP_SALT, pbData, &dwCount, 0)) {    printf("Error %x during CryptGetKeyParam!/n", GetLastError());    return 1;}// Print out the initialization vector.printf("Default IV:");for(i=0;i<dwCount;i++) printf("%2.2x ",pbData[i]);printf("/n");////////////////////////////////////////////	strcpy((char *)pbBuffer, test);	DebugLog((DEST,"%s",(char *)pbBuffer));	dwByteCount = strlen((char *)pbBuffer);	rc = CryptEncrypt(hKey, 0, finished, 0, pbBuffer, &dwByteCount, OUT_BUFFER_SIZE);	DebugLog((DEST,"Encrypted buffer"));	rc = CryptDecrypt(hKey, 0, finished, 0, pbBuffer, &dwByteCount);	DebugLog((DEST,"Decrypted buffer"));	DebugLog((DEST,"%s",(char *)pbBuffer));	if (strcmp((char *)pbBuffer,test) ==0)	{		DebugLog((DEST,"Encrypt/Decrypt Succeeded"));	}	else	{		DebugLog((DEST,"Encrypt/Decrypt Failed"));	}	CleanupCryptoKey(hExchangeKey);    CleanupCryptoKey(hKey);	CleanupCryptoContext(hProvider);	DebugLog((DEST,"Listing Providers."));	ListProviders();      return(0);}
开发者ID:FrantisekKlika,项目名称:UltraVncAsDll,代码行数:101,


示例11: Encrypt

int Encrypt(char * inFile, char * outFile, char * keyFile) {		const IN_BUFFER_SIZE    = 2048;	const OUT_BUFFER_SIZE   = IN_BUFFER_SIZE + 64; // extra padding	HANDLE     hInFile; 	HANDLE     hOutFile;	HANDLE	   hKeyFile;    BYTE       pbBuffer[OUT_BUFFER_SIZE];	BOOL          finished;    HCRYPTPROV    hProvider = 0;    HCRYPTKEY     hKey = 0, hExchangeKey = 0;    DWORD         dwByteCount, dwBytesWritten;	long	rc=0;     // Open infile and create outfile.     hInFile = CreateFile(inFile, GENERIC_READ, FILE_SHARE_READ,          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);     hOutFile = CreateFile(outFile, GENERIC_WRITE, FILE_SHARE_READ,          NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);		DebugLog((DEST,"PrepContext"));	 PrepContext(iWinVer, &hProvider);     hKeyFile = CreateFile(keyFile, GENERIC_READ, FILE_SHARE_READ,          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);		DebugLog((DEST,"ImportCryptKey"));	ImportCryptKey(hProvider, &hKey, hKeyFile);DWORD	dwCount = 11;BYTE pbIV[11];//CryptGenRandom(hProvider, dwCount, pbIV);strcpy((char *)pbIV,"12345678901");if(!CryptSetKeyParam(hKey, KP_SALT, pbIV, 0)) {    printf("Error %x during CryptGetKeyParam!/n", GetLastError());    return 1;}   // Now, read data in, encrypt it, and write encrypted data to output.          do           {               ReadFile(hInFile, pbBuffer, IN_BUFFER_SIZE,&dwByteCount,NULL);               finished = (dwByteCount < IN_BUFFER_SIZE);               rc = CryptEncrypt(hKey, 0, finished, 0, pbBuffer, &dwByteCount,                           OUT_BUFFER_SIZE);				PrintLog((DEST,"Finished = %d ",finished));               WriteFile(hOutFile, pbBuffer, dwByteCount, &dwBytesWritten,                         NULL);          } while (!finished);   //And we’re finished   //almost. All we need to do now is clean up. We’re finished with both keys at this point, so let’s delete them.   // Clean up: release handles, close files.	CleanupCryptoKey(hExchangeKey);    CleanupCryptoKey(hKey);   //We’re finished using the CSP handle, so we must release it. We close the input and output files, and we’re finished.   CleanupCryptoContext(hProvider);   CloseHandle(hInFile);   CloseHandle(hOutFile);   return (0);}
开发者ID:FrantisekKlika,项目名称:UltraVncAsDll,代码行数:69,


示例12: CWE321_Hard_Coded_Cryptographic_Key__w32_char_64b_goodG2BSink

/* goodG2B uses the GoodSource with the BadSink */void CWE321_Hard_Coded_Cryptographic_Key__w32_char_64b_goodG2BSink(void * cryptoKeyVoidPtr){    /* cast void pointer to a pointer of the appropriate type */    char * * cryptoKeyPtr = (char * *)cryptoKeyVoidPtr;    /* dereference cryptoKeyPtr into cryptoKey */    char * cryptoKey = (*cryptoKeyPtr);    {        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);        }    }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:66,


示例13: rsaencrypt

void rsaencrypt(unsigned char *data, int length, struct RSAKey *rsakey) {    int i;    unsigned char *pKeybuf, *pKeyin;    HCRYPTKEY hRsaKey;    PUBLICKEYSTRUC *pBlob;    RSAPUBKEY *pRPK;    unsigned char *buf;    DWORD dlen;    DWORD bufsize;    /* allocate buffer for public key blob */    if((pBlob = malloc(sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY) +		       rsakey->bytes)) == NULL)	fatalbox("Out of memory");    /* allocate buffer for message encryption block */    bufsize = (length + rsakey->bytes) << 1;    if((buf = malloc(bufsize)) == NULL)	fatalbox("Out of memory");    /* construct public key blob from host public key */    pKeybuf = ((unsigned char*)pBlob) + sizeof(PUBLICKEYSTRUC) +	sizeof(RSAPUBKEY);    pKeyin = ((unsigned char*)rsakey->modulus);    /* change big endian to little endian */    for(i=0; i<rsakey->bytes; i++)	pKeybuf[i] = pKeyin[rsakey->bytes-i-1];    pBlob->bType = PUBLICKEYBLOB;    pBlob->bVersion = 0x02;    pBlob->reserved = 0;    pBlob->aiKeyAlg = CALG_RSA_KEYX;    pRPK = (RSAPUBKEY*)(((unsigned char*)pBlob) + sizeof(PUBLICKEYSTRUC));    pRPK->magic = 0x31415352; /* "RSA1" */    pRPK->bitlen = rsakey->bits;    pRPK->pubexp = rsakey->exponent;    /* import public key blob into key container */    if(CryptImportKey(hCryptProv, (void*)pBlob,		      sizeof(PUBLICKEYSTRUC)+sizeof(RSAPUBKEY)+rsakey->bytes,		      0, 0, &hRsaKey) == 0)	fatalbox("Error importing RSA key!");    /* copy message into buffer */    memcpy(buf, data, length);    dlen = length;    /* using host public key, encrypt the message */    if(CryptEncrypt(hRsaKey, 0, TRUE, 0, buf, &dlen, bufsize) == 0)	fatalbox("Error encrypting using RSA key!");    /*     * For some strange reason, Microsoft CryptEncrypt using public     * key, returns the cyphertext in backwards (little endian)     * order, so reverse it!     */    for(i = 0; i < (int)dlen; i++)	data[i] = buf[dlen - i - 1]; /* make it big endian */    CryptDestroyKey(hRsaKey);    free(buf);    free(pBlob);}
开发者ID:rdebath,项目名称:sgt,代码行数:64,


示例14: MyHandleError

//.........这里部分代码省略.........	} else {		ltemp = 0;		fread (&ltemp, 1, sizeof (unsigned long), hSource);		fread (&ltemp, 1, sizeof (unsigned long), hSource);		fread (&ltemp, 1, sizeof (unsigned long), hSource);		fread (&ltemp, 1, sizeof (unsigned long), hSource);	}	//-------------------------------------------------------------------	// In a do loop, encrypt the source file, 	// and write to the source file. 	m_lastprogressvalue = 0;	m_bmaxprogressredone = false;	m_ispeedtrigger = 0;	unsigned long ltimereading = 0;	unsigned long long lbytesreading = 0;	int ispeed = 0;	int iaverage = 0;	m_lastbytesreading = 0;	m_lasttimereading = 0;	do 	{ 		//-------------------------------------------------------------------		// Read up to dwBlockLen bytes from the source file. 		dwCount = fread(pbBuffer, 1, dwBlockLen, hSource); 		if(ferror(hSource)) { 			MyHandleError("Error reading plaintext!");			return false;		}	 		//-------------------------------------------------------------------		// Encrypt / Decrypt data.		if (bEncrypt == true) {			if(!CryptEncrypt(hKey, 0, feof(hSource), 0, pbBuffer, &dwCount, dwBufferLen)) {			   MyHandleError("Error during Encrypt.");			   return false;			}				} else {			if(!CryptDecrypt(hKey, 0, feof(hSource), 0, pbBuffer, &dwCount)) {			   MyHandleError("Error during Decrypt.");			   return false;			}		}		//-------------------------------------------------------------------		// Write data to the destination file. 		fwrite(pbBuffer, 1, dwCount, hDestination); 		ltotalbytesprocessed+=dwCount;		//OutputInt ("ltotalprocessed: ", ltotalbytesprocessed);		int idivvalue = 1000;		if (ltotalbytes > 0 && ltotalbytes <= 1000) {			idivvalue = 1;		}		if (ltotalbytes > 1000 && ltotalbytes <= 10000) {			idivvalue = 10;		}		if (ltotalbytes > 10000 && ltotalbytes <= 100000) {			idivvalue = 100;		}		if (ltotalbytes > 100000 && ltotalbytes <= 1000000) {			idivvalue = 1000;
开发者ID:dannydraper,项目名称:CedeCryptPortable,代码行数:67,


示例15: des_encrypt_blk

void des_encrypt_blk(unsigned char *blk, int len) {    DWORD dlen;    dlen = len;    if(CryptEncrypt(hDESKey[0][0], 0, FALSE, 0, blk, &dlen, len + 8) == 0)	fatalbox("Error encrypting block!/n");}
开发者ID:rdebath,项目名称:sgt,代码行数:6,


示例16: des_encrypt

void des_encrypt(const u8 *clear, const u8 *key, u8 *cypher){	u8 next, tmp;	int i;	HCRYPTPROV prov;	HCRYPTKEY ckey;	DWORD dlen;	struct {		BLOBHEADER hdr;		DWORD len;		BYTE key[8];	} key_blob;	DWORD mode = CRYPT_MODE_ECB;	key_blob.hdr.bType = PLAINTEXTKEYBLOB;	key_blob.hdr.bVersion = CUR_BLOB_VERSION;	key_blob.hdr.reserved = 0;	key_blob.hdr.aiKeyAlg = CALG_DES;	key_blob.len = 8;	/* Add parity bits to the key */	next = 0;	for (i = 0; i < 7; i++) {		tmp = key[i];		key_blob.key[i] = (tmp >> i) | next | 1;		next = tmp << (7 - i);	}	key_blob.key[i] = next | 1;	if (!CryptAcquireContext(&prov, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL,				 CRYPT_VERIFYCONTEXT)) { 		wpa_printf(MSG_DEBUG, "CryptoAPI: CryptAcquireContext failed: "			   "%d", (int) GetLastError());		return;	}	if (!CryptImportKey(prov, (BYTE *) &key_blob, sizeof(key_blob), 0, 0,			    &ckey)) { 		wpa_printf(MSG_DEBUG, "CryptoAPI: CryptImportKey failed: %d",			   (int) GetLastError());		CryptReleaseContext(prov, 0);		return;	}	if (!CryptSetKeyParam(ckey, KP_MODE, (BYTE *) &mode, 0)) { 		wpa_printf(MSG_DEBUG, "CryptoAPI: CryptSetKeyParam(KP_MODE) "			   "failed: %d", (int) GetLastError());		CryptDestroyKey(ckey);		CryptReleaseContext(prov, 0);		return;	}	os_memcpy(cypher, clear, 8);	dlen = 8;	if (!CryptEncrypt(ckey, 0, FALSE, 0, cypher, &dlen, 8)) {		wpa_printf(MSG_DEBUG, "CryptoAPI: CryptEncrypt failed: %d",			   (int) GetLastError());		os_memset(cypher, 0, 8);	}	CryptDestroyKey(ckey);	CryptReleaseContext(prov, 0);}
开发者ID:09sea98,项目名称:rtl8188eu,代码行数:63,


示例17: EncryptDecryptFile

//.........这里部分代码省略.........        {            // Read in key block size, then key blob itself from input file.            fResult = ReadFile(hInFile, &dwByteCount, sizeof(dwByteCount),                               &dwBytesRead, NULL);            if (!fResult)            {                MyPrintf(_T("ReadFile failed with %d/n"), GetLastError());                __leave;            }            fResult = ReadFile(hInFile, pbBuffer, dwByteCount, &dwBytesRead, NULL);            if (!fResult)            {                MyPrintf(_T("ReadFile failed with %d/n"), GetLastError());                __leave;            }            // import key blob into "CSP"            fResult = CryptImportKey(hProv, pbBuffer, dwByteCount, hRSAKey, 0, &hSessionKey);            if (!fResult)            {                MyPrintf(_T("CryptImportKey failed with %X/n"), GetLastError());                __leave;            }        }        do        {            dwByteCount = 0;            // Now read data from the input file 64K bytes at a time.            fResult = ReadFile(hInFile, pbBuffer, IN_BUFFER_SIZE, &dwByteCount, NULL);            // If the file size is exact multiple of 64K, dwByteCount will be zero after            // all the data has been read from the input file. In this case, simply break            // from the while loop. The check to do this is below            if (dwByteCount == 0)                break;            if (!fResult)            {                MyPrintf(_T("ReadFile failed with %d/n"), GetLastError());                __leave;            }            finished = (dwByteCount < IN_BUFFER_SIZE);            // Encrypt/Decrypt depending on the required action.            if (fEncrypt)            {                fResult = CryptEncrypt(hSessionKey, 0, finished, 0, pbBuffer, &dwByteCount,                                       OUT_BUFFER_SIZE);                if (!fResult)                {                    MyPrintf(_T("CryptEncrypt failed with %X/n"), GetLastError());                    __leave;                }            }            else            {                fResult = CryptDecrypt(hSessionKey, 0, finished, 0, pbBuffer, &dwByteCount);                if (!fResult)                {                    MyPrintf(_T("CryptDecrypt failed with %X/n"), GetLastError());                    __leave;                }            }            // Write the encrypted/decrypted data to the output file.            fResult = WriteFile(hOutFile, pbBuffer, dwByteCount,                                &dwBytesWritten, NULL);            if (!fResult)            {                MyPrintf(_T("WriteFile failed with %d/n"), GetLastError());                __leave;            }        } while (!finished);        if (fEncrypt)            MyPrintf(_T("File %s is encrypted successfully!/n"), lpszInputFileName);        else            MyPrintf(_T("File %s is decrypted successfully!/n"), lpszInputFileName);        fSuccess = TRUE;    }    __finally    {        /* Cleanup */        CheckAndLocalFree(pbSessionKeyBlob);        if (pCertContext != NULL) CertFreeCertificateContext(pCertContext);        if (hRSAKey != NULL) CryptDestroyKey(hRSAKey);        if (hSessionKey != NULL) CryptDestroyKey(hSessionKey);        if (fCallerFreeProv && hProv != NULL) CryptReleaseContext(hProv, 0);        if (hInFile != INVALID_HANDLE_VALUE) CloseHandle(hInFile);        if (hOutFile != INVALID_HANDLE_VALUE) CloseHandle(hOutFile);    }    return fSuccess;}
开发者ID:dbremner,项目名称:Windows-classic-samples,代码行数:101,


示例18: EncryptPassword

byte* EncryptPassword(byte* blob, DWORD* size, const char* masterPassword, const char* salt, HWND hwndParent) {  HCRYPTPROV csp = NULL;  HCRYPTHASH hash = NULL;  HCRYPTKEY key = NULL;  if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, 0)) {    if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {	    MessageBoxA(hwndParent, "Could not create key container!", "ChromePasswords", MB_ICONERROR);      return NULL;    }  }  if (!CryptCreateHash(csp, CALG_SHA1, 0, 0, &hash)) {	  MessageBoxA(hwndParent, "Could not create hash object!", "ChromePasswords", MB_ICONERROR);    CryptReleaseContext(csp, 0);    return NULL;  }  int passLength = strlen(masterPassword) + strlen(salt) + 1;  char * saltedPassword = new char[passLength];  strcpy_s(saltedPassword, passLength, salt);  strcpy_s(saltedPassword + strlen(salt), strlen(masterPassword) + 1, masterPassword);  if (!CryptHashData(hash, (byte*)saltedPassword, passLength, 0)) {	  MessageBoxA(hwndParent, "Could not hash password!", "ChromePasswords", MB_ICONERROR);    SecureZeroMemory(saltedPassword, passLength);    delete[] saltedPassword;    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    return NULL;  }  SecureZeroMemory(saltedPassword, passLength);  delete[] saltedPassword;  if (!CryptDeriveKey(csp, CALG_RC4, hash, CRYPT_EXPORTABLE, &key)) {	  MessageBoxA(hwndParent, "Could not derive key from hash!", "ChromePasswords", MB_ICONERROR);    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    return NULL;  }  DWORD encSize = *size;  if (!CryptEncrypt(key, NULL, TRUE, 0, NULL, &encSize, encSize)) {	  MessageBoxA(hwndParent, "Could not get the size of the encrypted password!", "ChromePasswords", MB_ICONERROR);    CryptDestroyKey(key);    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    return NULL;  }  byte* text = new byte[encSize];  memcpy(text, blob, *size);  if (!CryptEncrypt(key, NULL, TRUE, 0, text, size, encSize)) {	  MessageBoxA(hwndParent, "Could not encrypt the password!", "ChromePasswords", MB_ICONERROR);    delete[] text;    CryptDestroyKey(key);    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    return NULL;  }  CryptDestroyKey(key);  CryptDestroyHash(hash);  CryptReleaseContext(csp, 0);  return text;}
开发者ID:Juxi,项目名称:OpenSignals,代码行数:73,


示例19: MyEncryptFile

//.........这里部分代码省略.........    {         MyHandleError(TEXT("Out of memory. /n"), E_OUTOFMEMORY);         goto Exit_MyEncryptFile;    }    //---------------------------------------------------------------    // In a do loop, encrypt the source file,     // and write to the source file.     bool fEOF = FALSE;    do     {         //-----------------------------------------------------------        // Read up to dwBlockLen bytes from the source file.         if(!ReadFile(            hSourceFile,             pbBuffer,             dwBlockLen,             &dwCount,             NULL))        {            MyHandleError(                TEXT("Error reading plaintext!/n"),                 GetLastError());            goto Exit_MyEncryptFile;        }        if(dwCount < dwBlockLen)        {            fEOF = TRUE;        }        //-----------------------------------------------------------        // Encrypt data.         if(!CryptEncrypt(            hKey,             NULL,             fEOF,            0,             pbBuffer,             &dwCount,             dwBufferLen))        {             MyHandleError(                TEXT("Error during CryptEncrypt. /n"),                 GetLastError());             goto Exit_MyEncryptFile;        }         //-----------------------------------------------------------        // Write the encrypted data to the destination file.         if(!WriteFile(            hDestinationFile,             pbBuffer,             dwCount,            &dwCount,            NULL))        {             MyHandleError(                TEXT("Error writing ciphertext./n"),                 GetLastError());            goto Exit_MyEncryptFile;        }        //-----------------------------------------------------------        // End the do loop when the last block of the source file         // has been read, encrypted, and written to the destination 
开发者ID:josh200501,项目名称:mycode_vs,代码行数:67,


示例20: _tmain

//.........这里部分代码省略.........                                    MS_DEF_PROV,                                     PROV_RSA_FULL,                                    CRYPT_VERIFYCONTEXT);      if (!fResult)      {         _tprintf(_T("CryptAcquireContext failed with %X/n"), GetLastError());         __leave;      }      fResult = CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);      if (!fResult)      {         _tprintf(_T("CryptCreateHash failed with %X/n"), GetLastError());         __leave;      }      // Hash the supplied secret password      fResult = CryptHashData(hHash, (LPBYTE)argv[1], (DWORD)_tcslen(argv[1]), 0);      if (!fResult)      {         _tprintf(_T("CryptHashData failed with %X/n"), GetLastError());         __leave;      }      // Derive a symmetric session key from password hash      fResult = CryptDeriveKey(hProv, CALG_RC4, hHash, 0, &hSessionKey);      if (!fResult)      {         _tprintf(_T("CryptDeriveKey failed with %X/n"), GetLastError());         __leave;      }      do      {         dwByteCount = 0;         // Now read data from the input file 64K bytes at a time.         fResult = ReadFile(hInFile, pbBuffer, IN_BUFFER_SIZE, &dwByteCount, NULL);         // If the file size is exact multiple of 64K, dwByteCount will be zero after         // all the data has been read from the input file. In this case, simply break         // from the while loop. The check to do this is below         if (dwByteCount == 0)            break;         if (!fResult)         {            _tprintf(_T("ReadFile failed with %d/n"), GetLastError());            __leave;         }         finished = (dwByteCount < IN_BUFFER_SIZE);         // Encrypt/Decrypt depending on the required action.         if (fEncrypt)         {            fResult = CryptEncrypt(hSessionKey, 0, finished, 0, pbBuffer, &dwByteCount,                           OUT_BUFFER_SIZE);            if (!fResult)            {               _tprintf(_T("CryptEncrypt failed with %X/n"), GetLastError());               __leave;            }         }         else         {            fResult = CryptDecrypt(hSessionKey, 0, finished, 0, pbBuffer, &dwByteCount);            if (!fResult)            {               _tprintf(_T("CryptDecrypt failed with %X/n"), GetLastError());               __leave;            }         }         // Write the encrypted/decrypted data to the output file.         fResult = WriteFile(hOutFile, pbBuffer, dwByteCount,            &dwBytesWritten, NULL);         if (!fResult)         {            _tprintf(_T("WriteFile failed with %d/n"), GetLastError());            __leave;         }      } while (!finished);      if (fEncrypt)         _tprintf(_T("File %s is encrypted successfully!/n"), argv[3]);      else         _tprintf(_T("File %s is decrypted successfully!/n"), argv[3]);   }   __finally   {      /* Cleanup */      if (hInFile != INVALID_HANDLE_VALUE) CloseHandle(hInFile);      if (hOutFile != INVALID_HANDLE_VALUE) CloseHandle(hOutFile);      if (hSessionKey != NULL) CryptDestroyKey(hSessionKey);      if (hHash != NULL) CryptDestroyHash(hHash);      if (hProv != NULL) CryptReleaseContext(hProv, 0);   }}
开发者ID:Essjay1,项目名称:Windows-classic-samples,代码行数:101,


示例21: CWE321_Hard_Coded_Cryptographic_Key__w32_char_06_bad

void CWE321_Hard_Coded_Cryptographic_Key__w32_char_06_bad(){    char * cryptoKey;    char cryptoKeyBuffer[100] = "";    cryptoKey = cryptoKeyBuffer;    if(STATIC_CONST_FIVE==5)    {        /* FLAW: Use a hardcoded value for the hash input causing a hardcoded crypto key in the sink */        strcpy(cryptoKey, CRYPTO_KEY);    }    {        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);        }    }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:69,


示例22: goodG2B2

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */static void goodG2B2(){    char * cryptoKey;    char cryptoKeyBuffer[100] = "";    cryptoKey = cryptoKeyBuffer;    if(STATIC_CONST_FIVE==5)    {        {            size_t cryptoKeyLen = strlen(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 (fgets(cryptoKey+cryptoKeyLen, (int)(100-cryptoKeyLen), stdin) == NULL)                {                    printLine("fgets() failed");                    /* Restore NUL terminator if fgets fails */                    cryptoKey[cryptoKeyLen] = '/0';                }                /* The next 3 lines remove the carriage return from the string that is                 * inserted by fgets() */                cryptoKeyLen = strlen(cryptoKey);                if (cryptoKeyLen > 0)                {                    cryptoKey[cryptoKeyLen-1] = '/0';                }            }        }    }    {        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);        }    }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:89,


示例23: aes_Encrypt

DWORD aes_Encrypt(LPBYTE key, DWORD SizeKey, LPBYTE iv, LPBYTE InData, DWORD SizeInData, LPBYTE *OutData){    HCRYPTPROV provider = NULL;    HCRYPTKEY hKey = NULL;    DWORD SizeData = SizeInData;    DWORD SizeBuffer = 0;    DWORD Result = -1;    do {        if (!OpenCryptContext(&provider)) {            xstrerror("CryptAcquireContext()");            break;        }        // 创建 Key        struct keyBlob {            BLOBHEADER hdr;            DWORD cbKeySize;            BYTE rgbKeyData[32];                // FOR AES-256 = 32        } keyBlob;        keyBlob.hdr.bType = PLAINTEXTKEYBLOB;        keyBlob.hdr.bVersion = CUR_BLOB_VERSION;        keyBlob.hdr.reserved = 0;        keyBlob.hdr.aiKeyAlg = CALG_AES_256;    // FOR AES-256 = CALG_AES_256        keyBlob.cbKeySize = 32;                    // FOR AES-256 = 32        CopyMemory(keyBlob.rgbKeyData, key, keyBlob.cbKeySize);        if (!CryptImportKey(provider, (BYTE*)(&keyBlob), sizeof(keyBlob), NULL, 0, &hKey)) {            break;        }        DWORD dwMode = CRYPT_MODE_CBC, dwPadding = PKCS5_PADDING;        if (!CryptSetKeyParam(hKey, KP_IV, (BYTE*)iv, 0)) {            break;        }        if (!CryptSetKeyParam(hKey, KP_MODE, reinterpret_cast<BYTE*>(&dwMode), 0)) {            break;        }        if (!CryptSetKeyParam(hKey, KP_PADDING, reinterpret_cast<BYTE*>(&dwPadding), 0)) {            break;        }        DWORD block_size = GetCipherBlockSize(hKey);        DWORD data_len = SizeInData;        SizeBuffer = data_len + block_size;        *OutData = (LPBYTE)xmalloc(SizeBuffer);        if (*OutData == NULL)            break;        memcpy(*OutData, InData, SizeInData);        if (!CryptEncrypt(hKey, NULL, TRUE, 0, *OutData, &SizeData, SizeBuffer)) {            xstrerror("CryptEncrypt()");            break;        }        Result = SizeData;    } while (0);    if (hKey != NULL) {        CryptDestroyKey(hKey);    }    if (provider != NULL)   {        CryptReleaseContext(provider, 0);    }    if (OutData != NULL && !Result)        xfree(*OutData);    return Result;}
开发者ID:ZhuHuiBeiShaDiao,项目名称:CryptoAPI-examples,代码行数:76,


示例24: encrypt_block

/** * Takes a block of data and encrypts it with a symmetric cypher. * The output buffer must be at least the size of source data + block size. */int encrypt_block(int keytype, const unsigned char *IV,                  const unsigned char *key,                  const unsigned char *src, unsigned int srclen,                  unsigned char *dest, unsigned int *destlen){    // TODO: right now we reimport the key each time.  Test to see if this    // is quick enough or if we need to cache an imported key.    HCRYPTKEY hckey;    char keyblob[BLOBLEN];    BLOBHEADER *bheader;    DWORD *keysize;    BYTE *keydata;    int bloblen, keylen, ivlen, rval;    ALG_ID alg;    DWORD mode, _destlen;    get_key_info(keytype, &keylen, &ivlen);    alg = get_cipher(keytype);    bheader = (BLOBHEADER *)keyblob;    keysize = (DWORD *)(keyblob + sizeof(BLOBHEADER));    keydata = (BYTE *)((char *)keysize + sizeof(DWORD));    memset(keyblob, 0, sizeof(keyblob));    bheader->bType = PLAINTEXTKEYBLOB;    bheader->bVersion = CUR_BLOB_VERSION;    bheader->aiKeyAlg = alg;    *keysize = keylen;    memcpy(keydata, key, keylen);    bloblen = sizeof(BLOBHEADER) + sizeof(DWORD) + keylen;    if (!CryptImportKey(base_prov, keyblob, bloblen, 0, 0, &hckey)) {        mserror("CryptImportKey failed");        return 0;    }    mode = CRYPT_MODE_CBC;    if (!CryptSetKeyParam(hckey, KP_MODE, (BYTE *)&mode, 0)) {        mserror("CryptSetKeyParam failed on KP_MODE");        rval = 0;        goto end;    }    if (!CryptSetKeyParam(hckey, KP_IV, IV, 0)) {        mserror("CryptSetKeyParam failed on KP_IV");        rval = 0;        goto end;    }    memcpy(dest, src, srclen);    _destlen = srclen;    if (!CryptEncrypt(hckey, 0, 1, 0, dest, &_destlen, srclen + ivlen)) {        mserror("CryptEncrypt failed");        rval = 0;        goto end;    }    *destlen = _destlen;    rval = 1;end:    if (!CryptDestroyKey(hckey)) {        mserror("CryptDestroyKey failed");    }    return rval;}
开发者ID:b-cuts,项目名称:uftp,代码行数:67,


示例25: stringdup

//.........这里部分代码省略.........    // set encryption mode to ECB    dwParam=CRYPT_MODE_ECB;    res = CryptSetKeyParam(        key,                      // key handle        KP_MODE,                   // set key mode flag        (unsigned char*) &dwParam, // new mode value        0                          // flags not used    );    if (res == FALSE) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    // set padding mode to PKCS5    dwParam=PKCS5_PADDING;    res = CryptSetKeyParam(        key,                      // key handle        KP_PADDING,                   // set key mode flag        (unsigned char*) &dwParam, // new mode value        0                          // flags not used    );    if (res == FALSE) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    // create big buffer    sizeOut = sizeIn;    // Get the size of the encrypted block    res = CryptEncrypt(        key,            // Key obtained earlier        0,              // No hashing of data        TRUE,           // Final or only buffer of data        0,              // Must be zero        NULL,           // No data this time        &sizeOut,       // Length of the source data        0               // Size of block    );    if ((res == FALSE) && (GetLastError() != ERROR_MORE_DATA)) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    // allocate and intialize the buffer    ret = new char[sizeOut];    memcpy(ret, data, sizeIn);    // Now encrypt the data    res = CryptEncrypt(        key,                 // Key obtained earlier        0,                   // No hashing of data        TRUE,                // Final or only buffer of data        0,                   // Must be zero        (unsigned char*)ret, // Data buffer        &sizeIn,             // Size of data        sizeOut              // Size of block    );    if (res == FALSE) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    info.size = sizeIn;    info.newReturnedData = true; exit:   // Destroy the session key.   if (key)     CryptDestroyKey (key);   // Destroy the hash object.   if (hash)     CryptDestroyHash (hash);   // Release the provider handle.   if (prov)     CryptReleaseContext (prov, 0);   if (password) {       delete [] password;   }   return ret;}
开发者ID:fieldwind,项目名称:syncsdk,代码行数:101,


示例26: xmlSecMSCryptoKWDes3BlockEncrypt

static intxmlSecMSCryptoKWDes3BlockEncrypt(void * context,                               const xmlSecByte * iv, xmlSecSize ivSize,                               const xmlSecByte * in, xmlSecSize inSize,                               xmlSecByte * out, xmlSecSize outSize) {    xmlSecMSCryptoKWDes3CtxPtr ctx = (xmlSecMSCryptoKWDes3CtxPtr)context;    DWORD dwBlockLen, dwBlockLenLen, dwCLen;    HCRYPTKEY cryptKey = 0;    int ret;    xmlSecAssert2(ctx != NULL, -1);    xmlSecAssert2(xmlSecBufferGetData(&(ctx->keyBuffer)) != NULL, -1);    xmlSecAssert2(xmlSecBufferGetSize(&(ctx->keyBuffer)) >= XMLSEC_KW_DES3_KEY_LENGTH, -1);    xmlSecAssert2(iv != NULL, -1);    xmlSecAssert2(ivSize >= XMLSEC_KW_DES3_IV_LENGTH, -1);    xmlSecAssert2(in != NULL, -1);    xmlSecAssert2(inSize > 0, -1);    xmlSecAssert2(out != NULL, -1);    xmlSecAssert2(outSize >= inSize, -1);    /* Import this key and get an HCRYPTKEY handle, we do it again and again        to ensure we don't go into CBC mode */    if (!xmlSecMSCryptoImportPlainSessionBlob(ctx->desCryptProvider,        ctx->pubPrivKey,        ctx->desAlgorithmIdentifier,        xmlSecBufferGetData(&ctx->keyBuffer),        xmlSecBufferGetSize(&ctx->keyBuffer),        TRUE,        &cryptKey))  {        xmlSecError(XMLSEC_ERRORS_HERE,                    NULL,                    "xmlSecMSCryptoImportPlainSessionBlob",                    XMLSEC_ERRORS_R_XMLSEC_FAILED,                    XMLSEC_ERRORS_NO_MESSAGE);        return(-1);    }    xmlSecAssert2(cryptKey != 0, -1);    /* iv len == block len */    dwBlockLenLen = sizeof(DWORD);    if (!CryptGetKeyParam(cryptKey, KP_BLOCKLEN, (BYTE *)&dwBlockLen, &dwBlockLenLen, 0)) {        xmlSecError(XMLSEC_ERRORS_HERE,                    NULL,                    "CryptGetKeyParam",                    XMLSEC_ERRORS_R_CRYPTO_FAILED,                    XMLSEC_ERRORS_NO_MESSAGE);        CryptDestroyKey(cryptKey);        return(-1);    }    /* set IV */    if((ivSize < dwBlockLen / 8) || (!CryptSetKeyParam(cryptKey, KP_IV, iv, 0))) {        xmlSecError(XMLSEC_ERRORS_HERE,                    NULL,                    "CryptSetKeyParam",                    XMLSEC_ERRORS_R_CRYPTO_FAILED,                    "ivSize=%d, dwBlockLen=%d",                     ivSize, dwBlockLen / 8);        CryptDestroyKey(cryptKey);        return(-1);    }    /* Set process last block to false, since we handle padding ourselves, and MSCrypto padding     * can be skipped. I hope this will work .... */    if(out != in) {        memcpy(out, in, inSize);    }    dwCLen = inSize;    if(!CryptEncrypt(cryptKey, 0, FALSE, 0, out, &dwCLen, outSize)) {        xmlSecError(XMLSEC_ERRORS_HERE,                    NULL,                    "CryptEncrypt",                    XMLSEC_ERRORS_R_CRYPTO_FAILED,                    XMLSEC_ERRORS_NO_MESSAGE);        CryptDestroyKey(cryptKey);        return(-1);    }    /* cleanup */    CryptDestroyKey(cryptKey);    return(dwCLen);}
开发者ID:KonstantinDavidov,项目名称:xmlsec,代码行数:83,


示例27: xmlSecMSCryptoRsaPkcs1Process

static int  xmlSecMSCryptoRsaPkcs1Process(xmlSecTransformPtr transform, xmlSecTransformCtxPtr transformCtx) {    xmlSecMSCryptoRsaPkcs1CtxPtr ctx;    xmlSecBufferPtr in, out;    xmlSecSize inSize, outSize;    xmlSecSize keySize;    int ret;    HCRYPTKEY hKey = 0;    DWORD dwInLen;    DWORD dwBufLen;    DWORD dwOutLen;    BYTE * outBuf;    BYTE * inBuf;    int i;    xmlSecAssert2(xmlSecTransformCheckId(transform, xmlSecMSCryptoTransformRsaPkcs1Id), -1);    xmlSecAssert2((transform->operation == xmlSecTransformOperationEncrypt) || (transform->operation == xmlSecTransformOperationDecrypt), -1);    xmlSecAssert2(xmlSecTransformCheckSize(transform, xmlSecMSCryptoRsaPkcs1Size), -1);    xmlSecAssert2(transformCtx != NULL, -1);    ctx = xmlSecMSCryptoRsaPkcs1GetCtx(transform);    xmlSecAssert2(ctx != NULL, -1);    xmlSecAssert2(ctx->data != NULL, -1);        keySize = xmlSecKeyDataGetSize(ctx->data) / 8;    xmlSecAssert2(keySize > 0, -1);        in = &(transform->inBuf);    out = &(transform->outBuf);	    inSize = xmlSecBufferGetSize(in);    outSize = xmlSecBufferGetSize(out);        xmlSecAssert2(outSize == 0, -1);	    /* the encoded size is equal to the keys size so we could not     * process more than that */    if((transform->operation == xmlSecTransformOperationEncrypt) && (inSize >= keySize)) {        xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,                    xmlSecErrorsSafeString(xmlSecTransformGetName(transform)),                    NULL,                    XMLSEC_ERRORS_R_INVALID_SIZE,                    "%d when expected less than %d", inSize, keySize);        return(-1);    } else if((transform->operation == xmlSecTransformOperationDecrypt) && (inSize != keySize)) {        xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,                    xmlSecErrorsSafeString(xmlSecTransformGetName(transform)),                    NULL,                    XMLSEC_ERRORS_R_INVALID_SIZE,                    "%d when expected %d", inSize, keySize);        return(-1);    }	    outSize = keySize;     ret = xmlSecBufferSetMaxSize(out, outSize);    if(ret < 0) {        xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,                     xmlSecErrorsSafeString(xmlSecTransformGetName(transform)),                    "xmlSecBufferSetMaxSize",                    XMLSEC_ERRORS_R_XMLSEC_FAILED,                    "size=%d", outSize);        return(-1);    }    if(transform->operation == xmlSecTransformOperationEncrypt) {	BYTE ch;	if(inSize > outSize) {	    xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, 			xmlSecErrorsSafeString(xmlSecTransformGetName(transform)),			NULL,			XMLSEC_ERRORS_R_INVALID_SIZE,			"inSize=%d;outSize=%d", 			inSize, outSize);	    return(-1);	}	ret = xmlSecBufferSetData(out, xmlSecBufferGetData(in), inSize);	if(ret < 0) {	    xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, 			xmlSecErrorsSafeString(xmlSecTransformGetName(transform)),			"xmlSecBufferSetData",			XMLSEC_ERRORS_R_XMLSEC_FAILED,			"size=%d", inSize);	    return(-1);	}        dwInLen = inSize;        dwBufLen = outSize;	if (0 == (hKey = xmlSecMSCryptoKeyDataGetKey(ctx->data, xmlSecKeyDataTypePublic))) {	    xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,                        NULL,                        "xmlSecMSCryptoKeyDataGetKey",                        XMLSEC_ERRORS_R_CRYPTO_FAILED,                        XMLSEC_ERRORS_NO_MESSAGE);            return (-1);	}        	outBuf = xmlSecBufferGetData(out);	xmlSecAssert2(outBuf != NULL, -1);	if (!CryptEncrypt(hKey, 0, TRUE, 0, outBuf, &dwInLen, dwBufLen)) {//.........这里部分代码省略.........
开发者ID:Arcenciel,项目名称:DDReader,代码行数:101,


示例28: bad

void bad(){    wchar_t * cryptoKey;    wchar_t cryptoKeyBuffer[100] = L"";    cryptoKey = cryptoKeyBuffer;    badSource(cryptoKey);    {        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,代码行数:65,



注:本文中的CryptEncrypt函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ CryptGenRandom函数代码示例
C++ CryptDestroyKey函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。