CryptGenRandom is giving same value while calling in loop - c++

Sorry, I cant use separate class for this and I tried to build following code and getting same output when calling from out side in loop.
unsigned int crypt_rand()
{
HCRYPTPROV hProvider = 0;
const DWORD dwLength = sizeof(unsigned int);
unsigned int pbBuffer[dwLength] = {};
if (!::CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
return 1;
if (!::CryptGenRandom(hProvider, sizeof(unsigned int), reinterpret_cast<PBYTE>(&pbBuffer)))
{
::CryptReleaseContext(hProvider, 0);
return 1;
}
if (!::CryptReleaseContext(hProvider, 0))
return 1;
return (unsigned int)pbBuffer;
}
If I am calling this function from loop getting same output every time.Is it anything I can give like input as time in this method.Can you plz help me on this?
for (DWORD i = 0; i < 5; ++i)
{
rand_no = crypt_rand();
std::cout << "windows::"<<i<<"::"<<rand_no<< std::endl;
}
Output is
windows::0::4519964
windows::1::4519964
windows::2::4519964
windows::3::4519964
windows::4::4519964

The use of casts (the reinterpret_cast and the one in the return statement) is hiding some important compiler errors that would have allowed you to write this code correctly in the first place.
Avoid the casts as much as you can, fix the types instead.
CryptGenRandom expects a
BYTE *pbBuffer
parameter. Pass it a pointer to an array of BYTE not anything else (you are passing a pointer to an array of int).
In your return statement you are casting an address to unsigned int. You need to take the BYTE array and convert the values it contains to an int (you can find examples of that online or you can make one yourself via sit shifts and additions). What you are doing now is probably outputting the same address (or part of it) over and over again.
To clarify, define your array as
BYTE pbBuffer[dwLength] = {};
and call your function as
::CryptGenRandom(hProvider, dwLength, pbBuffer)
Avoid casts, especially the C style casts, and read about arrays. In C++, when passed to a function an array decays to a pointer to the first element of the array. If you have an array of BYTE it will decay to a BYTE*, the expected type of your function.

The problem is in return (unsigned int)pbBuffer; here you are just getting address of pbBUffer everytime.If pbBuffer is an array and function crypt_rand is returning unsigned int then it should be elements of array at return.
You need to enable warnings during your compilation.These kind of possible errors must be there as warning.

You want a random number that is an unsigned int?
Just cast the contents of the BYTE buffer to an unsigned int
How about:
unsigned int crypt_rand()
{
HCRYPTPROV hProvider = 0;
const DWORD dwLength = sizeof(unsigned int);
BYTE buffer[dwLength];
if (!::CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
return 1;
if (!::CryptGenRandom(hProvider, sizeof(buffer), &buffer))
{
::CryptReleaseContext(hProvider, 0);
return 1;
}
if (!::CryptReleaseContext(hProvider, 0))
return 1;
return *(unsigned int*)buffer;
}

Related

Unable to understand libusb API

I am working in libusb and have minimal knowledge on C++. I am trying to understand the API of libusb and write code accordingly. But I am unable to understand how to declare and use variables as variable or pointer or double or triple pointer.
The below code is from question. How to find what level of pointers to be used while declaring these variables from the API documentation. Is there any documentation or tutorial videos that explains these things.
libusb_context *context = NULL ;
libusb_device_handle *dev_handle = NULL ;
libusb_device **devs ;
int rc = 0 ;
ssize_t count ; //holding number of devices in list
For example, consider libusb_device_handle. How to declare this and use it?
typedef struct libusb_device_handle libusb_device_handle
The syntax of libusb_strerror() is const char * libusb_strerror (int errcode). The function returns constant string. Should I declare a char or char array or string to read the returned value. If the below way of usage right?
char char *err_code;//declaration
err_code = libusb_strerror(rc);
if the returned value is a string, then how can a characer pointer hold it?
An example would be really helpful.
3)Here is my entire code. I can open the device. But the bulk transfer command returns 5 and fails. I am not sure at which part I am making mistake.
#include <iostream>
#include "libusb.h"
#define IN_EP 0x81
#define OUT_EP 0x02
int main(){
libusb_context *context = NULL;
libusb_device_handle *dev_handle = NULL ;
libusb_device **devs ;
int rc = 100 ;
//ssize_t count ; //holding number of devices in list
unsigned int vid=0x1234;
unsigned int pid=0x5678;
unsigned char data[10];
data[0]=128;
int transferred = 0;
unsigned int timeout = 5000;
//std::string str[100];
const char* err_code;
rc = libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL,2);
if (rc==0){ std::cout<<"libusb_setOption worked:"<<rc<<"\n"; }
else{ std::cout<<"libusb_setOption_Failed:"<<rc<<"\n"; }
rc = libusb_init(&context);
if (rc==0){ std::cout<<"libusb_init worked:"<<rc<<"\n"; }
else{ std::cout<<"libusb_init Failed"<<rc<<"\n"; }
dev_handle = libusb_open_device_with_vid_pid(context,vid,pid);
if (dev_handle == NULL){
std::cout<<"libusb_open Failed"<<"\n";
libusb_exit(context);std::cout<<"libusb_exit"<<"\n";exit(1); }
else{ std::cout<<"libusb_opened"<<"\n"; }
rc = libusb_bulk_transfer(dev_handle,OUT_EP,data,1,&transferred, timeout); //Send data to device
if (rc==0){ std::cout<<"libusb_write worked:"<<rc<<"; Wrote "<<transferred<<" bytes\n"; }
else{ std::cout<<"libusb__Write failed"<<rc<<"; Wrote "<<transferred<<" bytes\n"; }
err_code = libusb_strerror(rc);
rc = libusb_bulk_transfer(dev_handle,IN_EP,data,3,&transferred, timeout); //Read data from device
if (rc==0){ std::cout<<"libusb_read worked:"<<rc<<" ; Read"<<transferred<<" bytes; Data:"<<data<<"\n";
std::cout<<data[0]<<" "<<data[1]<<" "<<data[2]<<"\n"; }
else{ std::cout<<"libusb__read failed"<<rc<<"; Read "<<transferred<<" bytes\n"; }
libusb_close(dev_handle);
std::cout<<"libusb_close"<<"\n";
libusb_exit(context);
std::cout<<"libusb_close"<<"\n";
return 0;
}
Any help will be appreciated.
[...] For example, consider libusb_device_handle. How to declare this and use it?
You declare it exactly like in your code:
libusb_device_handle *dev_handle = NULL;
Because libusb_open_device_with_vid_pid() returns a pointer to libusb_device_handle, your dev_handle must also be a pointer to that.
You might be confused because of devs being a pointer-to-pointer. This is because it is actually returning a pointer to an array, but since you are not even using that in your code, I would forget about it for now.
The syntax of libusb_strerror() is const char * libusb_strerror (int errcode). The function returns constant string. Should I declare a char or char array or string to read the returned value?
You should declare a variable exactly the same as the return type of libusb_strerror(), thus:
const char *err_string;
err_string = libusb_strerror(rc);
If the returned value is a string, then how can a characer pointer hold it?
The returned value is a pointer, you just make a copy of the pointer. The pointer points to some part of memory where the string is stored. You don't have to worry about how libusb allocated it.
I can open the device. But the bulk transfer command returns 5 and fails. I am not sure at which part I am making mistake.
The code looks mostly fine, except you want to call libusb_strerror() after the second call to libusb_bulk_transfer(), not right before it. Error code -5 is LIBUSB_ERROR_NOT_FOUND. This might mean it didn't find the endpoint. Are you sure IN_EP and OUT_EP are set correctly?

