Пример #1
0
//-----------------------------------------------------------------------------
// swCryptEncryptData()
//-----------------------------------------------------------------------------
// [in] iv = vecteur d'initialisation
// [in/out] pData = pointeur vers les données à chiffrer / chiffrées
// [in] lData = taille des données à chiffrer (lData en entrée = lData en sortie)
// [in] hKey = clé de chiffrement
//-----------------------------------------------------------------------------
// Retour : 0 si OK
//-----------------------------------------------------------------------------
int swCryptEncryptData(unsigned char *iv, unsigned char *pData,DWORD lData,HCRYPTKEY hKey)
{
	TRACE((TRACE_ENTER,_F_,""));
	BOOL brc;
	int rc=-1;
	DWORD dwMode=CRYPT_MODE_CBC;

	brc=CryptSetKeyParam(hKey,KP_IV,iv,0);
	if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptSetKeyParam(KP_IV)")); goto end; }
	brc=CryptSetKeyParam(hKey,KP_MODE,(BYTE*)&dwMode,0);
	if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptSetKeyParam(KP_MODE)")); goto end; }

	brc=CryptEncrypt(hKey,0,TRUE,0,pData,&lData,lData+16);
	if (!brc) 
	{
		TRACE((TRACE_ERROR,_F_,"CryptEncrypt()=0x%08lx",GetLastError()));
		goto end;
	}
	TRACE_BUFFER((TRACE_DEBUG,_F_,iv,16,"iv"));
	TRACE_BUFFER((TRACE_DEBUG,_F_,pData,64,"Donnees chiffrees"));
	TRACE_BUFFER((TRACE_DEBUG,_F_,pData+64,16,"ov"));
	rc=0;
end:
	TRACE((TRACE_LEAVE,_F_,"rc=%d",rc));
	return rc;
}
Пример #2
0
BOOL kuhl_m_dpapi_vault_key_type(PKULL_M_CRED_VAULT_CREDENTIAL_ATTRIBUTE attribute, HCRYPTPROV hProv, BYTE aes128[AES_128_KEY_SIZE], BYTE aes256[AES_256_KEY_SIZE], HCRYPTKEY *hKey, BOOL *isAttr)
{
	BOOL status = FALSE;
	DWORD mode = CRYPT_MODE_CBC, calgId, keyLen;
	LPCVOID key;

	*isAttr = attribute->id && (attribute->id < 100);
	if(*isAttr)
	{
		calgId = CALG_AES_128;
		key = aes128;
		keyLen = AES_128_KEY_SIZE;
		
	}
	else
	{
		calgId = CALG_AES_256;
		key = aes256;
		keyLen = AES_256_KEY_SIZE;
	}

	if(status = kull_m_crypto_hkey(hProv, calgId, key, keyLen, 0, hKey, NULL))
	{
		CryptSetKeyParam(*hKey, KP_MODE, (LPCBYTE) &mode, 0);
		if(attribute->szIV && attribute->IV)
			CryptSetKeyParam(*hKey, KP_IV, attribute->IV, 0);
	}
	return status;
}
Пример #3
0
bool Crypt::GeneratePrivateKey()
{
	// Acquire a provider handle for party 1.
	BOOL fReturn = CryptAcquireContext( &m_ProvParty, NULL, MS_ENH_DSS_DH_PROV, PROV_DSS_DH, CRYPT_VERIFYCONTEXT );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	// Create an ephemeral private key for party 1.
	// 임시 비밀 키 생성 
	fReturn = CryptGenKey( m_ProvParty, CALG_DH_EPHEM, DHKEYSIZE << 16 | CRYPT_EXPORTABLE | CRYPT_PREGEN, &m_PrivateKey );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	// Set the prime for party 1's private key.
	// P값 설정 
	fReturn = CryptSetKeyParam( m_PrivateKey, KP_P, (PBYTE)&m_P, 0 );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	// Set the generator for party 1's private key.
	// 비밀 키 생성기 장착
	fReturn = CryptSetKeyParam( m_PrivateKey, KP_G, (PBYTE)&m_G, 0 );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	// Generate the secret values for party 1's private key.
	// 비밀 키 생성 
	fReturn = CryptSetKeyParam( m_PrivateKey, KP_X, NULL, 0 );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	return true;
}
Пример #4
0
CryptoKey::CryptoKey(HCRYPTPROV cryptProv, const ByteVector& keyMaterial, const ByteVector& iv)
         :handle(NULL)
{
    if (keyMaterial.size() != 0x10)
        throw logic_error("Invalid key length. Expected 128b");
    if (iv.size() != 0x10)
        throw logic_error("Invalid IV length. Expected 128b");

    byte_t blobHeader[] = { 
        // Header
        0x08,                               //plaintextblob
        CUR_BLOB_VERSION, 
        0x00, 0x00,
        ALG_SID_AES_128, 0x66, 0x00, 0x00,  //ALG_ID
        0x10, 0x00, 0x00, 0x00};            //key length in bytes
    
    ByteVector keyToImport;
    keyToImport.append(blobHeader, sizeof(blobHeader));
    keyToImport.append(keyMaterial);

    // import key
    TOE(CryptImportKey(cryptProv, keyToImport.c_ptr(), static_cast<DWORD>(keyToImport.size()),
                       0, 0, &handle), "CryptImportKey");
    
    // set IV
    TOE(CryptSetKeyParam(handle, KP_IV, const_cast<byte_t*>(iv.c_ptr()), 0), "CryptSetKeyParam(IV)");
}
Пример #5
0
void Widget::on_IVErr_clicked()
{
    BYTE *iv, *srcData, *newData, *blockData1, *blockData2;
    DWORD ivLen, blockLen = 0;
    HCRYPTPROV hCryptProv;
    HCRYPTKEY hKey, newHKey;
    QVector<int> values;
    QFile myFile(fName);

    plot->clear();
    if (myFile.exists())
        myFile.open(QIODevice::ReadOnly);
    else
    {
        QMessageBox::critical(0, "Ошибка", "Файл не выбран", QMessageBox::Ok);
        return;
    }
    CryptAcquireContext(&hCryptProv, NULL, MS_DEF_RSA_SCHANNEL_PROV, PROV_RSA_SCHANNEL, CRYPT_VERIFYCONTEXT);
    CryptGenKey(hCryptProv, CALG_AES_256, 0, &hKey);
    CryptEncrypt(hKey, 0, true, 0, NULL, &blockLen, myFile.size());
    srcData = new BYTE[block * blockLen];
    newData = new BYTE[block * blockLen];
    blockData1  = new BYTE[blockLen];
    blockData2  = new BYTE[blockLen];
    myFile.read((char*)srcData, block * blockLen);
    myFile.close();
    memcpy((char*)newData, (char*)srcData, block * blockLen);
    newData[0] = -newData[0];
    CryptDuplicateKey(hKey, NULL, 0, &newHKey);
    CryptGetKeyParam(newHKey, KP_IV, NULL, &ivLen, 0);
    iv = new BYTE[ivLen];
    CryptGetKeyParam(newHKey, KP_IV, iv, &ivLen, 0);
    iv[0] = -iv[0];
    CryptSetKeyParam(newHKey, KP_IV, iv, 0);
    for (uint i = 0; i < (block * blockLen); i++)
    {
        CryptEncrypt(hKey, 0, i < 2, 0, srcData + i, &blockLen, block * blockLen);
        CryptEncrypt(newHKey, 0, i < 2, 0, newData + i, &blockLen, block * blockLen);
    }
    for(uint i = 0; i < (block * blockLen); i += blockLen)
    {
        int k = 0;
        memcpy(blockData1, srcData + i, blockLen);
        memcpy(blockData2, newData + i, blockLen);
        for (uint j = i; j < (i + blockLen); j++)
            k += trueBitsCount(srcData[j] ^ newData[j]);
        values.push_back(k);
    }
    delete[] newData;
    delete[] srcData;
    delete[] blockData1;
    delete[] blockData2;
    delete[] iv;
    CryptReleaseContext(hCryptProv, 0);
    CryptDestroyKey(hKey);
    CryptDestroyKey(newHKey);
    DrawPlot(plot, values);
    plot->show();
}
Пример #6
0
//-----------------------------------------------------------------------------
// swCryptDecryptDataAES()
//-----------------------------------------------------------------------------
// [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 swCryptDecryptDataAES256(unsigned char *iv, unsigned char *pData,DWORD lData,HCRYPTKEY hKey)
{
	TRACE((TRACE_ENTER,_F_,""));
	int rc=-1;
	BOOL brc;
	DWORD dwMode=CRYPT_MODE_CBC;

	brc=CryptSetKeyParam(hKey,KP_IV,iv,0);
	if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptSetKeyParam(KP_IV)")); goto end; }
	brc=CryptSetKeyParam(hKey,KP_MODE,(BYTE*)&dwMode,0);
	if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptSetKeyParam(KP_MODE)")); 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;
}
Пример #7
0
void * aes_encrypt_init(const u8 *key, size_t len)
{
	struct aes_context *akey;
	struct {
		BLOBHEADER hdr;
		DWORD len;
		BYTE key[16];
	} key_blob;
	DWORD mode = CRYPT_MODE_ECB;

	if (len != 16)
		return NULL;

	key_blob.hdr.bType = PLAINTEXTKEYBLOB;
	key_blob.hdr.bVersion = CUR_BLOB_VERSION;
	key_blob.hdr.reserved = 0;
	key_blob.hdr.aiKeyAlg = CALG_AES_128;
	key_blob.len = len;
	os_memcpy(key_blob.key, key, len);

	akey = os_zalloc(sizeof(*akey));
	if (akey == NULL)
		return NULL;

	if (!CryptAcquireContext(&akey->prov, NULL,
				 MS_ENH_RSA_AES_PROV, PROV_RSA_AES,
				 CRYPT_VERIFYCONTEXT)) {
 		wpa_printf(MSG_DEBUG, "CryptoAPI: CryptAcquireContext failed: "
			   "%d", (int) GetLastError());
		os_free(akey);
		return NULL;
	}

	if (!CryptImportKey(akey->prov, (BYTE *) &key_blob, sizeof(key_blob),
			    0, 0, &akey->ckey)) {
 		wpa_printf(MSG_DEBUG, "CryptoAPI: CryptImportKey failed: %d",
			   (int) GetLastError());
		CryptReleaseContext(akey->prov, 0);
		os_free(akey);
		return NULL;
	}

	if (!CryptSetKeyParam(akey->ckey, KP_MODE, (BYTE *) &mode, 0)) {
 		wpa_printf(MSG_DEBUG, "CryptoAPI: CryptSetKeyParam(KP_MODE) "
			   "failed: %d", (int) GetLastError());
		CryptDestroyKey(akey->ckey);
		CryptReleaseContext(akey->prov, 0);
		os_free(akey);
		return NULL;
	}

	return akey;
}
CryptAES::CryptAES(BYTE *pKey, BYTE *pIV)
{
    this->hProv = NULL;
    this->hKey = NULL;

    if (CryptAcquireContext(&this->hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) {
        AESKEY128 AESBlob;

        for (int i = 0; i < 16; i++)
            AESBlob.pKey[i] = pKey[i];

        CryptImportKey(this->hProv, reinterpret_cast<BYTE*>(&AESBlob), sizeof(AESBlob), NULL, 0, &this->hKey);

        if (this->hKey) {
            DWORD dwMode = CRYPT_MODE_CBC,
                  dwPadding = PKCS5_PADDING;
            CryptSetKeyParam(this->hKey, KP_IV, pIV, 0);
            CryptSetKeyParam(this->hKey, KP_MODE, reinterpret_cast<BYTE*>(&dwMode), 0);
            CryptSetKeyParam(this->hKey, KP_PADDING, reinterpret_cast<BYTE*>(&dwPadding), 0);
        }
    }
}
Пример #9
0
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");
}
Пример #10
0
static int
xmlSecMSCryptoKWDes3BlockDecrypt(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(!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);
}
Пример #11
0
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;

}
DWORD aes_Decrypt(LPBYTE key, DWORD SizeKey, LPBYTE iv, LPBYTE Data, LPDWORD SizeData)
{
    HCRYPTPROV provider = NULL;
    HCRYPTKEY hKey = NULL;
    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;
        }

        if (!CryptDecrypt(hKey, NULL, TRUE, 0, Data, SizeData)) {
            xstrerror("CryptDecrypt()");
            break;
        }

        Result = *SizeData; // Set return value to the decrypted data size
    } while (0);

    if (hKey != NULL) {
        CryptDestroyKey(hKey);
    }

    if (provider != NULL)   {
        CryptReleaseContext(provider, 0);
    }

    return Result;
}
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;
}
Пример #14
0
struct crypto_cipher * crypto_cipher_init(enum crypto_cipher_alg alg,
					  const u8 *iv, const u8 *key,
					  size_t key_len)
{	
	struct crypto_cipher *ctx;
	struct {
		BLOBHEADER hdr;
		DWORD len;
		BYTE key[32];
	} key_blob;
	DWORD mode = CRYPT_MODE_CBC;

	key_blob.hdr.bType = PLAINTEXTKEYBLOB;
	key_blob.hdr.bVersion = CUR_BLOB_VERSION;
	key_blob.hdr.reserved = 0;
	key_blob.len = key_len;
	if (key_len > sizeof(key_blob.key))
		return NULL;
	os_memcpy(key_blob.key, key, key_len);

	switch (alg) {
	case CRYPTO_CIPHER_ALG_AES:
		if (key_len == 32)
			key_blob.hdr.aiKeyAlg = CALG_AES_256;
		else if (key_len == 24)
			key_blob.hdr.aiKeyAlg = CALG_AES_192;
		else
			key_blob.hdr.aiKeyAlg = CALG_AES_128;
		break;
	case CRYPTO_CIPHER_ALG_3DES:
		key_blob.hdr.aiKeyAlg = CALG_3DES;
		break;
	case CRYPTO_CIPHER_ALG_DES:
		key_blob.hdr.aiKeyAlg = CALG_DES;
		break;
	case CRYPTO_CIPHER_ALG_RC2:
		key_blob.hdr.aiKeyAlg = CALG_RC2;
		break;
	case CRYPTO_CIPHER_ALG_RC4:
		key_blob.hdr.aiKeyAlg = CALG_RC4;
		break;
	default:
		return NULL;
	}

	ctx = os_zalloc(sizeof(*ctx));
	if (ctx == NULL)
		return NULL;

	if (!CryptAcquireContext(&ctx->prov, NULL, MS_ENH_RSA_AES_PROV,
				 PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
		cryptoapi_report_error("CryptAcquireContext");
		goto fail1;
	}

	if (!CryptImportKey(ctx->prov, (BYTE *) &key_blob,
			    sizeof(key_blob), 0, 0, &ctx->key)) {
 		cryptoapi_report_error("CryptImportKey");
		goto fail2;
	}

	if (!CryptSetKeyParam(ctx->key, KP_MODE, (BYTE *) &mode, 0)) {
 		cryptoapi_report_error("CryptSetKeyParam(KP_MODE)");
		goto fail3;
	}

	if (iv && !CryptSetKeyParam(ctx->key, KP_IV, (BYTE *) iv, 0)) {
 		cryptoapi_report_error("CryptSetKeyParam(KP_IV)");
		goto fail3;
	}

	return ctx;

fail3:
	CryptDestroyKey(ctx->key);
fail2:
	CryptReleaseContext(ctx->prov, 0);
fail1:
	os_free(ctx);
	return NULL;
}
Пример #15
0
int  main (int argc, char *argv[])
{


    DWORD dwProvType = 75;   
    DWORD data_len = 0;			    
    BYTE *oid = NULL;			    
    DWORD dwBlobLen = 0;		    
    DWORD cAlg = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 31);

	LPCSTR SourceName = NULL;
	LPCSTR Psdw = NULL;

	HANDLE hCurrProc = GetCurrentProcess();
	char patch[] = {0x80,0xbd,0x1c,0x00,0x00,0x00,0x98,0x75,0x07,0xc6,0x85,0x1c,0x00,0x00,0x00,0x9c,0x90,0x90,0x90,0x90,0x90,0x90}; ///!!!
	int patchLen = sizeof(patch);
	DWORD previous = 0;

	DWORD writeAddr = 0x11BC2;// INITIALIZED with offset!!!  //0x611E1BC2;


	/// PARSE COMMAND PARAMETERS HERE
	for (int n = 1;n < argc;n++) {
		if (n+1 >= argc)
			break;
		if (strcmp(argv[n],"-p") == 0) {
			Psdw = argv[++n];
		}
		if (strcmp(argv[n],"-s") == 0) {
			SourceName = argv[++n];
		}
	}
	if (!Psdw || !SourceName) {
		printf("[!] Dude, u specified incorrect parameters :/\n\tUsage: %s -s <source container name> -p <container password>",argv[0]);
		exit(1);
	}


    if(!CryptAcquireContextA(
	&hProvResponder, 
	"\\\\.\\Registry\\DestCopy", //Hardcoded name for container we create!!!
	NULL,
	dwProvType,
	CRYPT_NEWKEYSET | CRYPT_SILENT))
    {
		HandleError("Error during CryptAcquireContext");
    }


    if(!CryptAcquireContextA(
	&hProvSender, 
	SourceName, 
	NULL, 
	dwProvType, 
	0)) 
    {
		HandleError("Error during CryptAcquireContext");
    }

	/// FIND ADDRESS TO PATCH
	HMODULE hModules[1024];
	DWORD needed;
	if (EnumProcessModules(hCurrProc,hModules,1024,&needed)) {
		for (int i = 0; i < (needed / sizeof(HMODULE)); i++ )
        {
            char szModName[1024];

            if ( GetModuleFileNameA( hModules[i], szModName, sizeof(szModName)))
            {
				if (StrStrA(szModName, "cpcspi.dll")) {
					writeAddr += (DWORD)hModules[i];
					printf("[+] Address in memory for patching is '%08X'.\n",writeAddr);
					break;
				}
            }
        }
	}

	
	/// !!!
	printf("[+] Now we patch process memory, patch size is '%i' bytes...",patchLen);
	VirtualProtectEx(hCurrProc, (void*)writeAddr, 2, PAGE_EXECUTE_READWRITE, &previous);
	WriteProcessMemory(hCurrProc, (void*)writeAddr, &patch, patchLen, NULL);
	printf("Ok\n");

	printf("[+] Now we export container '%s'...\n",SourceName);

	if(!CryptGetProvParam( 
	hProvSender, 
	92, 
	NULL, 
	&data_len, 
	0))
    {
		HandleError("Error computing buffer length");
    }

    oid = (BYTE *)malloc( data_len );
    if( !oid )
		HandleError("Out of memory.");


    if(!CryptGetProvParam( 
	hProvSender, 
	92, 
	oid, 
	&data_len, 
	0))
    {
		HandleError("Error during CryptGetProvParam");
    }


    if(!CryptSetProvParam(
	hProvResponder, 
	92, 
	oid, 
	0 ))
    {
		free( oid );
		HandleError("Error during CryptSetProvParam");
    }

    free( oid );

    data_len = 0;


    if(!CryptGetProvParam( 
	hProvSender, 
	93, 
	NULL, 
	&data_len, 
	0))
    {
		HandleError("Error computing buffer length");
    }

	/// SPECIFY PASSWORD FOR CONTAINER HERE
	if(!CryptSetProvParam( hProvSender,PP_SIGNATURE_PIN,(LPBYTE)Psdw,0))
	{
	    HandleError("Error during CryptSetProvParam");
	}

    oid = (BYTE *)malloc( data_len );
    if( !oid )
		HandleError("Out of memory");

    if(!CryptGetProvParam( 
	hProvSender, 
	93, 
	oid, 
	&data_len, 
	0))
    {
		free( oid );
		HandleError("Error during CryptGetProvParam");
    }

    if(!CryptSetProvParam(
	hProvResponder, 
	93, 
	oid, 
	0 ))
    {
		free( oid );
		HandleError("Error during CryptSetProvParam");
    }
    free( oid );


    if(!CryptGetUserKey( 
	hProvSender, 
	AT_KEYEXCHANGE, 
	&hSenderKey )) 
    {
		HandleError("Error during CryptGetUserKey private key");
    }		

	
    if(!CryptGenKey(
	hProvSender, 
	(ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | 37), 
	CRYPT_EXPORTABLE, 
	&hSenderEphemKey)) 
    {
		HandleError("ERROR -- CryptGenKey");
    }
	
	
    if(!CryptGenKey(
	hProvResponder, 
	(ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | 37), 
	CRYPT_EXPORTABLE | CRYPT_PREGEN,
	&hResponderEphemKey))
    {
		HandleError("ERROR -- CryptGenKey");
    }
	
	
    if(!CryptGetKeyParam( 
	hSenderEphemKey, 
	106, 
	NULL, 
	&dwBlobLen, 
	0))
    {
		HandleError("Error computing BLOB length");
    }

    pbKeyBlob = (BYTE*)malloc(dwBlobLen);
    if(!pbKeyBlob)
		HandleError("Out of memory");


    if(!CryptGetKeyParam( 
	hSenderEphemKey, 
	106, 
	pbKeyBlob, 
	&dwBlobLen, 
	0))
    {
		HandleError("Error during CryptGetProvParam");
    }

    if(!CryptSetKeyParam(
	hResponderEphemKey, 
	106, 
	pbKeyBlob, 
	0))
    {
		HandleError("Error during CryptSetProvParam");
    }

    free(pbKeyBlob);
    pbKeyBlob = NULL; 
    dwBlobLen = 0;


    if(!CryptSetKeyParam(
	hResponderEphemKey, 
	KP_X, 
	NULL, 
	0))
    {
		HandleError("Error during CryptSetKeyParam");
    }

    if(!CryptExportKey(
	hSenderEphemKey,
	0, 
	PUBLICKEYBLOB,
	0, 
	NULL,
	&dwBlobLen ))
    {
		HandleError("Error computing BLOB length");
    }

    pbKeyBlob = (BYTE*)malloc(dwBlobLen);
    if(!pbKeyBlob) 
		HandleError("Out of memory");

    if(!CryptExportKey(
	hSenderEphemKey,
	0, 
	PUBLICKEYBLOB,
	0, 
	pbKeyBlob,
	&dwBlobLen ))
    {
		HandleError("Error during CryptExportKey");
    }


    if(!CryptImportKey(
	hProvResponder, 
	pbKeyBlob, 
	dwBlobLen, 
	hResponderEphemKey, 
	0, 
	&hResponderAgreeKey))
    {
		HandleError("Error during CryptImportKey ephemeral key");
    }


    free(pbKeyBlob);
    pbKeyBlob = NULL; 
    dwBlobLen = 0;


    if(!CryptExportKey(
	hResponderEphemKey,
	0, 
	PUBLICKEYBLOB,
	0, 
	NULL,
	&dwBlobLen ))
    {
		HandleError("Error computing BLOB length");
    }

    pbKeyBlob = (BYTE*)malloc(dwBlobLen);
    if(!pbKeyBlob) 
		HandleError("Out of memory");

    if(!CryptExportKey(
	hResponderEphemKey,
	0, 
	PUBLICKEYBLOB,
	0, 
	pbKeyBlob,
	&dwBlobLen ))
    {
		HandleError("Error during CryptExportKey");
    }

 

    if(!CryptImportKey(
	hProvSender, 
	pbKeyBlob, 
	dwBlobLen, 
	hSenderEphemKey, 
	0, 
	&hSenderAgreeKey))
    {
		HandleError("Error during CryptImportKey ephemeral key");
    }


    free(pbKeyBlob);
    pbKeyBlob = NULL; 
    dwBlobLen = 0;


    if(!CryptSetKeyParam(
	hSenderAgreeKey,
	KP_ALGID, 
	(BYTE*)&cAlg,
	0 ))
    {
		HandleError("Error during CryptSetKeyParam agree key");
    }


    if(!CryptSetKeyParam(
	hResponderAgreeKey,
	KP_ALGID, 
	(BYTE*)&cAlg,
	0 ))
    {
		HandleError("Error during CryptSetKeyParam agree key");
    }
	

    if(!CryptExportKey(
	hSenderKey,
	hSenderAgreeKey, 
	PRIVATEKEYBLOB,
	0, 
	NULL,
	&dwBlobLen ))
    {
		HandleError("Error computing BLOB length");
    }

    pbKeyBlob = (BYTE*)malloc(dwBlobLen);
    if(!pbKeyBlob) 
		HandleError("Out of memory");

    if(!CryptExportKey(
	hSenderKey,
	hSenderAgreeKey, 
	PRIVATEKEYBLOB,
	0, 
	pbKeyBlob,
	&dwBlobLen ))
    {
		HandleError("Error during CryptExportKey");
    }



    if(!CryptImportKey(
	hProvResponder, 
	pbKeyBlob, 
	dwBlobLen, 
	hResponderAgreeKey, 
	0,
	&hResponderKey))
    {
		HandleError("Error during CryptImportKey private key");
    }


    free(pbKeyBlob);
    pbKeyBlob = NULL; 
    dwBlobLen = 0;



    if(!CryptGetKeyParam( 
	hSenderKey, 
	KP_CERTIFICATE, 
	NULL, 
	&dwBlobLen, 
	0))
    {
		HandleError("Error computing BLOB length");
    }

    pbKeyBlob = (BYTE*)malloc(dwBlobLen);

    if(!pbKeyBlob)
    {
		HandleError("Out of memory");
    }


    if(!CryptGetKeyParam( 
	hSenderKey, 
	KP_CERTIFICATE, 
	pbKeyBlob, 
	&dwBlobLen, 
	0))
    {
		HandleError("Error during CryptGetProvParam");
    }

    if(!CryptSetKeyParam(
	hResponderKey, 
	KP_CERTIFICATE, 
	pbKeyBlob, 
	0))
    {
		HandleError("Error during CryptSetProvParam");
    }

	printf("[+] D0n3!!!\n");

    CleanUp();
    return 0;
}
Пример #16
0
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);
}
Пример #17
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);
}
Пример #18
0
bool Crypt::GenerateSessionKey( PBYTE keyBlob, DWORD dataLen )
{
	BOOL fReturn = CryptImportKey(
		m_ProvParty,
		keyBlob,
		dataLen,
		m_PrivateKey,
		0,
		&m_SessionKeyEn );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	fReturn = CryptImportKey(
		m_ProvParty,
		keyBlob,
		dataLen,
		m_PrivateKey,
		0,
		&m_SessionKeyDe );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	/************************
	Convert the agreed keys to symmetric keys. They are currently of
	the form CALG_AGREEDKEY_ANY. Convert them to CALG_RC4.
	************************/
	ALG_ID Algid = CALG_RC4;

	// Enable the party 1 public session key for use by setting the 
	// ALGID.
	fReturn = CryptSetKeyParam(
		m_SessionKeyEn,
		KP_ALGID,
		(PBYTE)&Algid,
		0 );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	fReturn = CryptSetKeyParam(
		m_SessionKeyDe,
		KP_ALGID,
		(PBYTE)&Algid,
		0 );
	if ( !fReturn )
	{
		ReleaseResources();
		return false;
	}

	// printf( "session key : %d\n", m_SessionKey );

	return true;
}
Пример #19
0
int Decrypt(char * inFile, char * outFile, char * keyFile) {	

// note: the IN_BUFFER_SIZE used here is purposely an even multiple of the
// various possible encryption block sizes, namely 1, 8, and 64 bytes.
const IN_BUFFER_SIZE    = 64 * 100; // needs to be multiple of block size.

	HANDLE      hInFile; 
	HANDLE		hOutFile;
	HANDLE		hKeyFile;
     BYTE        pbBuffer[IN_BUFFER_SIZE];
     BOOL        finished;
     HCRYPTPROV  hProvider = 0;
    HCRYPTKEY     hKey = 0, hExchangeKey = 0;
     DWORD       dwByteCount, dwBytesWritten;

	 //As in the Encrypt demo, we first need to get a handle to the default CSP.

     // Get handle for the default provider (use RSA encryption).
		DebugLog((DEST,"PrepContext"));
	 PrepContext(iWinVer, &hProvider);

     // Open infile and create outfile.
     hInFile = CreateFile(inFile, GENERIC_READ, FILE_SHARE_READ, 
         NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     hKeyFile = CreateFile(keyFile, 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);

//We now read in, in the same order as they were written, the key blob size and then the key blob itself. 

   // Import Key blob into "CSP"
	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;
}

//Next, we read encrypted data in, decrypt it using CryptDecrypt, and write the decrypted data to our output file. Like the CryptEncrypt function, CryptDecrypt takes a “finished” Boolean flag to tell it when we’re sending it the last buffer to decrypt.

     // Read data in, encrypt it, and write encrypted data to output file.
     do 
     {
          ReadFile(hInFile, pbBuffer, IN_BUFFER_SIZE, &dwByteCount,NULL);
          finished = (dwByteCount < IN_BUFFER_SIZE);
          CryptDecrypt(hKey, 0, finished, 0, pbBuffer, &dwByteCount);
          WriteFile(hOutFile, pbBuffer,dwByteCount,&dwBytesWritten,NULL);
     } while (!finished);
//We’re finished, so we now delete our key, release the CSP handle, and close the input and output files.

     // Clean up: release handles, close files.
	 CleanupCryptoKey(hExchangeKey);
     CleanupCryptoKey(hKey);

	 CleanupCryptoContext(hProvider);

     CloseHandle(hInFile);
     CloseHandle(hOutFile);
     CloseHandle(hKeyFile);
     return(0);
}
Пример #20
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);
}
Пример #21
0
/**
 * 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;
}
Пример #22
0
static BOOL
decodeSK( BOOL aes256, DWORD keylen, BYTE *keybuf )
{
    BYTE	buffer[ 1024 ];
    DWORD	i, size, length;

    struct skb
    {
	PUBLICKEYSTRUC	hdr;
	ALG_ID		algId;
	BYTE		key[1];
    }		*expKey = (struct skb *)buffer;

    struct ptkb
    {
	PUBLICKEYSTRUC	hdr;
	DWORD		keysize;
	BYTE		key[1];
    }		*txtKey = (struct ptkb *)buffer;

    length = (expKey->key - buffer) + keylen;

    if ( length > sizeof( buffer ) )
    {
	fprintf( stderr, "CryptImportKey() requires %d bytes\n", length );
	return( FALSE );
    }

    expKey->hdr.bType = SIMPLEBLOB;
    expKey->hdr.bVersion = CUR_BLOB_VERSION;
    expKey->hdr.reserved = 0;
    expKey->hdr.aiKeyAlg = aes256 ? SessKey256 : SessKey128;
    expKey->algId = XchgKeyType;

    /*
    ** NOTE: it appears that the encoded key is byte swapped compared
    ** to external standards.  There is a cryptic reference to a
    ** ReverseMemCopy() function in the RSA/SChannel server master
    ** key creation example.  Also, the internal RSA modulus is
    ** byte swapped compared to the X509 encoding.  This swap is
    ** required to interoperate with JavaSSE.
    */
    for( i = 0; i < keylen; i++ )
	expKey->key[i] = keybuf[ keylen - i - 1 ];

    if ( ! CryptImportKey( provider, (BYTE *)expKey, length, xchgKey, CRYPT_EXPORTABLE, &sessKey ) )
    {
	fprintf( stderr, "CryptImportKey() failed: 0x%x\n", GetLastError() );
	return( FALSE );
    }

    if ( ! CryptSetKeyParam( sessKey, KP_MODE, (BYTE *)&sessKeyMode, 0 ) )
    {
	fprintf( stderr, "CryptSetKeyParam() MODE failed: 0x%x\n", GetLastError() );
	return( 0 );
    }

    if ( ! CryptSetKeyParam( sessKey, KP_PADDING, (BYTE *)&sessKeyPadding, 0 ) )
    {
	fprintf( stderr, "CryptSetKeyParam() PADDING failed: 0x%x\n", GetLastError() );
	return( 0 );
    }

    if ( sessKeyMode == CRYPT_MODE_CBC )
    {
	size = sizeof( length );

	if ( ! CryptGetKeyParam( sessKey, KP_BLOCKLEN, (BYTE *)&length, &size, 0 ) )
	{
	    fprintf( stderr, "CryptGetKeyParam() BLOCKLEN failed: 0x%x\n", GetLastError() );
	    exit( 1 );
        }

	length /= 8;	/* Bits -> bytes */
	for( i = 0; i < length; i++ )  buffer[i] = 0;
	
	if ( ! CryptSetKeyParam( sessKey, KP_IV, buffer, 0 ) )
	{
	    fprintf( stderr, "CryptSetKeyParam() PADDING failed: 0x%x\n", GetLastError() );
	    return( 0 );
	}
    }

    if ( verbose )
    {
	if ( ! CryptExportKey( sessKey, 0, PLAINTEXTKEYBLOB, 0, NULL, &size ) )
	{
	    fprintf( stderr, "CryptExportKey() [1] failed: 0x%x\n", GetLastError() );
	    return( FALSE );
	}

	if ( size > sizeof( buffer ) )
	{
	    fprintf( stderr, "CryptExportKey() requires %d bytes\n", size );
	    return( FALSE );
	}

	length = sizeof( buffer );

	if ( ! CryptExportKey( sessKey, 0, PLAINTEXTKEYBLOB, 0, (BYTE *)txtKey, &length ) )
	{
	    fprintf( stderr, "CryptExportKey() [2] failed: 0x%x\n", GetLastError() );
	    return( FALSE );
	}

	printf( "Sess Key: \n" );
	hexDump( txtKey->keysize, txtKey->key );
	keyInfo( sessKey );
    }

    return( TRUE );
}
Пример #23
-1
BOOL kull_m_crypto_aesCTSDecrypt(HCRYPTKEY hKey, PBYTE data, DWORD szData, PBYTE pbIV)
{
	BOOL status = FALSE;
	DWORD nbBlock, lastLen, i;
	BYTE buffer[32], *ptr;
	HCRYPTKEY hKeyNoIV;

	if(szData > 16)
	{
		if(CryptDuplicateKey(hKey, NULL, 0, &hKeyNoIV))
		{
			if(CryptSetKeyParam(hKey, KP_IV, pbIV, 0))
			{
				nbBlock = (szData + 15) >> 4;
				lastLen = (szData & 0xf) ? (szData & 0xf) : 16;
				if (nbBlock <= 2 || kull_m_crypto_aesBlockEncryptDecrypt(hKey, data, nbBlock - 2, FALSE))
				{
					ptr = &data[16 * (nbBlock - 2)];
					RtlCopyMemory(buffer, ptr, lastLen + 16);
					RtlZeroMemory(&buffer[lastLen + 16], 16 - lastLen);
					if(kull_m_crypto_aesBlockEncryptDecrypt(hKeyNoIV, buffer, 1, FALSE))
					{
						for(i = 0; i < 16; i++)
							buffer[i] ^= buffer[i + 16];
						RtlCopyMemory(&buffer[lastLen + 16], &buffer[lastLen], 16 - lastLen);
						if(status = kull_m_crypto_aesBlockEncryptDecrypt(hKey, buffer + 16, 1, FALSE))
						{
							RtlCopyMemory(ptr, buffer + 16, 16);
							RtlCopyMemory(&data[16 * nbBlock - 16], buffer, lastLen);
						}
					}
				}
			}
			CryptDestroyKey(hKeyNoIV);
		}
	}