Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulate C# Random() in C++ (Same Numbers)

Tags:

c++

c#

random

Is there a way to implement the C# Random() class in C++? I specifically need to generate the same number sequences based on a given seed.

The scenario: I am working to "break" several encrypting malware by exploiting their usage of Random() in C# to generate the key. Obviously this is weak to having only 2^32 possible keys, ~4.3B keys, which is in the realm of possibility to guess. I have written bruteforcers in C#, but they are rather slow, no matter how much I optimize. I would like to implement a bruteforcer in C++ for the best efficiency ("closer to the hardware"), as I can get much better speed optimizations with the decryption part (e.g. AES-256 typically, could even leverage a GPU in the future), and exponentially get better outputs.

Obviously, Random(seed) != srand(seed), based on being different generators. Is there a way to implement the PRNG C# uses, in C++? I obviously cannot modify the C# malware, as the encryption has already been done to the victim's files, so I cannot just "rewrite both to use the same common RNG".

like image 815
Demonslay335 Avatar asked Sep 04 '16 17:09

Demonslay335


2 Answers

You can see the source for Random (in c#) here.

like image 108
js441 Avatar answered Nov 09 '22 14:11

js441


Thanks everyone for the answers and comments. I am posting my ported C++ code here if anyone else needs it for a similar project. It was pretty copy/paste, and only had to "translate" a few lines, and break it out into a proper prototype. Confirmed to side-by-side produce the exact same number sequences as a C# application. :)

Random.h

#include <limits>

#pragma once
class Random
{
private:
    const int MBIG = INT_MAX;
    const int MSEED = 161803398;
    const int MZ = 0;

    int inext;
    int inextp;
    int *SeedArray = new int[56]();

    double Sample();
    double GetSampleForLargeRange();
    int InternalSample();

public:
    Random(int seed);
    ~Random();
    int Next();
    int Next(int minValue, int maxValue);
    int Next(int maxValue);
    double NextDouble();
};

Random.cpp

#include "stdafx.h"
#include "Random.h"
#include <limits.h>
#include <math.h>
#include <stdexcept>

double Random::Sample() {
    //Including this division at the end gives us significantly improved
    //random number distribution.
    return (this->InternalSample()*(1.0 / MBIG));
}

int Random::InternalSample() {
    int retVal;
    int locINext = this->inext;
    int locINextp = this->inextp;

    if (++locINext >= 56) locINext = 1;
    if (++locINextp >= 56) locINextp = 1;

    retVal = SeedArray[locINext] - SeedArray[locINextp];

    if (retVal == MBIG) retVal--;
    if (retVal<0) retVal += MBIG;

    SeedArray[locINext] = retVal;

    inext = locINext;
    inextp = locINextp;

    return retVal;
}

Random::Random(int seed) {
    int ii;
    int mj, mk;

    //Initialize our Seed array.
    //This algorithm comes from Numerical Recipes in C (2nd Ed.)
    int subtraction = (seed == INT_MAX) ? INT_MAX : abs(seed);
    mj = MSEED - subtraction;
    SeedArray[55] = mj;
    mk = 1;
    for (int i = 1; i<55; i++) {  //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
        ii = (21 * i) % 55;
        SeedArray[ii] = mk;
        mk = mj - mk;
        if (mk<0) mk += MBIG;
        mj = SeedArray[ii];
    }
    for (int k = 1; k<5; k++) {
        for (int i = 1; i<56; i++) {
            SeedArray[i] -= SeedArray[1 + (i + 30) % 55];
            if (SeedArray[i]<0) SeedArray[i] += MBIG;
        }
    }
    inext = 0;
    inextp = 21;
    seed = 1;
}

Random::~Random()
{
    delete SeedArray;
}

int Random::Next() {
    return this->InternalSample();
}

double Random::GetSampleForLargeRange() {

    int result = this->InternalSample();
    // Note we can't use addition here. The distribution will be bad if we do that.
    bool negative = (InternalSample() % 2 == 0) ? true : false;  // decide the sign based on second sample
    if (negative) {
        result = -result;
    }
    double d = result;
    d += (INT_MAX - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1)
    d /= 2 * INT_MAX - 1;
    return d;
}

int Random::Next(int minValue, int maxValue) {
    if (minValue>maxValue) {
        throw std::invalid_argument("minValue is larger than maxValue");
    }

    long range = (long)maxValue - minValue;
    if (range <= (long)INT_MAX) {
        return ((int)(this->Sample() * range) + minValue);
    }
    else {
        return (int)((long)(this->GetSampleForLargeRange() * range) + minValue);
    }
}


int Random::Next(int maxValue) {
    if (maxValue<0) {
        throw std::invalid_argument("maxValue must be positive");
    }

    return (int)(this->Sample()*maxValue);
}

double Random::NextDouble() {
    return this->Sample();
}

Main.cpp

#include "Random.h"
#include <iostream>

int main(int argc, char* argv[]){
    // Example usage with a given seed
    Random r = Random(7898);
    std::cout << r.Next() << std::endl;
}
like image 32
Demonslay335 Avatar answered Nov 09 '22 13:11

Demonslay335