Felix K.
Felix K.

Reputation: 6281

Generate a byte sequence with fixed size from a string

I want to create a byte sequence with a fixed length out of a string which has a variable length. What is the best way to archive this. All bytes should be as different as possible.

The code is used for research for myself, nothing productive.

This has been my first approach for the generation of the bytes:

static byte[] GenerateBytes(string password, Int32 strength)
{
    Byte[] result = new byte[strength];
    Byte[] pwBytes = Encoding.ASCII.GetBytes(password);
    Int32 prime = GetLowerPrime(pwBytes.Length);
    
    // Offset count to avoid values
    Int32 count = prime;
    Int32 sum = 0;
    for (int i = 0; i < result.Length; i++) {
        sum += (result[i] = pwBytes[(count++ % pwBytes.Length)]);
    }
    
    count += prime;
    Int32 pcount = prime;
    for (int i = 0; i < result.Length * 7; i++) {
        result[(i % result.Length)] ^= (Byte)(pwBytes[(count++ % pwBytes.Length)] ^ ((pcount += pwBytes[(count % pwBytes.Length)]) % 255));
    }
    
    return result;
}

And generated some samples with 256 / 128 / 64 generated bytes and counted the unique bytes:

Password "Short":                170  103  60
Password "LongerX":              173  101  55
Password "Really Long":          169  100  57
Password "Unbelivable Safe!0§$": 162  101  56
Password "MCV":                  119  113  61
Password "AAA":                  50   51   50
Password "BBB":                  67   67   52
Password "AAAAAA":               48   48   48

I tried to change the prime selector a bit this improves the generation with short keys but has partly a impact on long ones. I also tracked some statistics of the bytes. Generated and each byte value is used between 9 and 30 times.

What do you think about the results? How can i improve the generation of the bytes?

Upvotes: 2

Views: 419

Answers (2)

Bradley Thomas
Bradley Thomas

Reputation: 4097

well if you really want to roll your own solution that has no real practical use other than theoretical interest, (because this sounds like a homework question) just start off with a one-time pad of random bytes and XOR the pwd with the first few bytes, should give you reasonably high entropy for short pwds.

Upvotes: 2

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

You seems to be reinventing the wheel. If you need to make key from the password, use hashing function, or, the best way - one of the standard password-based key derivation function. Search for PBKDF2.

Upvotes: 2

Related Questions