Hwid to clipboard - c++

So this is what i am trying todo i am trying to copy serial number to clipboard but it doesnt work is there anything i did wrong if yes then plz help me i would like to have this working becouse its something for a project of me that i am selling
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "windows.h"
namespace std {}
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR volumeName[MAX_PATH + 1] = { 0 };
TCHAR fileSystemName[MAX_PATH + 1] = { 0 };
DWORD serialNumber = 0;
DWORD maxComponentLen = 0;
DWORD fileSystemFlags = 0;
if (GetVolumeInformation(
_T("C:\\"),
volumeName,
ARRAYSIZE(volumeName),
& serialNumber,
& maxComponentLen,
& fileSystemFlags,
fileSystemName,
ARRAYSIZE(fileSystemName)))
{
_tprintf(_T("Serial Number: %lu\n"), serialNumber);
GlobalUnlock(GetVolumeInformation);
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(1, GetVolumeInformation);
CloseClipboard();
MessageBoxA(NULL, "HWID COPYED.", "HWID", NULL);
std::cout << std::endl << "Press any key to continue...";
getchar();
}
}

You should avoid using the T macros (the macros starting with _T and _t). Microsoft still uses these macros in some of its documentations for historical reasons, but it's useless and confusing. I don't know if you are using ANSI or Unicode (Unicode is recommended).
If you only need the serial number from GetVolumeInformation then you can set the other variables to NULL, see documentation.
Once you get the serial number, convert it to text. Then copy the text to clipboard. Below is ANSI example:
void copy(const char* text)
{
int len = strlen(text) + 1;
HGLOBAL hmem = GlobalAlloc(GMEM_MOVEABLE, len);
char* buffer = (char*)GlobalLock(hmem);
strcpy_s(buffer, len, text);
GlobalUnlock(hmem);
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_TEXT, hmem);
CloseClipboard();
}
int _tmain()
{
DWORD serialNumber = 0;
if (GetVolumeInformation(
_T("C:\\"),
NULL,
0,
&serialNumber,
NULL,
0,
NULL,
0))
{
std::cout << serialNumber << std::endl;
char buf[100];
sprintf_s(buf, 100, "%d", serialNumber);
copy(buf);
MessageBoxA(NULL, buf, "HWID", NULL);
}
return 0;
}

Related

How to get extended port information when enumerating ports using Windows API

