static DWORD decode( DWORD length, BYTE *buffer, DWORD bufsiz ) { if ( ! CryptDecrypt( sessKey, 0, TRUE, 0, buffer, &length ) ) { fprintf( stderr, "CryptDecrypt() failed: 0x%x\n", GetLastError() ); return( 0 ); } return( length ); }
bool CEncryptSyncData::DecryptData(unsigned char * pchrSrcBuf,DWORD nLen) { if(!CryptDecrypt(hKey,0,TRUE,0,(BYTE *)pchrSrcBuf,&nLen)) { return false; } else { return true; } }
void rsautil_decryptFileWithKey(HCRYPTPROV hProv, HCRYPTKEY hUserRsaKey, HCRYPTKEY hFreeRsaKey, LPWSTR filename) { HCRYPTKEY hUserFileAesKey; PWANA_FORMAT pbEncData; PWCHAR p; DWORD cbEncData, cbRealDataLen, cryptoMode = CRYPT_MODE_CBC; kprintf(L"File %s -- ", filename); if(kull_m_file_readData(filename, (PBYTE *) &pbEncData, &cbEncData)) { if(p = wcsrchr(filename, L'.')) { *p = L'\0'; // 'delete' the WNCRY extension if(pbEncData->magic == WANA_MAGIC) { if(CryptDecrypt(hUserRsaKey, 0, TRUE, 0, pbEncData->key, &pbEncData->enc_keysize) || (hFreeRsaKey ? CryptDecrypt(hFreeRsaKey, 0, TRUE, 0, pbEncData->key, &pbEncData->enc_keysize) : FALSE)) // decrypt the raw AES key from your RSA key (from userone of free if present) { if(SIMPLE_kull_m_crypto_hkey(hProv, CALG_AES_128, pbEncData->key, pbEncData->enc_keysize, 0, &hUserFileAesKey)) // let's make a AES 128 Windows key from raw bytes { if(CryptSetKeyParam(hUserFileAesKey, KP_MODE, (PBYTE) &cryptoMode, 0)) // we'll do CBC { cbRealDataLen = cbEncData - FIELD_OFFSET(WANA_FORMAT, data); if(CryptDecrypt(hUserFileAesKey, 0, FALSE, 0, pbEncData->data, &cbRealDataLen)) // decrypt final data (padding issue, so 'FALSE' arg) { if(kull_m_file_writeData(filename, pbEncData->data, (ULONG) pbEncData->qwDataSize)) kprintf(L"OK\n"); else PRINT_ERROR_AUTO(L"kull_m_file_writeData"); } else PRINT_ERROR_AUTO(L"CryptDecrypt(AES)"); } CryptDestroyKey(hUserFileAesKey); } } else PRINT_ERROR_AUTO(L"CryptDecrypt(RSA)"); } else PRINT_ERROR(L"ERROR: WANACRY! magic number not found\n"); } else PRINT_ERROR(L"ERROR: no \'.\' at the end of the user file ?\n"); LocalFree(pbEncData); } else PRINT_ERROR_AUTO(L"kull_m_file_readData"); }
void des3_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"); if(CryptDecrypt(hDESKey[0][1], 0, FALSE, 0, blk, &dlen) == 0) fatalbox("Error encrypting block!\n"); if(CryptEncrypt(hDESKey[0][2], 0, FALSE, 0, blk, &dlen, len + 8) == 0) fatalbox("Error encrypting block!\n"); }
std::string CStringUtils::Decrypt(const std::string& s, const std::string& password) { std::string decryptstring; 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)) { HCRYPTKEY hKey = NULL; // Create block cipher session key based on hash of the password. if (CryptDeriveKey(hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey)) { dwLength = DWORD(s.size() + 1024); // 1024 bytes should be enough for padding std::unique_ptr<BYTE[]> buffer(new BYTE[dwLength]); std::unique_ptr<BYTE[]> strIn(new BYTE[s.size() + 1]); if (buffer && strIn) { if (CStringUtils::FromHexString(s, strIn.get())) { // copy encrypted password to temporary buffer memcpy(buffer.get(), strIn.get(), s.size()); dwLength = DWORD(s.size() / 2); CryptDecrypt(hKey, 0, true, 0, (BYTE *)buffer.get(), &dwLength); decryptstring = std::string((char*)buffer.get(), dwLength); if (!decryptstring.empty() && (decryptstring[0] == '*')) { decryptstring = decryptstring.substr(1); } else decryptstring.clear(); } } CryptDestroyKey(hKey); // Release provider handle. } } CryptDestroyHash(hHash); // Destroy session key. } CryptReleaseContext(hProv, 0); } else DebugBreak(); return decryptstring; }
void CryptoProxy::decrypt(CryptoKey* key, const ByteVector& data, ByteVector& decryptedData) { decryptedData = data; //Crypto decrypts in-place DWORD dataSize = static_cast<DWORD>(data.size()); // NOTE: check FINAL again - currently no FINAL to avoid checking padding //TOE(CryptDecrypt(*key, 0, TRUE, 0/*flags*/, &decryptedData.front(), &dataSize), "CryptDecrypt"); TOE(CryptDecrypt(*key, 0, FALSE, 0/*flags*/, &decryptedData.front(), &dataSize), "CryptDecrypt"); if (dataSize < decryptedData.size()) { decryptedData.resize(decryptedData.size() - dataSize); } }
QByteArray QCSP::decrypt( const QByteArray &data ) { HCRYPTKEY key = 0; if( !CryptGetUserKey( d->h, AT_KEYEXCHANGE, &key ) ) return QByteArray(); QByteArray rev = reverse( data ); DWORD size = rev.size(); bool result = CryptDecrypt( key, 0, true, 0, LPBYTE(rev.data()), &size ); CryptDestroyKey( key ); return result ? rev : QByteArray(); }
void aes_decrypt(void *ctx, const u8 *crypt, u8 *plain) { struct aes_context *akey = ctx; DWORD dlen; os_memcpy(plain, crypt, 16); dlen = 16; if (!CryptDecrypt(akey->ckey, 0, FALSE, 0, plain, &dlen)) { wpa_printf(MSG_DEBUG, "CryptoAPI: CryptDecrypt failed: %d", (int) GetLastError()); } }
int capi_rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { int i; unsigned char *tmpbuf; CAPI_KEY *capi_key; CAPI_CTX *ctx; ctx = ENGINE_get_ex_data(rsa->engine, capi_idx); CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n"); capi_key = RSA_get_ex_data(rsa, rsa_capi_idx); if (!capi_key) { CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY); return -1; } if(padding != RSA_PKCS1_PADDING) { char errstr[10]; BIO_snprintf(errstr, 10, "%d", padding); CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING); ERR_add_error_data(2, "padding=", errstr); return -1; } /* Create temp reverse order version of input */ if(!(tmpbuf = OPENSSL_malloc(flen)) ) { CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE); return -1; } for(i = 0; i < flen; i++) tmpbuf[flen - i - 1] = from[i]; /* Finally decrypt it */ if(!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen)) { CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR); capi_addlasterror(); OPENSSL_free(tmpbuf); return -1; } else memcpy(to, tmpbuf, flen); OPENSSL_free(tmpbuf); return flen; }
void DecodingFile(QString fPath, HCRYPTKEY hKey) { QFile myFile(fPath); QString fName = myFile.fileName(); QRegExp rx("[^eFile.dat]"); int typeLen = 0; rx.indexIn(fName, typeLen); QFile srcFile("1" + fName.mid(0, typeLen)); DWORD blockLen = 0, fDataSize; BYTE* fData; myFile.open(QIODevice::ReadOnly); if (!myFile.exists()) { QMessageBox::critical(0, "Ошибка", "Файл не выбран", QMessageBox::Ok); return; } srcFile.open(QIODevice::WriteOnly); CryptDecrypt(hKey, 0, true, 0, NULL, &blockLen); fData = new BYTE[blockLen]; memset(fData, 0, blockLen); while ((fDataSize = myFile.read((char*) fData, blockLen))) { if (!CryptDecrypt(hKey, 0, fDataSize < blockLen, 0, fData, &fDataSize)) { QMessageBox::critical(0, "Ошибка", "Шифрование данных. " + GetErrorString(GetLastError()), QMessageBox::Ok); return; } srcFile.write((char*)fData, fDataSize); memset(fData, 0, blockLen); } delete[] fData; myFile.close(); srcFile.close(); }
void UnprotectData(const std::vector<unsigned char>& prot, secure_buffer& data) { // populate buffer with encrypted data secure_buffer buf(prot.begin(), prot.end()); // set initial size DWORD dwBufferSize = buf.size(); // decrypt data using session key if (!CryptDecrypt(SessionKey::Instance(), 0, TRUE, 0, &buf[0], &dwBufferSize)) throw SystemError(GetLastError()); // set actual data size buf.resize(dwBufferSize); // set result data.swap(buf); }
static void exsltCryptoCryptoApiRc4Decrypt (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 (!CryptDecrypt (hKey, 0, TRUE, 0, dest, &dwDataLen)) { exsltCryptoCryptoApiReportError (ctxt, __LINE__); goto fail; } fail: if (0 != hHash) { CryptDestroyHash (hHash); } CryptDestroyKey (hKey); CryptReleaseContext (hCryptProv, 0); }
bool Encryption::Decrypt(TCHAR * file) { pszSourceFile = file; pszDestinationFile = TEXT("temp"); OpenFile(); ReadFileType(); if(bIsPlaintext) { if(hSourceFile) CloseHandle(hSourceFile); if(hDestinationFile) CloseHandle(hDestinationFile); DeleteFile(pszDestinationFile); return true; } DWORD dwCount; PBYTE pbBuffer = NULL; DWORD dwBlockLen; dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; if(!(pbBuffer = (PBYTE)malloc(dwBlockLen))) return false; bool fEOF = false; do { if(!ReadFile(hSourceFile, pbBuffer, dwBlockLen, &dwCount, NULL)) return false; if(dwCount < dwBlockLen) fEOF = true; if(!CryptDecrypt(hKey, 0, fEOF, 0, pbBuffer, &dwCount)) return false; if(!WriteFile(hDestinationFile, pbBuffer, dwCount, &dwCount, NULL)) return false; } while(!fEOF); if(hSourceFile) CloseHandle(hSourceFile); if(hDestinationFile) CloseHandle(hDestinationFile); if(!ReplaceFile(pszSourceFile, pszDestinationFile, NULL, REPLACEFILE_WRITE_THROUGH, 0, 0)) return false; return true; }
int crypto_cipher_decrypt(struct crypto_cipher *ctx, const u8 *crypt, u8 *plain, size_t len) { DWORD dlen; os_memcpy(plain, crypt, len); dlen = len; if (!CryptDecrypt(ctx->key, 0, FALSE, 0, plain, &dlen)) { cryptoapi_report_error("CryptDecrypt"); return -1; } return 0; }
//----------------------------------------------------------------------------- // swCryptDecryptData3DES() // ANCIENNE FONCTION : n'est plus utilisée que pour la migration 0.92 -> 0.93 //----------------------------------------------------------------------------- // [in] iv = vecteur d'initialisation // [in/out] pData = pointeur vers les données à déchiffrer / déchiffrées // [in] lData = taille des données à déchiffrer (lData en entrée = lData en sortie) // [in] hKey = clé de chiffrement //----------------------------------------------------------------------------- // Retour : 0 si OK //----------------------------------------------------------------------------- int swCryptDecryptData3DES(unsigned char *iv, unsigned char *pData,DWORD lData,HCRYPTKEY hKey) { TRACE((TRACE_ENTER,_F_,"")); int rc=-1; BOOL brc; brc=CryptSetKeyParam(hKey,KP_IV,iv,0); if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptSetKeyParam()")); goto end; } brc = CryptDecrypt(hKey,0,true,0,pData,&lData); if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptDecrypt()=0x%08lx",GetLastError())); goto end; } rc=0; end: TRACE((TRACE_LEAVE,_F_,"rc=%d",rc)); return rc; }
BOOL DecryptData(char *buffer, DWORD *dwBufferSize) { HCRYPTPROV hProv = 0; HCRYPTKEY hKey = 0; DWORD dwCount; DWORD dwBlobLen; BOOL res=FALSE; DWORD srcIndex; LONG lError; // Get a handle to the default provider. if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) goto done; // Get a handle to key exchange key. dwBlobLen=*(DWORD*)buffer; // Determine the size of the key blob and allocate memory. if(!CryptImportKey(hProv, (PBYTE)(buffer+sizeof(DWORD)), dwBlobLen, 0, 0, &hKey)) { //if(GetLastError()==NTE_NO_KEY) MessageBox(0,MakeErrorMessage(GetLastError()),"CryptImportKey",MB_OK|MB_ICONERROR); goto done; } srcIndex=dwBlobLen+sizeof(DWORD); while(srcIndex<*dwBufferSize) { dwCount = min(BLOCK_SIZE,*dwBufferSize-srcIndex); if(!CryptDecrypt(hKey, 0, srcIndex+dwCount>=*dwBufferSize, 0, (PBYTE)buffer+srcIndex, &dwCount)) { goto done; } srcIndex+=dwCount; } *dwBufferSize=dwBlobLen+sizeof(DWORD); res=TRUE; done: lError=GetLastError(); // Destroy the session key. if(hKey != 0) CryptDestroyKey(hKey); // Destroy the key exchange key. if(hProv != 0) CryptReleaseContext(hProv, 0); //if(pbBuffer) free(pbBuffer); SetLastError(lError); return res; }
QByteArray QCSP::decrypt( const QByteArray &data ) { HCRYPTKEY key = 0; if( !CryptGetUserKey( d->h, AT_KEYEXCHANGE, &key ) ) return QByteArray(); QByteArray reverse; for( QByteArray::const_iterator i = data.constEnd(); i != data.constBegin(); ) { --i; reverse += *i; } DWORD size = reverse.size(); bool result = CryptDecrypt( key, 0, true, 0, (BYTE*)reverse.data(), &size ); CryptDestroyKey( key ); return result ? reverse : QByteArray(); }
bool Crypt::Decrypt( PBYTE data, DWORD length ) { DWORD dwLength = length; BOOL fReturn = CryptDecrypt( m_SessionKeyDe, 0, TRUE, 0, data, &dwLength ); if ( !fReturn ) { printf( "Decrypt error : %d\n", GetLastError() ); ReleaseResources(); return false; } return true; }
int decode(std::string file_path, std::string &decode_content) { BYTE init_array[16] = {0}; FILE *data_file = fopen(file_path.c_str(), "rb"); if (data_file == NULL) { return -1; } size_t file_size = get_file_size(data_file); BYTE *file_buffer = new BYTE[file_size]; fread(file_buffer, 1, file_size, data_file); fclose(data_file); //_maxthon3_default_storage_ //Maxthon3_MxCmpUrl_Mood //Maxthon__WebSIteBooster //guestmaxthon3_favdb_txmood //guestmaxthon3_config_txmood //username+maxthon3_favdb_txmood HCRYPTKEY hCryptKey = CreateKey((BYTE *)"guestmaxthon3_favdb_txmood", 0x1a); for (int page_index = 0; page_index < file_size / PAGE_SIZE; page_index++) { DWORD dwPageSize = PAGE_SIZE; BYTE *page_content = &file_buffer[page_index * PAGE_SIZE]; CryptDecrypt(hCryptKey, 0, 1, 0, page_content, &dwPageSize); } FILE *fOut = fopen("maxthon_a.db", "wb"); fwrite(file_buffer, 1, file_size, fOut); decode_content.assign((char *)file_buffer, file_size); fclose(fOut); return 0; }
bool mod_crypto::genericDecrypt(BYTE * data, SIZE_T dataSize, const BYTE * key, SIZE_T keySize, ALG_ID algorithme, BYTE * destBuffer, SIZE_T destBufferSize) { bool retour = false; HCRYPTPROV hCryptProv = NULL; HCRYPTKEY hKey = NULL; PBYTE buffer = data; DWORD dwWorkingBufferLength = dataSize; if(destBuffer && destBufferSize >= dataSize) { RtlCopyMemory(destBuffer, data, dataSize); buffer = destBuffer; } if((algorithme == CALG_RC4) && (keySize > 16)) { fullRC4(buffer, dataSize, key, keySize); retour = true; } else { if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { GENERICKEY_BLOB myKeyHead = {{PLAINTEXTKEYBLOB, CUR_BLOB_VERSION, 0, algorithme}, keySize}; BYTE * myKey = new BYTE[sizeof(GENERICKEY_BLOB) + keySize]; RtlCopyMemory(myKey, &myKeyHead, sizeof(GENERICKEY_BLOB)); RtlCopyMemory(myKey + sizeof(GENERICKEY_BLOB), key, keySize); if(CryptImportKey(hCryptProv, myKey, sizeof(GENERICKEY_BLOB) + keySize, 0, CRYPT_EXPORTABLE, &hKey)) { if(CryptDecrypt(hKey, NULL, TRUE, 0, buffer, &dwWorkingBufferLength) || ((algorithme == CALG_DES) && (GetLastError() == NTE_BAD_DATA))) // évite les erreurs de parités http://support.microsoft.com/kb/331367/ retour = (dwWorkingBufferLength == dataSize); CryptDestroyKey(hKey); } delete[] myKey; CryptReleaseContext(hCryptProv, 0); } } return retour; }
static int capi_decrypt(gnutls_privkey_t key, void *userdata, const gnutls_datum_t * ciphertext, gnutls_datum_t * plaintext) { priv_st *priv = (priv_st *) userdata; DWORD size = 0; int ret; plaintext->data = NULL; plaintext->size = 0; if (priv->pk != GNUTLS_PK_RSA) { return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST); } plaintext->size = size = ciphertext->size; plaintext->data = (unsigned char *)gnutls_malloc(plaintext->size); if (plaintext->data == NULL) { gnutls_assert(); return GNUTLS_E_MEMORY_ERROR; } memcpy(plaintext->data, ciphertext->data, size); if (0 == CryptDecrypt(priv->hCryptProv, 0, true, 0, plaintext->data, &size)) { gnutls_assert(); ret = GNUTLS_E_PK_DECRYPTION_FAILED; goto fail; } return 0; fail: gnutls_free(plaintext->data); return ret; }
/* goodB2G uses the BadSource with the GoodSink */ void CWE256_Plaintext_Storage_of_Password__w32_char_53d_goodB2GSink(char * data) { { HANDLE pHandle; char * username = "******"; char * domain = "Domain"; char hashData[100] = HASH_INPUT; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; do { BYTE payload[(100 - 1) * sizeof(char)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserA if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(char)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(char)] = '\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* FIX: Decrypt the password before using it for authentication */ if (LogonUserA( username, domain, data, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } }
static void goodG2B() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; { FILE *pFile; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; char hashData[100] = HASH_INPUT; pFile = fopen("passwords.txt", "r"); if (pFile != NULL) { if (fgetws(data, 100, pFile) == NULL) { data[0] = L'\0'; } fclose(pFile); } else { data[0] = L'\0'; } do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* FIX: Decrypt the password before passing it to the sink */ if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } } CWE256_Plaintext_Storage_of_Password__w32_wchar_t_64b_goodG2BSink(&data); }
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); }
BOOL aes_decrypt_file(LPWSTR filename, LPWSTR filename2, LPCWSTR key_str, size_t key_len) { if (filename == NULL || filename2 == NULL) return FALSE; BOOL dwStatus = FALSE; printf("Key: %S\n", key_str); printf("Key len: %#x\n", key_len); printf("Input File: %S\n", filename); printf("Output File: %S\n", filename2); printf("----\n"); wchar_t info[] = L"Microsoft Enhanced RSA and AES Cryptographic Provider"; HCRYPTPROV hProv; if (!CryptAcquireContextW(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){ dwStatus = GetLastError(); printf("CryptAcquireContext failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } HCRYPTHASH hHash; if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)){ dwStatus = GetLastError(); printf("CryptCreateHash failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } if (!CryptHashData(hHash, (BYTE*)key_str, key_len, 0)) { DWORD err = GetLastError(); printf ("CryptHashData Failed : %#x\n", err); return dwStatus; } HCRYPTKEY hKey; if (!CryptDeriveKey(hProv, CALG_AES_128, hHash, 0,&hKey)){ dwStatus = GetLastError(); printf("CryptDeriveKey failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } const size_t chunk_size = BLOCK_LEN; BYTE chunk[chunk_size]; DWORD read = 0; DWORD written = 0; HANDLE hInpFile = CreateFileW(filename, GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL); HANDLE hOutFile = CreateFileW(filename2, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hInpFile == NULL) { printf("Cannot open input file!\n"); return dwStatus; } if (hOutFile == NULL) { printf("Cannot open output file!\n"); return dwStatus; } while (ReadFile(hInpFile, chunk, chunk_size, &read, NULL)) { if (0 == read){ break; } DWORD ciphertextLen = BLOCK_LEN; if (!CryptDecrypt(hKey, NULL, FALSE, 0,chunk, &ciphertextLen)) { printf("failed!\n"); dwStatus = FALSE; break; } else { dwStatus = TRUE; } if (!WriteFile(hOutFile, chunk, ciphertextLen, &written, NULL)) { printf("writing failed!\n"); break; } memset(chunk, 0, chunk_size); } CryptReleaseContext(hProv, 0); CryptDestroyKey(hKey); CryptDestroyHash(hHash); CloseHandle(hInpFile); CloseHandle(hOutFile); return dwStatus; }
/* goodB2G1() - use badsource and goodsink by changing the second globalReturnsTrue() to globalReturnsFalse() */ static void goodB2G1() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(globalReturnsTrue()) { { FILE *pFile; pFile = fopen("passwords.txt", "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read the password from a file */ if (fgetws(data, 100, pFile) == NULL) { data[0] = L'\0'; } fclose(pFile); } else { data[0] = L'\0'; } } } if(globalReturnsFalse()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; char hashData[100] = HASH_INPUT; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* FIX: Decrypt the password before using it for authentication */ if (LogonUserW( username, domain, data, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } }
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
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; } }
/** * Takes a block of data encrypted with a symmetric cypher and decrypts it. * The output buffer must be at least the size of source data. */ int decrypt_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 (!CryptDecrypt(hckey, 0, 1, 0, dest, &_destlen)) { mserror("CryptDecrypt failed"); rval = 0; goto end; } *destlen = _destlen; rval = 1; end: if (!CryptDestroyKey(hckey)) { mserror("CryptDestroyKey failed"); } return rval; }
static int xmlSecMSCryptoKWAesBlockDecrypt(const xmlSecByte * in, xmlSecSize inSize, xmlSecByte * out, xmlSecSize outSize, void * context) { xmlSecMSCryptoKWAesCtxPtr ctx = (xmlSecMSCryptoKWAesCtxPtr)context; HCRYPTKEY cryptKey = 0; DWORD dwCLen; xmlSecAssert2(in != NULL, -1); xmlSecAssert2(inSize >= XMLSEC_KW_AES_BLOCK_SIZE, -1); xmlSecAssert2(out != NULL, -1); xmlSecAssert2(outSize >= inSize, -1); xmlSecAssert2(ctx != NULL, -1); xmlSecAssert2(ctx->pubPrivKey != 0, -1); xmlSecAssert2(xmlSecBufferGetSize(&ctx->keyBuffer) == ctx->keySize, -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->cryptProvider, ctx->pubPrivKey, ctx->algorithmIdentifier, 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); /* 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(!CryptDecrypt(cryptKey, 0, FALSE, 0, out, &dwCLen)) { xmlSecError(XMLSEC_ERRORS_HERE, NULL, "CryptEncrypt", XMLSEC_ERRORS_R_CRYPTO_FAILED, XMLSEC_ERRORS_NO_MESSAGE); CryptDestroyKey(cryptKey); return(-1); } /* cleanup */ CryptDestroyKey(cryptKey); return(dwCLen); }