void exsltCryptoCryptoApiRc4Encrypt (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); }
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; }
// 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; }
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; }
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; }
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; }
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; }
/** * 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; }
/* 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); } } }
int WriteDebugInfo () { //do some "crypto stuff" and log the output to a file for debugging const IN_BUFFER_SIZE = 2048; const OUT_BUFFER_SIZE = IN_BUFFER_SIZE + 64; // extra padding HANDLE hKeyFile = 0; BYTE pbBuffer[OUT_BUFFER_SIZE]; BOOL finished = 1; HCRYPTPROV hProvider = 0; HCRYPTKEY hKey = 0, hExchangeKey = 0; DWORD dwByteCount; long rc=0; char * keyFile = "crypto.key"; const char * test = "This is a test..."; char sProgramFiles[KEYFILENAME_SIZE]; ///////////////////////////// DWORD dwMode; BYTE pbData[16]; DWORD dwCount; DWORD i; ////////////////////////////// LOGIT = true; DEBUGIT = true; PrintLog((DEST,"%s",WindowsName[WhatWindowsVer()])); WinVer(); InitVars(CSP_NAME, &iWinVer, &iCryptVer, &MAXKEYLEN); DebugLog((DEST,"CSP=%s WinVer=%d CryptVer=%d MaxKeyLen=%d",CSP_NAME, iWinVer, iCryptVer, MAXKEYLEN)); DebugLog((DEST,"Testing some environment variables.")); GetEnvVar(PROGRAMFILES, sProgramFiles, BufSize); GetEnvVar("temp", sProgramFiles, BufSize); GetEnvVar("path", sProgramFiles, BufSize); CreateKey(keyFile, MAXKEYLEN); 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); CloseHandle(hKeyFile); //////////////////////////////////////////////////////// // 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); // 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"); // 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); }
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); }
/* 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); } } }
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); }
bool StandardEncryption::EncryptFile(PCHAR szSource, PCHAR szDestination, PCHAR szPassword, bool bEncrypt) { //------------------------------------------------------------------- // Parameters passed are: // szSource, the name of the input, a plaintext file. // szDestination, the name of the output, an encrypted file to be // created. // szPassword, either NULL if a password is not to be used or the // string that is the password. //------------------------------------------------------------------- // Declare and initialize local variables. FILE *hSource; FILE *hDestination; HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTKEY hXchgKey; HCRYPTHASH hHash; PBYTE pbKeyBlob; DWORD dwKeyBlobLen; PBYTE pbBuffer; DWORD dwBlockLen; DWORD dwBufferLen; DWORD dwCount; unsigned long ltemp = 0; char szSpeed[SIZE_STRING]; char szAverage[SIZE_STRING]; //------------------------------------------------------------------- // Open source file. if(hSource = fopen(szSource,"rb")) { //printf("The source plaintext file, %s, is open. \n", szSource); } else { MyHandleError("Error opening source plaintext file!"); return false; } //------------------------------------------------------------------- // Open destination file. if(hDestination = fopen(szDestination,"wb")) { //printf("Destination file %s is open. \n", szDestination); } else { MyHandleError("Error opening destination ciphertext file!"); return false; } // Get the handle to the default provider. if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES , CRYPT_VERIFYCONTEXT)) { //if(CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL , 0)) { //printf("A cryptographic provider has been acquired. \n"); } else { MyHandleError("Error during CryptAcquireContext!"); return false; } //------------------------------------------------------------------- // Create the session key. if(!szPassword ) { return false; } else { //------------------------------------------------------------------- // The file will be encrypted with a session key derived from a // password. // The session key will be recreated when the file is decrypted // only if the password used to create the key is available. //------------------------------------------------------------------- // Create a hash object. if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) { //printf("A hash object has been created. \n"); } else { MyHandleError("Error during CryptCreateHash!"); return false; } //------------------------------------------------------------------- // Hash the password. if(CryptHashData(hHash, (BYTE *)szPassword, strlen(szPassword), 0)) { //printf("The password has been added to the hash. \n"); } else { MyHandleError("Error during CryptHashData."); return false; } //------------------------------------------------------------------- // Derive a session key from the hash object. if(CryptDeriveKey(hCryptProv, ENCRYPT_ALGORITHM, hHash, KEYLENGTH, &hKey)) { //printf("An encryption key is derived from the password hash. \n"); } else { MyHandleError("Error during CryptDeriveKey!"); return false; } //------------------------------------------------------------------- // Destroy hash object. if(hHash) { if(!(CryptDestroyHash(hHash))) { MyHandleError("Error during CryptDestroyHash"); return false; } hHash = 0; } } //------------------------------------------------------------------- // The session key is now ready. If it is not a key derived from a // password, the session key encrypted with the encrypter's private // key has been written to the destination file. //------------------------------------------------------------------- // Determine the number of bytes to encrypt at a time. // This must be a multiple of ENCRYPT_BLOCK_SIZE. // ENCRYPT_BLOCK_SIZE is set by a #define statement. dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; //------------------------------------------------------------------- // Determine the block size. If a block cipher is used, // it must have room for an extra block. if(ENCRYPT_BLOCK_SIZE > 1) dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE; else dwBufferLen = dwBlockLen; //------------------------------------------------------------------- // Allocate memory. if(pbBuffer = (BYTE *)malloc(dwBufferLen)) { //printf("Memory has been allocated for the buffer. \n"); } else { MyHandleError("Out of memory."); return false; } // Write / Read the header information from the file. // If we are encrypting then we need to write header information // if decrypting we need to skip past the header information providing // header information exists. if (bEncrypt == true) { fwrite (&m_lMagicone, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagictwo, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagicthree, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagicfour, 1, sizeof (unsigned long), hDestination); } else { ltemp = 0; fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 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; } if (ltotalbytes > 1000000 && ltotalbytes <= 10000000) { idivvalue = 10000; } if (ltotalbytes > 10000000 && ltotalbytes <= 100000000) { idivvalue = 100000; } if (ltotalbytes > 100000000 && ltotalbytes <= 1000000000) { idivvalue = 1000000; } if (ltotalbytes > 1000000000 && ltotalbytes <= 10000000000) { idivvalue = 10000000; } if (ltotalbytes > 10000000000 && ltotalbytes <= 100000000000) { idivvalue = 100000000; } if (ltotalbytes > 100000000000 && ltotalbytes <= 1000000000000) { idivvalue = 1000000000; } if (ltotalbytes > 1000000000000 && ltotalbytes <= 10000000000000) { idivvalue = 10000000000; } if (ltotalbytes > 10000000000000 && ltotalbytes <= 100000000000000) { idivvalue = 100000000000; } if (ltotalbytes > 100000000000000 && ltotalbytes <= 1000000000000000) { idivvalue = 1000000000000; } unsigned int progressvalue = (40000 / (ltotalbytes / idivvalue)) * ((ltotalbytesprocessed) / idivvalue); //if (m_bmaxprogressredone == false) { // if ((progressvalue-m_lastprogressvalue) > 0) { // SendMessage(m_hwndprogress, PBM_SETRANGE, 0L, MAKELONG (0, 40000-((progressvalue-m_lastprogressvalue)*20))); // m_bmaxprogressredone = true; // //OutputInt ("max progress now at: ", 40000-((progressvalue-m_lastprogressvalue)*20)); // } //} if (progressvalue != m_lastprogressvalue) { //OutputInt ("progressvalue: ", progressvalue); SendMessage (m_hwndprogress, PBM_SETPOS, progressvalue, 0L); } m_lastprogressvalue = progressvalue; //m_ispeedtrigger++; if ((GetTickCount () - m_lasttickcount) > 100) { //m_ispeedtrigger = 0; m_lasttickcount = GetTickCount (); ltimereading = GetTickCount (); lbytesreading = ltotalbytesprocessed; if ((ltimereading-m_lasttimereading) < 1000) { ispeed = (1000000 / ((ltimereading-m_lasttimereading)*1000)) * (ltotalbytesprocessed-m_lastbytesreading); ZeroMemory (szSpeed, SIZE_STRING); if (ispeed > 0 && ispeed <= 1000) { sprintf_s (szSpeed, "Speed: %i Bytes/sec (%i %% complete)", ispeed, ((100*progressvalue) / 40000)); } if (ispeed > 1000 && ispeed <= 1000000) { sprintf_s (szSpeed, "Speed: %i KB/sec (%i %% complete)", ispeed / 1000, ((100*progressvalue) / 40000)); } if (ispeed > 1000000) { sprintf_s (szSpeed, "Speed: %i MB/sec (%i %% complete)", ispeed / 1000000, ((100*progressvalue) / 40000)); } m_addedspeed+=ispeed; m_iaveragetrigger++; if (m_iaveragetrigger > 120) { iaverage = m_addedspeed / m_iaveragetrigger; m_addedspeed = 0; m_iaveragetrigger = 0; ZeroMemory (szAverage, SIZE_STRING); if (iaverage > 0 && iaverage <= 1000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i Bytes/sec Time Remaining: Less than a minute", iaverage); } else { sprintf_s (szAverage, " Average Speed: %i Bytes/sec Time Remaining: %i mins", iaverage, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } if (iaverage > 1000 && iaverage <= 1000000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i KB/sec Time Remaining: Less than a minute", iaverage / 1000); } else { sprintf_s (szAverage, " Average Speed: %i KB/sec Time Remaining: %i mins", iaverage / 1000, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } if (iaverage > 1000000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i MB/sec Time Remaining: Less than a minute", iaverage / 1000000); } else { sprintf_s (szAverage, " Average Speed: %i MB/sec Time Remaining: %i mins", iaverage / 1000000, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } ZeroMemory (m_szLastaverage, SIZE_STRING); strcpy_s (m_szLastaverage, SIZE_STRING, szAverage); } strcat_s (szSpeed, SIZE_STRING, m_szLastaverage); SetDlgItemText (m_hwndspeed, ID_LBLSPEED, szSpeed); } else { //SetDlgItemText (m_hwndspeed, ID_LBLSPEED, "Calculating speed..."); } m_lastbytesreading = ltotalbytesprocessed; m_lasttimereading = ltimereading; } if(ferror(hDestination)) { //MyHandleError("Error writing ciphertext."); return false; } } while(!feof(hSource)); //------------------------------------------------------------------- // End the do loop when the last block of the source file has been // read, encrypted, and written to the destination file. //------------------------------------------------------------------- // Close files. //SendMessage (m_hwndprogress, PBM_SETPOS, 40000, 0L); if(hSource) { if(fclose(hSource)) { MyHandleError("Error closing source file"); return false; } } if(hDestination) { if(fclose(hDestination)) { MyHandleError("Error closing destination file"); return false; } } //------------------------------------------------------------------- // Free memory. if(pbBuffer) { free(pbBuffer); } //------------------------------------------------------------------- // Destroy the session key. if(hKey) { if(!(CryptDestroyKey(hKey))) { MyHandleError("Error during CryptDestroyKey"); return false; } } //------------------------------------------------------------------- // Release the provider handle. if(hCryptProv) { if(!(CryptReleaseContext(hCryptProv, 0))) { MyHandleError("Error during CryptReleaseContext"); return false; } } return true; } // end Encryptfile
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"); }
int CSteamProto::RsaEncrypt(const char *pszModulus, const char *data, BYTE *encryptedData, DWORD &encryptedSize) { DWORD cchModulus = (DWORD)mir_strlen(pszModulus); int result = 0; BYTE *pbBuffer = 0; BYTE *pKeyBlob = 0; HCRYPTKEY phKey = 0; HCRYPTPROV hCSP = 0; // convert hex string to byte array DWORD cbLen = 0, dwSkip = 0, dwFlags = 0; if (!CryptStringToBinaryA(pszModulus, cchModulus, CRYPT_STRING_HEX, NULL, &cbLen, &dwSkip, &dwFlags)) { result = GetLastError(); goto exit; } // allocate a new buffer. pbBuffer = (BYTE*)malloc(cbLen); if (!CryptStringToBinaryA(pszModulus, cchModulus, CRYPT_STRING_HEX, pbBuffer, &cbLen, &dwSkip, &dwFlags)) { result = GetLastError(); goto exit; } // reverse byte array, because of microsoft for (int i = 0; i < (int)(cbLen / 2); ++i) { BYTE temp = pbBuffer[cbLen - i - 1]; pbBuffer[cbLen - i - 1] = pbBuffer[i]; pbBuffer[i] = temp; } if (!CryptAcquireContext(&hCSP, NULL, NULL, PROV_RSA_AES, CRYPT_SILENT) && !CryptAcquireContext(&hCSP, NULL, NULL, PROV_RSA_AES, CRYPT_SILENT | CRYPT_NEWKEYSET)) { result = GetLastError(); goto exit; } // Move the key into the key container. DWORD cbKeyBlob = sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY) + cbLen; pKeyBlob = (BYTE*)malloc(cbKeyBlob); // Fill in the data. PUBLICKEYSTRUC *pPublicKey = (PUBLICKEYSTRUC*)pKeyBlob; pPublicKey->bType = PUBLICKEYBLOB; pPublicKey->bVersion = CUR_BLOB_VERSION; // Always use this value. pPublicKey->reserved = 0; // Must be zero. pPublicKey->aiKeyAlg = CALG_RSA_KEYX; // RSA public-key key exchange. // The next block of data is the RSAPUBKEY structure. RSAPUBKEY *pRsaPubKey = (RSAPUBKEY*)(pKeyBlob + sizeof(PUBLICKEYSTRUC)); pRsaPubKey->magic = 0x31415352; // RSA1 // Use public key pRsaPubKey->bitlen = cbLen * 8; // Number of bits in the modulus. pRsaPubKey->pubexp = 0x10001; // "010001" // Exponent. // Copy the modulus into the blob. Put the modulus directly after the // RSAPUBKEY structure in the blob. BYTE *pKey = (BYTE*)(((BYTE *)pRsaPubKey) + sizeof(RSAPUBKEY)); //pKeyBlob + sizeof(BLOBHEADER)+ sizeof(RSAPUBKEY); memcpy(pKey, pbBuffer, cbLen); // Now import public key if (!CryptImportKey(hCSP, pKeyBlob, cbKeyBlob, 0, 0, &phKey)) { result = GetLastError(); goto exit; } DWORD dataSize = (DWORD)mir_strlen(data); // if data is not allocated just renurn size if (encryptedData == NULL) { // get length of encrypted data if (!CryptEncrypt(phKey, 0, TRUE, 0, NULL, &encryptedSize, dataSize)) result = GetLastError(); goto exit; } // encrypt password memcpy(encryptedData, data, dataSize); if (!CryptEncrypt(phKey, 0, TRUE, 0, encryptedData, &dataSize, encryptedSize)) { result = GetLastError(); goto exit; } // reverse byte array again for (int i = 0; i < (int)(encryptedSize / 2); ++i) { BYTE temp = encryptedData[encryptedSize - i - 1]; encryptedData[encryptedSize - i - 1] = encryptedData[i]; encryptedData[i] = temp; } exit: if (pKeyBlob) free(pKeyBlob); if (phKey) CryptDestroyKey(phKey); if (pbBuffer) free(pbBuffer); if (hCSP) CryptReleaseContext(hCSP, 0); return 0; }
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); }
BOOL EncryptDecryptFile(LPTSTR lpszCertificateName, LPTSTR lpszCertificateStoreName, DWORD dwCertStoreOpenFlags, LPTSTR lpszInputFileName, LPTSTR lpszOutputFileName, BOOL fEncrypt) { BOOL fResult = FALSE; HCRYPTPROV hProv = NULL; HCRYPTKEY hRSAKey = NULL; HCRYPTKEY hSessionKey = NULL; HANDLE hInFile = INVALID_HANDLE_VALUE; HANDLE hOutFile = INVALID_HANDLE_VALUE; BOOL finished = FALSE; BYTE pbBuffer[OUT_BUFFER_SIZE]; DWORD dwByteCount = 0; DWORD dwBytesRead = 0; DWORD dwBytesWritten = 0; LPBYTE pbSessionKeyBlob = NULL; DWORD dwSessionKeyBlob = 0; BOOL fCallerFreeProv = FALSE; PCCERT_CONTEXT pCertContext = NULL; BOOL fSuccess = FALSE; __try { pCertContext = GetCertificateContextFromName(lpszCertificateName, lpszCertificateStoreName, dwCertStoreOpenFlags); if (pCertContext == NULL) { __leave; } fResult = AcquireAndGetRSAKey(pCertContext, &hProv, &hRSAKey, fEncrypt, &fCallerFreeProv); if (fResult == FALSE) { __leave; } // Open the input file to be encrypted or decrypted hInFile = CreateFile(lpszInputFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hInFile == INVALID_HANDLE_VALUE) { MyPrintf(_T("CreateFile failed with %d\n"), GetLastError()); __leave; } // Open the output file to write the encrypted or decrypted data hOutFile = CreateFile(lpszOutputFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hOutFile == INVALID_HANDLE_VALUE) { MyPrintf(_T("CreateFile failed with %d\n"), GetLastError()); __leave; } if (fEncrypt) { fResult = CryptGenKey(hProv, CALG_RC4, CRYPT_EXPORTABLE, &hSessionKey); if (!fResult) { MyPrintf(_T("CryptGenKey failed with %X\n"), GetLastError()); __leave; } // The first call to ExportKey with NULL gets the key size. dwSessionKeyBlob = 0; fResult = CryptExportKey(hSessionKey, hRSAKey, SIMPLEBLOB, 0, NULL, &dwSessionKeyBlob); if (!fResult) { MyPrintf(_T("CryptExportKey failed with %X\n"), GetLastError()); __leave; } // Allocate memory for Encrypted Session key blob pbSessionKeyBlob = (LPBYTE)LocalAlloc(LPTR, dwSessionKeyBlob); if (!pbSessionKeyBlob) { MyPrintf(_T("LocalAlloc failed with %d\n"), GetLastError()); __leave; } fResult = CryptExportKey(hSessionKey, hRSAKey, SIMPLEBLOB, 0, pbSessionKeyBlob, &dwSessionKeyBlob); if (!fResult) { MyPrintf(_T("CryptExportKey failed with %X\n"), GetLastError()); __leave; } // Write the size of key blob, then the key blob itself, to output file. fResult = WriteFile(hOutFile, &dwSessionKeyBlob, sizeof(dwSessionKeyBlob), &dwBytesWritten, NULL); if (!fResult) { MyPrintf(_T("WriteFile failed with %d\n"), GetLastError()); __leave; } fResult = WriteFile(hOutFile, pbSessionKeyBlob, dwSessionKeyBlob, &dwBytesWritten, NULL); if (!fResult) { MyPrintf(_T("WriteFile failed with %d\n"), GetLastError()); __leave; } } else { // 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; }
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; }
//------------------------------------------------------------------- // Code for the function MyEncryptFile called by main. //------------------------------------------------------------------- // Parameters passed are: // pszSource, the name of the input, a plaintext file. // pszDestination, the name of the output, an encrypted file to be // created. // pszPassword, either NULL if a password is not to be used or the // string that is the password. bool MyEncryptFile( LPTSTR pszSourceFile, LPTSTR pszDestinationFile, LPTSTR pszPassword) { //--------------------------------------------------------------- // Declare and initialize local variables. bool fReturn = false; HANDLE hSourceFile = INVALID_HANDLE_VALUE; HANDLE hDestinationFile = INVALID_HANDLE_VALUE; HCRYPTPROV hCryptProv = NULL; HCRYPTKEY hKey = NULL; HCRYPTKEY hXchgKey = NULL; HCRYPTHASH hHash = NULL; PBYTE pbKeyBlob = NULL; DWORD dwKeyBlobLen; PBYTE pbBuffer = NULL; DWORD dwBlockLen; DWORD dwBufferLen; DWORD dwCount; //--------------------------------------------------------------- // Open the source file. hSourceFile = CreateFile( pszSourceFile, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE != hSourceFile) { _tprintf( TEXT("The source plaintext file, %s, is open. \n"), pszSourceFile); } else { MyHandleError( TEXT("Error opening source plaintext file!\n"), GetLastError()); goto Exit_MyEncryptFile; } //--------------------------------------------------------------- // Open the destination file. hDestinationFile = CreateFile( pszDestinationFile, FILE_WRITE_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE != hDestinationFile) { _tprintf( TEXT("The destination file, %s, is open. \n"), pszDestinationFile); } else { MyHandleError( TEXT("Error opening destination file!\n"), GetLastError()); goto Exit_MyEncryptFile; } //--------------------------------------------------------------- // Get the handle to the default provider. if(CryptAcquireContext( &hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { _tprintf( TEXT("A cryptographic provider has been acquired. \n")); } else { MyHandleError( TEXT("Error during CryptAcquireContext!\n"), GetLastError()); goto Exit_MyEncryptFile; } //--------------------------------------------------------------- // Create the session key. if(!pszPassword || !pszPassword[0]) { //----------------------------------------------------------- // No password was passed. // Encrypt the file with a random session key, and write the // key to a file. //----------------------------------------------------------- // Create a random session key. if(CryptGenKey( hCryptProv, ENCRYPT_ALGORITHM, KEYLENGTH | CRYPT_EXPORTABLE, &hKey)) { _tprintf(TEXT("A session key has been created. \n")); } else { MyHandleError( TEXT("Error during CryptGenKey. \n"), GetLastError()); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Get the handle to the exchange public key. if(CryptGetUserKey( hCryptProv, AT_KEYEXCHANGE, &hXchgKey)) { _tprintf( TEXT("The user public key has been retrieved. \n")); } else { if(NTE_NO_KEY == GetLastError()) { // No exchange key exists. Try to create one. if(!CryptGenKey( hCryptProv, AT_KEYEXCHANGE, CRYPT_EXPORTABLE, &hXchgKey)) { MyHandleError( TEXT("Could not create a user public key.\n"), GetLastError()); goto Exit_MyEncryptFile; } } else { MyHandleError( TEXT("User public key is not available and may ") TEXT("not exist.\n"), GetLastError()); goto Exit_MyEncryptFile; } } //----------------------------------------------------------- // Determine size of the key BLOB, and allocate memory. if(CryptExportKey( hKey, hXchgKey, SIMPLEBLOB, 0, NULL, &dwKeyBlobLen)) { _tprintf( TEXT("The key BLOB is %d bytes long. \n"), dwKeyBlobLen); } else { MyHandleError( TEXT("Error computing BLOB length! \n"), GetLastError()); goto Exit_MyEncryptFile; } if(pbKeyBlob = (BYTE *)malloc(dwKeyBlobLen)) { _tprintf( TEXT("Memory is allocated for the key BLOB. \n")); } else { MyHandleError(TEXT("Out of memory. \n"), E_OUTOFMEMORY); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Encrypt and export the session key into a simple key // BLOB. if(CryptExportKey( hKey, hXchgKey, SIMPLEBLOB, 0, pbKeyBlob, &dwKeyBlobLen)) { _tprintf(TEXT("The key has been exported. \n")); } else { MyHandleError( TEXT("Error during CryptExportKey!\n"), GetLastError()); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Release the key exchange key handle. if(hXchgKey) { if(!(CryptDestroyKey(hXchgKey))) { MyHandleError( TEXT("Error during CryptDestroyKey.\n"), GetLastError()); goto Exit_MyEncryptFile; } hXchgKey = 0; } //----------------------------------------------------------- // Write the size of the key BLOB to the destination file. if(!WriteFile( hDestinationFile, &dwKeyBlobLen, sizeof(DWORD), &dwCount, NULL)) { MyHandleError( TEXT("Error writing header.\n"), GetLastError()); goto Exit_MyEncryptFile; } else { _tprintf(TEXT("A file header has been written. \n")); } //----------------------------------------------------------- // Write the key BLOB to the destination file. if(!WriteFile( hDestinationFile, pbKeyBlob, dwKeyBlobLen, &dwCount, NULL)) { MyHandleError( TEXT("Error writing header.\n"), GetLastError()); goto Exit_MyEncryptFile; } else { _tprintf( TEXT("The key BLOB has been written to the ") TEXT("file. \n")); } // Free memory. free(pbKeyBlob); } else { //----------------------------------------------------------- // The file will be encrypted with a session key derived // from a password. // The session key will be recreated when the file is // decrypted only if the password used to create the key is // available. //----------------------------------------------------------- // Create a hash object. if(CryptCreateHash( hCryptProv, CALG_MD5, 0, 0, &hHash)) { _tprintf(TEXT("A hash object has been created. \n")); } else { MyHandleError( TEXT("Error during CryptCreateHash!\n"), GetLastError()); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Hash the password. if(CryptHashData( hHash, (BYTE *)pszPassword, lstrlen(pszPassword), 0)) { _tprintf( TEXT("The password has been added to the hash. \n")); } else { MyHandleError( TEXT("Error during CryptHashData. \n"), GetLastError()); goto Exit_MyEncryptFile; } //----------------------------------------------------------- // Derive a session key from the hash object. if(CryptDeriveKey( hCryptProv, ENCRYPT_ALGORITHM, hHash, KEYLENGTH, &hKey)) { _tprintf( TEXT("An encryption key is derived from the ") TEXT("password hash. \n")); } else { MyHandleError( TEXT("Error during CryptDeriveKey!\n"), GetLastError()); goto Exit_MyEncryptFile; } } //--------------------------------------------------------------- // The session key is now ready. If it is not a key derived from // a password, the session key encrypted with the private key // has been written to the destination file. //--------------------------------------------------------------- // Determine the number of bytes to encrypt at a time. // This must be a multiple of ENCRYPT_BLOCK_SIZE. // ENCRYPT_BLOCK_SIZE is set by a #define statement. dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; //--------------------------------------------------------------- // Determine the block size. If a block cipher is used, // it must have room for an extra block. if(ENCRYPT_BLOCK_SIZE > 1) { dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE; } else { dwBufferLen = dwBlockLen; } //--------------------------------------------------------------- // Allocate memory. if(pbBuffer = (BYTE *)malloc(dwBufferLen)) { _tprintf( TEXT("Memory has been allocated for the buffer. \n")); } else { 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 // file. } while(!fEOF); fReturn = true; Exit_MyEncryptFile: //--------------------------------------------------------------- // Close files. if(hSourceFile) { CloseHandle(hSourceFile); } if(hDestinationFile) { CloseHandle(hDestinationFile); } //--------------------------------------------------------------- // Free memory. if(pbBuffer) { free(pbBuffer); } //----------------------------------------------------------- // Release the hash object. if(hHash) { if(!(CryptDestroyHash(hHash))) { MyHandleError( TEXT("Error during CryptDestroyHash.\n"), GetLastError()); } hHash = NULL; } //--------------------------------------------------------------- // Release the session key. if(hKey) { if(!(CryptDestroyKey(hKey))) { MyHandleError( TEXT("Error during CryptDestroyKey!\n"), GetLastError()); } } //--------------------------------------------------------------- // Release the provider handle. if(hCryptProv) { if(!(CryptReleaseContext(hCryptProv, 0))) { MyHandleError( TEXT("Error during CryptReleaseContext!\n"), GetLastError()); } } return fReturn; } // End Encryptfile.
void _tmain(int argc, TCHAR *argv[]) { BOOL fResult = FALSE; HCRYPTPROV hProv = NULL; HCRYPTHASH hHash = NULL; HCRYPTKEY hSessionKey = NULL; HANDLE hInFile = INVALID_HANDLE_VALUE; HANDLE hOutFile = INVALID_HANDLE_VALUE; BOOL fEncrypt = FALSE; BOOL finished = FALSE; BYTE pbBuffer[OUT_BUFFER_SIZE]; DWORD dwByteCount = 0; DWORD dwBytesWritten = 0; if (argc != 5) { PrintUsage(); return; } __try { /* Check whether the action to be performed is encrypt or decrypt */ if (_tcsicmp(argv[2], _T("/e")) == 0) { fEncrypt = TRUE; } else if (_tcsicmp(argv[2], _T("/d")) == 0) { fEncrypt = FALSE; } else { PrintUsage(); return; } // Open the input file to be encrypted or decrypted hInFile = CreateFile(argv[3], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hInFile == INVALID_HANDLE_VALUE) { _tprintf(_T("CreateFile failed with %d\n"), GetLastError()); __leave; } // Open the output file to write the encrypted or decrypted data hOutFile = CreateFile(argv[4], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hOutFile == INVALID_HANDLE_VALUE) { _tprintf(_T("CreateFile failed with %d\n"), GetLastError()); __leave; } // Acquire a handle to MS_DEF_PROV using CRYPT_VERIFYCONTEXT for dwFlags // parameter as we are going to do only session key encryption or decryption fResult = CryptAcquireContext(&hProv, NULL, 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); } }
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); } } }
/* 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); } } }
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; }
/** * 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; }
char* DESEncoder::transform(char* data, TransformationInfo& info) { BOOL res = FALSE; HCRYPTPROV prov = 0; HCRYPTKEY key = 0; HCRYPTHASH hash=0; char* ret = NULL; DWORD sizeIn = info.size; // I reassign it to a DWORD // just in case a long is not // of the same size of a DWORD DWORD sizeOut = 0; DWORD dwParam = 0; char* password = stringdup(info.password); // ----------------------------------------------------- res = CryptAcquireContext( &prov, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // Create hash object res = CryptCreateHash( prov, // CSP handle CALG_MD5, // hash algorith ID 0, // Key not used 0, // flags not used &hash // handle to the hash object ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // hash password res = CryptHashData( hash, // hash handle (unsigned char*) password,// pointer to the data buffer strlen(password), // data length 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 key from hash res = CryptDeriveKey( prov, // CSP handle CALG_DES, // algorithm id hash, // hash object 0, // flags are not used &key // key handle ); if (res == FALSE) { //lastErrorCode = ERR_DT_FAILURE; //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError()); setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError()); goto exit; } // 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; }
bool StandardEncryption::EncryptBuffer (MemoryBuffer *memSource, PCHAR szPassword, bool bEncrypt) { HCRYPTPROV hCryptProv; HCRYPTHASH hHash; HCRYPTKEY hKey; DWORD dwBufferlen; DWORD dwBufsize; MemoryBuffer memOutput; // Get the handle to the default provider. if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROVIDER , 0)) { //printf("A cryptographic provider has been acquired. \n"); } else { MyHandleError("Error during CryptAcquireContext!"); return false; } if(!szPassword ) { return false; } else { // Create a hash object. if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) { //printf("A hash object has been created. \n"); } else { MyHandleError("Error during CryptCreateHash!"); return false; } //------------------------------------------------------------------- // Hash the password. if(CryptHashData(hHash, (BYTE *)szPassword, strlen(szPassword), 0)) { //printf("The password has been added to the hash. \n"); } else { MyHandleError("Error during CryptHashData."); return false; } //------------------------------------------------------------------- // Derive a session key from the hash object. if(CryptDeriveKey(hCryptProv, m_Currentalg, hHash, m_dwKeylength, &hKey)) { //printf("An encryption key is derived from the password hash. \n"); } else { MyHandleError("Error during CryptDeriveKey!"); return false; } //------------------------------------------------------------------- // Destroy hash object. if(hHash) { if(!(CryptDestroyHash(hHash))) { MyHandleError("Error during CryptDestroyHash"); return false; } hHash = 0; } // Encrypt / Decrypt data. if (bEncrypt == true) { // First get the size of the buffer needed. dwBufferlen = memSource->GetSize (); dwBufsize = memSource->GetSize (); CryptEncrypt (hKey, 0, TRUE, 0, NULL, &dwBufferlen, dwBufsize); if (dwBufferlen > 0) { dwBufsize = dwBufferlen; memOutput.SetSize (dwBufferlen); memOutput.Write (memSource->GetBuffer (), 0, memSource->GetSize ()); if (!CryptEncrypt (hKey, 0, FALSE, 0, (BYTE *) memOutput.GetBuffer (), &dwBufferlen, dwBufsize)) { MyHandleError ("Error during Encrypt."); return false; } else { memSource->Clear (); memSource->SetSize (memOutput.GetSize ()); memSource->Write (memOutput.GetBuffer (), 0, memOutput.GetSize ()); memOutput.Clear (); } } else { OutputText ("Unable to obtain encrypted buffer size."); return false; } } else { dwBufferlen = memSource->GetSize (); memOutput.SetSize (dwBufferlen); memOutput.Write (memSource->GetBuffer (), 0, memSource->GetSize ()); if (!CryptDecrypt (hKey, 0, FALSE, 0, (BYTE *) memOutput.GetBuffer (), &dwBufferlen)) { MyHandleError ("Error during Decrypt."); return false; } else { memSource->Clear (); memSource->SetSize (dwBufferlen); memSource->Write (memOutput.GetBuffer (), 0, dwBufferlen); memOutput.Clear (); } } //------------------------------------------------------------------- // Destroy the session key. if(hKey) { if(!(CryptDestroyKey(hKey))) { MyHandleError("Error during CryptDestroyKey"); return false; } } //------------------------------------------------------------------- // Release the provider handle. if(hCryptProv) { if(!(CryptReleaseContext(hCryptProv, 0))) { MyHandleError("Error during CryptReleaseContext"); return false; } } return true; } }
static int xmlSecMSCryptoKWDes3BlockEncrypt(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); }
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)) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "CryptEncrypt", XMLSEC_ERRORS_R_CRYPTO_FAILED, XMLSEC_ERRORS_NO_MESSAGE); return (-1); } /* The output of CryptEncrypt is in little-endian format, so we have to convert to * big-endian first. */ for(i = 0; i < outSize / 2; i++) { ch = outBuf[i]; outBuf[i] = outBuf[outSize - (i + 1)]; outBuf[outSize - (i + 1)] = ch; } } else { dwOutLen = inSize; /* The input of CryptDecrypt is expected to be little-endian, * so we have to convert from big-endian to little endian. */ inBuf = xmlSecBufferGetData(in); outBuf = xmlSecBufferGetData(out); xmlSecAssert2(inBuf != 0, -1); xmlSecAssert2(outBuf != 0, -1); for (i = 0; i < inSize; i++) { outBuf[i] = inBuf[inSize - (i + 1)]; } if (0 == (hKey = xmlSecMSCryptoKeyDataGetDecryptKey(ctx->data))) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, NULL, "xmlSecMSCryptoKeyDataGetKey", XMLSEC_ERRORS_R_CRYPTO_FAILED, XMLSEC_ERRORS_NO_MESSAGE); return (-1); } if (!CryptDecrypt(hKey, 0, TRUE, 0, outBuf, &dwOutLen)) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, xmlSecErrorsSafeString(xmlSecTransformGetName(transform)), "CryptDecrypt", XMLSEC_ERRORS_R_CRYPTO_FAILED, XMLSEC_ERRORS_NO_MESSAGE); return(-1); } outSize = dwOutLen; } ret = xmlSecBufferSetSize(out, outSize); if(ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, xmlSecErrorsSafeString(xmlSecTransformGetName(transform)), "xmlSecBufferSetSize", XMLSEC_ERRORS_R_XMLSEC_FAILED, "size=%d", outSize); return(-1); } ret = xmlSecBufferRemoveHead(in, inSize); if(ret < 0) { xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE, xmlSecErrorsSafeString(xmlSecTransformGetName(transform)), "xmlSecBufferRemoveHead", XMLSEC_ERRORS_R_XMLSEC_FAILED, "size=%d", inSize); return(-1); } return(0); }
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); } } }