I'm using some legacy code to enumerate ports on my machine:
#include <windows.h>
#include <devguid.h>
#include <setupapi.h>
#include <string>
#include <iostream>
#include <assert.h>
bool GetTextProperty( std::string& sProperty,
HDEVINFO dev,
_SP_DEVINFO_DATA* pDeviceInfoData,
DWORD prop )
{
char szBuf[MAX_PATH];
DWORD iPropertySize = 0;
if (SetupDiGetDeviceRegistryProperty(dev, pDeviceInfoData,
prop, 0L, (PBYTE) szBuf, MAX_PATH, &iPropertySize))
{
sProperty = szBuf;
assert( iPropertySize >= sProperty.size() + 1 );
return true;
}
return false;
}
inline bool readRegistryKeyValue( HKEY hKey, const std::string& key, std::string& value )
{
bool res = false;
CHAR szBuffer[512];
DWORD dwBufferSize = sizeof(szBuffer);
ULONG nError = RegQueryValueEx(hKey, key.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
if (ERROR_SUCCESS == nError)
{
value = szBuffer;
res = true;
}
return res;
}
void ListPorts()
{
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i;
hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, 0L, 0L, DIGCF_PRESENT);
if ( hDevInfo == INVALID_HANDLE_VALUE )
{
//Medoc_ReportError(MEDOC_ERROR_HARDWARE_DRIVER_API_FAILED,
// &hDevInfo, sizeof hDevInfo);
assert( false );
}
else
{
// Enumerate through all devices in Set.
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData) != 0; i++)
{
char szBuf[MAX_PATH];
short wImageIdx = 0;
short wItem = 0;
DWORD iPropertySize;
if (SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData,
SPDRP_FRIENDLYNAME, 0L, (PBYTE) szBuf, MAX_PATH, &iPropertySize))
{
std::cout << "Smart name: " << szBuf << std::endl;
HKEY hKey = SetupDiOpenDevRegKey(
hDevInfo,
&DeviceInfoData,
DICS_FLAG_GLOBAL,
0,
DIREG_DEV,
KEY_READ );
if ( hKey )
{
std::string portName;
readRegistryKeyValue( hKey, "PortName", portName );
std::cout << "Port name: " << szBuf << std::endl;
for ( DWORD prop = 0; prop != SPDRP_MAXIMUM_PROPERTY; ++prop )
{
std::string temp;
GetTextProperty( temp, hDevInfo, &DeviceInfoData, prop );
std::cout << prop << " : " << temp << std::endl;
}
RegCloseKey(hKey);
}
}
}
}
// Cleanup
SetupDiDestroyDeviceInfoList(hDevInfo);
}
int main( int argc, char* argv[] )
{
ListPorts();
return 0;
}
Among other information, this gives me access to port name (COM*), type (FTDI for instance), VID and PID...
However, when I have many different devices based on a FTDI chip plugged, they all have the same information (SPDRP_HARDWAREID prperty reports FTDIBUS\COMPORT&VID_0403&PID_6015 or FTDIBUS\COMPORT&VID_0403&PID_6010). So I cannot discriminate who is who.
When I use a USB sniffer ("Device Monitoring Studio"), this one is able to report more relevant information withoutestablishing any connection to the ports:
Can this kind of extended information be accessed through Windows API to discriminate by name many devices using the same FTDI chip? Or must I use FTDI driver API to achieve this?
With the help of Ben Voigt and Simon Mourier, I could achieve this, here is the piece of code:
// More includes:
#include <initguid.h>
#include <devpkey.h>
#include <cfgmgr32.h>
// A new dependency:
#pragma comment (lib, "Cfgmgr32.lib")
bool GetDeviceProperty( const std::string& what,
DEVINST dev,
DEVPROPKEY prop )
{
char szDeviceBuf[MAX_PATH];
DEVPROPTYPE type;
ULONG iDevicePropertySize = MAX_PATH;
if ( CM_Get_DevNode_PropertyW(dev,
&prop,
&type,
(PBYTE) szDeviceBuf,
&iDevicePropertySize,
0) == CR_SUCCESS )
{
wchar_t* txt = (wchar_t*) szDeviceBuf;
std::wstring ws(txt);
std::cout << what << " : " << std::string(ws.begin(), ws.end()) << std::endl;
return true;
}
else
{
return false;
}
}
void ListPorts()
{
...
DEVINST devInstParent;
auto status = CM_Get_Parent(&devInstParent, DeviceInfoData.DevInst, 0);
if (status == CR_SUCCESS)
{
ShowDeviceProperty( "Bus reported device description", devInstParent, DEVPKEY_Device_BusReportedDeviceDesc );
ShowDeviceProperty( "Device description", devInstParent, DEVPKEY_Device_DeviceDesc );
}
else
{
continue;
}
...

Pipes doesn't work in WinApi on Windows 7 but works on Windows 10

I made a server and a client in winapi.
Client sends an number and a base and the server returns the number in that base.
My problem that it works in Windows 10, but it doesn't work in Windows 7 and I don't understand why. Some help?
Client:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <assert.h>
#include <windows.h>
#include <string>
#define BUFFSIZE 512
using namespace std;
int main()
{
LPDWORD bytesRead = 0;
char res[50];
int num, base;
LPCTSTR Roura = TEXT("\\\\.\\pipe\\pipeline");
HANDLE h = CreateFile(Roura, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
while (true) {
for (int i = 0; i < 50; i++) {
res[i] = 0;
}
printf("Number: ");
cin >> num;
WriteFile(h, &num, sizeof(int), NULL, NULL);
if (num == 0) {
CloseHandle(h);
return 0;
}
printf("Base: ");
cin >> base;
WriteFile(h, &base, sizeof(int), NULL, NULL);
ReadFile(h, res, BUFFSIZE, bytesRead, NULL);
cout << res << endl;
}
return 0;
}
Server:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <assert.h>
#include <windows.h>
#include <string>
#define _CRT_SECURE_NO_WARNINGS
#define BUFFSIZE 512
using namespace std;
int main()
{
int num, base;
LPDWORD bytesRead = 0;
char result[50];
char end[] = {"\0"};
LPCTSTR Roura = TEXT("\\\\.\\pipe\\pipeline");
HANDLE h = CreateNamedPipe(Roura, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, BUFFSIZE, BUFFSIZE, 0, NULL);
assert(h != INVALID_HANDLE_VALUE);
if (!ConnectNamedPipe(h, NULL)) return -1;
while (true) {
ReadFile(h, &num, BUFFSIZE, bytesRead, NULL);
if (num == 0) {
CloseHandle(h);
return 0;
}
ReadFile(h, &base, BUFFSIZE, bytesRead, NULL);
_itoa(num, result, base);
WriteFile(h, result, strlen(result), NULL, NULL);
}
return 0;
}
#define BUFFSIZE 512
int num, base;
LPDWORD bytesRead = 0;
ReadFile(h, &num, BUFFSIZE, bytesRead, NULL);
this code complete of errors. need use
int num, base;
DWORD bytesRead;
ReadFile(h, &num, sizeof(num), &bytesRead, NULL);
instead. crash faster of all by bytesRead== 0
when
If lpOverlapped is NULL, lpNumberOfBytesRead cannot be NULL.
however this true on win7, but on say win10 - system let have lpNumberOfBytesRead == 0 - so no crash here
also this
WriteFile(h, &num, sizeof(int), NULL, NULL);
again - here already only 1 error compare ReadFile call
If lpOverlapped is NULL, lpNumberOfBytesWritten cannot be NULL.
why ?
that it works in Windows 10, but it doesn't work in Windows 7
this is because begin from win 8.1 (if I not mistake) code of ReadFile/WriteFile check lpNumberOfBytes parameter and if it ==0 not assign to it actual number of bytes read or written. but on windows 7 system not do this check and unconditionally write data by 0 address

Encountering seg fault in wininet ftp program

So i found this c++ program and i thought i would use it to automate backing up my files to my desktop ftp server but it always runs into the same seg fault problem, After checking the ftp server logs i can see that is does actually connect to the ftp server and log in with the user name and password but it when it reaches the actual upload part it crashes.
I ran it through the debugger in dev c++ and it says "Access violation (Seg faut)"
Is this a bug in wininet? and if so is there some sort of workaround?
#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet")
#include <fstream>
#include <string.h>
int send(const char * ftp, const char * user, const char * pass, const char * pathondisk, char * nameonftp)
{
HINTERNET hInternet;
HINTERNET hFtpSession;
hInternet = InternetOpen(NULL,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
if(hInternet==NULL)
{
cout << GetLastError();
//system("PAUSE");
return 1;
}
hFtpSession = InternetConnect(hInternet,
(LPTSTR)ftp, INTERNET_DEFAULT_FTP_PORT,
(LPTSTR)user, (LPTSTR)pass, INTERNET_SERVICE_FTP,
INTERNET_FLAG_PASSIVE, 0);
if(hFtpSession==NULL)
{
cout << GetLastError();
//system("PAUSE");
return 1;
}
Sleep(1000);
char * buf=nameonftp;
strcat(buf,".txt");
if (!FtpPutFile(hFtpSession, (LPTSTR)pathondisk, (LPTSTR)buf, FTP_TRANSFER_TYPE_ASCII, 0)) {
cout << GetLastError();//this is never reached
return 1;
}
Sleep(1000);
InternetCloseHandle(hFtpSession);
InternetCloseHandle(hInternet);
return 0;
}
int main() {
send("127.0.0.1","testuser","test","file.pdf","backup");
return 0;
}
You must not modify string literals. Copy the string to a new buffer to edit the contents.
Also, you should use hogeA() APIs to have the system use ANSI charset explicitly.
Try this:
#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet")
#include <iostream>
#include <fstream>
#include <string.h>
using std::cout;
int send(const char * ftp, const char * user, const char * pass, const char * pathondisk, const char * nameonftp)
{
HINTERNET hInternet;
HINTERNET hFtpSession;
hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if(hInternet==NULL)
{
cout << GetLastError();
//system("PAUSE");
return 1;
}
hFtpSession = InternetConnectA(hInternet,
ftp, INTERNET_DEFAULT_FTP_PORT,
user, pass, INTERNET_SERVICE_FTP,
INTERNET_FLAG_PASSIVE, 0);
if(hFtpSession==NULL)
{
cout << GetLastError();
//system("PAUSE");
return 1;
}
Sleep(1000);
char * buf=new char[strlen(nameonftp) + 4 + 1];
strcpy(buf, nameonftp);
strcat(buf, ".txt");
if (!FtpPutFileA(hFtpSession, pathondisk, buf, FTP_TRANSFER_TYPE_ASCII, 0)) {
cout << GetLastError();
delete[] buf;
return 1;
}
delete[] buf;
Sleep(1000);
InternetCloseHandle(hFtpSession);
InternetCloseHandle(hInternet);
return 0;
}
int main() {
send("127.0.0.1", "testuser", "test", "file.pdf", "backup");
return 0;
}

Slightly different SHA256 on windows and linux

The code below generates SHA256 hash on Windows. As you can see it produces the hash from text "doublecheck" (5/NK+1ZAwTjzTY1PjZm0xcPRDf6KMQhmE4SVQnPOQ3M=)
I've created the code in the linux which should produce same hash, but it is different. (5/NK+1ZAwTjzTY1PjZm0xcPRDf6KMQhmE4SVQnPOQ3O/enx3tzCun78sgwQIOK6fv1T6eLc=)
Could anybody help me to fix any of those codes to get the same hashes?
Windows code:
#include "stdafx.h"
#include "Hash2.h"
#include <Wincrypt.h>
#pragma comment(lib, "Crypt32.lib")
DWORD BufSize;
#define BUF_SIZE 256
TCHAR Buf[BUF_SIZE];
CStringA BinaryToBase64(__in const byte * pbBinary, __in DWORD cbBinary)
{
ATLASSERT(pbBinary != NULL);
if (pbBinary == NULL)
AtlThrow(E_POINTER);
ATLASSERT(cbBinary != 0);
if (cbBinary == 0)
AtlThrow(E_INVALIDARG);
DWORD cchBase64;
if (!CryptBinaryToStringA(pbBinary, cbBinary, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &cchBase64))
{
AtlThrowLastWin32();
}
CStringA strBase64;
LPSTR pszBase64 = strBase64.GetBuffer(cchBase64);
ATLASSERT(pszBase64 != NULL);
if (!CryptBinaryToStringA(pbBinary, cbBinary, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, pszBase64, &cchBase64))
AtlThrowLastWin32();
strBase64.ReleaseBuffer();
return strBase64;
}
// creates sha256 hash from string
LPCSTR CreateHash(LPCSTR tohash)
{
HCRYPTPROV hProv;
HCRYPTHASH hash;
if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
if (CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hash))
{
int sz = strlen(tohash);
if (CryptHashData(hash, (BYTE *)tohash, sz, 0))
{
ZeroMemory(&Buf, sizeof(Buf));
BufSize = sizeof(Buf);
if (!CryptGetHashParam(hash, HP_HASHVAL, (BYTE *)&Buf, &BufSize, 0))
AtlThrowLastWin32();
}
else
AtlThrowLastWin32();
if (!CryptDestroyHash(hash))
AtlThrowLastWin32();
}
else
AtlThrowLastWin32();
if (!CryptReleaseContext(hProv, 0))
AtlThrowLastWin32();
}
else
AtlThrowLastWin32();
CStringA stemp = BinaryToBase64(reinterpret_cast<BYTE *>(Buf), BufSize).Trim();
int sizeOfString = (stemp.GetLength() + 1);
LPSTR retVal = new char[sizeOfString];
strcpy_s(retVal, sizeOfString, stemp);
return retVal;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
LPCSTR text = "doublecheck";
LPCSTR hash = CreateHash(text);
printf("\"%s\" hashed = %s", text, hash);
//output: "doublecheck" hashed = 5/NK+1ZAwTjzTY1PjZm0xcPRDf6KMQhmE4SVQnPOQ3M=
getchar();
}
Linux code:
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/crypto.h>
int Base64Encode(const char* message, char** buffer) { //Encodes a string to base64
BIO *bio, *b64;
FILE* stream;
int encodedSize = 4*ceil((double)strlen(message)/3);
*buffer = (char *)malloc(encodedSize+1);
stream = fmemopen(*buffer, encodedSize+1, "w");
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stream, BIO_NOCLOSE);
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); //Ignore newlines - write everything in one line
// edit: bad code BIO_write(bio, message, strlen(message));
BIO_write(bio, message, SHA256_DIGEST_LENGTH); // edit: correction
BIO_flush(bio);
BIO_free_all(bio);
fclose(stream);
return (0); //success
}
int main() {
unsigned char digest[SHA256_DIGEST_LENGTH];
const char* string = "doublecheck";
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, string, strlen(string));
SHA256_Final(digest, &ctx);
printf("SHA256 digest: %s\n", digest);
char* base64EncodeOutput;
Base64Encode((char*)digest, &base64EncodeOutput);
printf("Output (base64): %s\n", base64EncodeOutput);
// now the output here is: 5/NK+1ZAwTjzTY1PjZm0xcPRDf6KMQhmE4SVQnPOQ3M=
return 0;
}