go equivalents of c types

What are the right equivalent of unsigned char or unsigned char* in go? Or am I even doing this right?
I have this C++ class:
class ArcfourPRNG
{
public:
ArcfourPRNG();
void SetKey(unsigned char *pucKeyData, int iKeyLen);
void Reset();
unsigned char Rand();
private:
bool m_bInit;
unsigned char m_aucState0[256];
unsigned char m_aucState[256];
unsigned char m_ucI;
unsigned char m_ucJ;
unsigned char* m_pucState1;
unsigned char* m_pucState2;
unsigned char m_ucTemp;
};
I am trying to rewrite it to go:
type ArcfourPRNG struct {
m_bInit bool
m_aucState0 [256]byte
m_aucState [256]byte
m_ucI, m_ucJ []byte
*m_pucState1 []byte
*m_pucState2 []byte
m_ucTemp []byte
}
func (arc4 *ArcfourPRNG) SetKey(pucKeyData []byte, iKeyLen int) {
func (arc4 *ArcfourPRNG) Reset() {
func (arc4 *ArcfourPRNG) Rand() uint {
Well, I just started with go a few hours ago. So this is still confusing me.
A function
for(i=0; i<256; i++)
{
m_pucState1 = m_aucState0 + i;
m_ucJ += *m_pucState1 + *(pucKeyData+m_ucI);
m_pucState2 = m_aucState0 + m_ucJ;
//Swaping
m_ucTemp = *m_pucState1;
*m_pucState1 = *m_pucState2;
*m_pucState2 = m_ucTemp;
m_ucI = (m_ucI + 1) % iKeyLen;
}
memcpy(m_aucState, m_aucState0, 256); // copy(aucState[:], aucState0) ?
Hopefully this can clear a few things up for you.
For storing raw sequences of bytes, use a slice []byte. If you know exactly how long the sequence will be, you can specify that, e.g. [256]byte but you cannot resize it later.
While Go has pointers, it does not have pointer arithmetic. So you will need to use integers to index into your slices of bytes.
For storing single bytes, byte is sufficient; you don't want a slice of bytes. Where there are pointers in the C++ code used to point to specific locations in the array, you'll simply have an integer index value that selects one element of a slice.
Go strings are not simply sequences of bytes, they are sequences of UTF-8 characters stored internally as runes, which may have different lengths. So don't try to use strings for this algorithm.
To reimplement the algorithm shown, you do not need either pointers or pointer arithmetic at all. Instead of keeping pointers into the byte arrays as you would in C++, you'll use int indexes into the slices.
This is kind of hard to follow since it's virtually all pointer arithmetic. I would want to have a description of the algorithm handy while converting this (and since this is probably a well-known algorithm, that should not be hard to find). I'm not going to do the entire conversion for you, but I'll demonstrate with hopefully a simpler example. This prints each character of a string on a separate line.
C++:
unsigned char *data = "Hello World";
unsigned char *ptr = 0;
for (int i = 0; i < std::strlen(data); i++) {
ptr = i + data;
std::cout << *ptr << std::endl;
}
Go:
data := []byte("Hello World")
for i := 0; i < len(data); i++ {
// The pointer is redundant already
fmt.Println(data[i:i+1])
}
So, learn about Go slices, and when you do reimplement this algorithm you will likely find the code to be somewhat simpler, or at least easier to understand, than its C++ counterpart.

DsGetDomainControllerInfo returns a "Pointer to a pointer variable that receives an array"? I don't get it

Most of my experience is with C#...so I'm still getting used to C++.
I'm trying to call DsGetDomainControllerInfo to get all of the domain controllers in the domain. Here's a link to the MSDN docs for that call:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms675987(v=vs.85).aspx
The fourth parameter returns the number of DC's that should be in the array of DS_DOMAIN_CONTROLLER_INFO_* structures.
I'm getting the first DS_DOMAIN_CONTROLLER_INFO_* in the array, but it throws an unhandled exception on the second. The last argument is a void**...I'm casting to that, but I doubt that's the right thing to do.
Here's my code:
PDOMAIN_CONTROLLER_INFO logonDomainController;
DsGetDcName(NULL, NULL, NULL, NULL, 0, &logonDomainController);
wstring domCon = logonDomainController->DomainControllerName;
wstring domNam = logonDomainController->DomainName;
HANDLE domHan;
DsBindWithCred(domCon.c_str(), domNam.c_str(), NULL, &domHan);
DWORD count = 0;
DS_DOMAIN_CONTROLLER_INFO_3 *dci[100] = { NULL };
DsGetDomainControllerInfo(domHan, domNam.c_str(), 3, &count, (void**)dci);
for (size_t i = 0; i < count; i++)
{
wcout << dci[i]->DnsHostName << endl;
}
I read the documentation as: you have to declare DS_DOMAIN_CONTROLLER_INFO_3 *dci; and pass its address as (VOID**) &dci (in the sense of a result/"out" parameter), so dci can be assigned the base address of the ..INFO_3 array by the callee. You can still access the elements of the array with dci[i].
I think it becomes clearer when reading the linked documentation for the DsFreeDomainControllerInfo function (which takes the same pointer as "in" parameter).

Array as out parameter in c++

I created a function that returns an error code (ErrCode enum) and pass two output parameters. But when I print the result of the function, I don't get the correct values in the array.
// .. some codes here ..
ErrCode err;
short lstCnt;
short lstArr[] = {};
err = getTrimmedList(lstArr, &lstCnt);
// list returned array (for comparison)
for (int i=0; i<lstCnt; ++i)
printf("lstArr[%3d] = %d", i, lstArr[i]);
// .. some codes here ..
The getTrimmedList function is like this:
ErrCode getTrimmedList(short* vList, short* vCnt)
{
short cnt;
ErrCode err = foo.getListCount(FOO_TYPE_1, &cnt);
if (NoError!=err) return err;
short* list = new short [cnt];
short total = 0;
for (short i=0; i<cnt; ++i)
{
FooBar bar = foo.getEntryByIndex(FOO_TYPE_1, i);
if (bar.isDeleted) continue;
list[total] = i;
++total;
}
*vCnt = total;
//vList = (short*)realloc(index, sizeof(short)*total);
vList = (short*)malloc(sizeof(short)*total);
memcpy(vList, list, sizeof(short)*total)
// list returned array (for comparison)
for (int i=0; i<lstCnt; ++i)
printf("lstArr[%3d] = %d", i, lstArr[i]);
return NoError;
}
where:
foo is an object that holds arrays of FooBar objects
foo.getListCount() returns the number of objects with type FOO_TYPE_1
FOO_TYPE_1 is the type of object we want to take/list
foo.getEntryByIndex() returns the ith FooBar object with type FOO_TYPE_1
bar.isDeleted is a flag that tells if bar is considered as 'deleted' or not
What's my error?
Edit:
Sorry, I copied a wrong line. I commented it above and put the correct line.
Edit 2
I don't have control over the returns of foo and bar. All their function returns are ErrCode and the outputs are passed through parameter.
Couple of questions before I can answer your post...
Where is "index" defined in:
vList = (short*)realloc(index, sizeof(short)*total);
Are you leaking the memory associated with:
short* list = new short [cnt];
Is it possible you have accidentally confused your pointers in memory allocation? In any case, here is an example to go from. You have a whole host of problems, but you should be able to use this as a guide to answer this question as it was originally asked.
WORKING EXAMPLE:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int getTrimmedList(short** vList, short* vCnt);
int main ()
{
// .. some codes here ..
int err;
short lstCnt;
short *lstArr = NULL;
err = getTrimmedList(&lstArr, &lstCnt);
// list returned array (for comparison)
for (int i=0; i<lstCnt; ++i)
printf("lstArr[%3d] = %d\n", i, lstArr[i]);
// .. some codes here ..
return 0;
}
int getTrimmedList(short** vList, short* vCnt)
{
short cnt = 5;
short* list = new short [cnt];
short* newList = NULL;
short total = 0;
list[0] = 0;
list[1] = 3;
list[2] = 4;
list[3] = 6;
total = 4;
*vCnt = total;
newList = (short*)realloc(*vList, sizeof(short)*total);
if ( newList ) {
memcpy(newList, list, sizeof(short)*total);
*vList = newList;
} else {
memcpy(*vList, list, sizeof(short)*total);
}
delete list;
return 0;
}
You have serious problems.
For starters, your function has only one output param as you use it: vCnt.
vList you use as just a local variable.
realloc is called with some index that we kow nothing about, not likely good. It must be something got from malloc() or realloc().
The allocated memory in vList is leaked as soon as you exit getTrimmedList.
Where you call the function you pass the local lstArr array as first argument that is not used for anything. Then print the original, unchanged array, to bounds in cnt, while it has 0 size still -- behavior is undefined.
Even if you managed to pass that array by ref, you could not reassign it to a different value -- C-style arrays can't do that.
You better use std::vector that you can actually pass by reference and fill in the called function. eliminating the redundant size and importantly the mess with memory handling.
You should use std::vector instead of raw c-style arrays, and pass-by-reference using "&" instead of "*" here. Right now, you are not properly setting your out parameter (a pointer to an array would look like "short **arr_ptr" not "short *arr_ptr", if you want to be return a new array to your caller -- this API is highly error-prone, however, as you're finding out.)
Your getTrimmedList function, therefore, should have this signature:
ErrCode getTrimmedList(std::vector<short> &lst);
Now you no longer require your "count" parameters, as well -- C++'s standard containers all have ways of querying the size of their contents.
C++11 also lets you be more specific about space requirements for ints, so if you're looking for a 16-bit "short", you probably want int16_t.
ErrCode getTrimmedList(std::vector<int16_t> &lst);
It may also be reasonable to avoid requiring your caller to create the "out" array, since we're using smarter containers here:
std::vector<int16_t> getTrimmedList(); // not a reference in the return here
In this style, we would likely manage errors using exceptions rather than return-codes, however, so other things about your interface would evolve, as well, most likely.

Function returns BYTE array

I want my function to return a BYTE array. The function is as follows.
BYTE sendRecieveData(BYTE control, unsigned int value){
//Open connection to LAC
HANDLE LACOutpipe;
HANDLE LACInpipe;
LACOutpipe=openConnection(MP_WRITE);
LACInpipe=openConnection(MP_READ);
//declare variables
BYTE bufDataOut[3];
BYTE bufDataIn[3];
DWORD bufInProcess;
DWORD bufOutProcess;
//sets CONTROL
bufDataOut[0]=control;
//sets DATA to be sent to LAC
BYTE low_byte = 0xff & value;
BYTE high_byte = value >> 8;
bufDataOut[1]=low_byte;
bufDataOut[2]=high_byte;
MPUSBWrite(LACOutpipe,bufDataOut,3,&bufOutProcess,1000);
MPUSBRead(LACInpipe,bufDataIn,3,&bufInProcess,1000);
MPUSBClose(LACOutpipe);
MPUSBClose(LACInpipe);
return bufDataIn[3];
}
It doesn't return a byte array and when I change BYTE to BYTE[] or BYTE[3] it gives me an error.
return bufDataIn[3]; means "return 4th element of bufDataIn array" and in this case it leads to undefined behaviour since the size of this array is 3.
You can allocate memory for this new array in the body of your function and return pointer to its first element:
BYTE* createArray(...)
{
BYTE* bufDataOut = new BYTE[3];
....
return bufDataOut;
}
Don't forget to delete it when you finish with it:
{
BYTE* myArray = createArray(...);
...
delete[] myArray;
}
Even better, use std::vector<BYTE> and get rid of this ugly memory management with it ;) This ensures that the memory is properly freed on any return path, even when exceptions are thrown.
Since your array is relatively small I'd recommend to pass your buffer as a function argument.
void sendRecieveData(BYTE control, unsigned int value, BYTE (&buffdataIn)[3] ).
Now, one will use this function as follows:
BYTE result[3] = {0};
sendRecieveData(3, 0, result);
This way you may avoid usage of dynamic memory allocation and make your code safer.