C++ FTP writing to file is not working

I wrote this code that is SUPPOSED to write to a file on an ftp server, but it doesn't work. The file stays 0 bytes. There are also no errors. Here's my code:
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
int main()
{
int error=0;
char buffer[256];
char *text="Hello world.";
HINTERNET hOpen=InternetOpen("",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,INTERNET_FLAG_PASSIVE);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hOpen:%d:%s\n",error,buffer);
HINTERNET hConnect=InternetConnect(hOpen,"diabloip.host22.com",INTERNET_DEFAULT_FTP_PORT,"MY_USER_NAME","MY_PASSWORD",INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hConnect:%d:%s\n",error,buffer);
HINTERNET hFile=FtpOpenFile(hConnect,"diabloip.host22.com/public_html/log.txt",GENERIC_WRITE,FTP_TRANSFER_TYPE_ASCII,0);
InternetGetLastResponseInfo((LPDWORD)error,(LPSTR)buffer,(LPDWORD)256);
printf("hFile:%d:%s\n",error,buffer);
InternetWriteFile(hFile,text,strlen(text),NULL);
return 0;
}
The problem is passing NULL as the last parameter to InternetWriteFile. It is not an optional parameter and if you had error checking for that call as the rest you'd see GetLastError returns 87, or ERROR_INVALID_PARAMETER.
This works correctly and cleans up some of the other issues with incorrect parameters and the excessive casting that masks the issues.
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
#pragma comment(lib, "wininet.lib")
void PrintStatus(const char* title)
{
DWORD error = 0;
DWORD sz = 256;
char buffer[256];
InternetGetLastResponseInfo(&error, buffer, &sz);
printf("%s:%u:%s\n", title, error, buffer);
}
int main()
{
const char *text = "Hello world.";
HINTERNET hOpen = InternetOpen("", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_PASSIVE);
PrintStatus("hOpen");
HINTERNET hConnect = InternetConnect(hOpen, "localhost", INTERNET_DEFAULT_FTP_PORT, "test", "test", INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
PrintStatus("hConnect");
HINTERNET hFile = FtpOpenFile(hConnect, "log.txt", GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII, 0);
PrintStatus("hFile");
DWORD wb = 0;
BOOL Success = InternetWriteFile(hFile, text, strlen(text), &wb);
if(!Success)
{
DWORD err = GetLastError();
printf("InternetWriteFile - Error = %u\n", err);
}
PrintStatus("InternetWriteFile");
InternetCloseHandle(hOpen);
return 0;
}