Custom string to 128-bit string

6.8k views Asked by At

I am trying to force a custom string with a length between 0 and 15 to a 128-bit string, so I can use it as a AesCryptoServiceProvider key.

I have tried fiddling around with multiple strategies, and have ended up with the following:

        if (stringToConvert.Length > 16)
        {
            StringBuilder sB = new StringBuilder();
            char[] chA = stringToConvert.ToCharArray();
            int chAMaxLength = chA.Length;

            for (int i = 0; i < 16; i++)
            {
                if (i <= chAMaxLength)
                {
                    sB.Append(chA[i]);
                }
            }
        }

I need a string exactly 16 characters long (16*8 = 128).

I am now stuck with it, and just need a helping hand to go through this obsticle.
I apologize in advance if this may seem simple.

Example:
asd would become
asdasdasdasdasda

2

There are 2 answers

0
Ahmed KRAIEM On BEST ANSWER
StringBuilder b = new StringBuilder();
for (int i = 0; i < 8; i++)
{
    b.Append(stringToConvert[i % stringToConvert.Length]);
}
stringToConvert = b.ToString();
byte[] key = Encoding.Unicode.GetBytes(stringToConvert);//key size is 16 bytes = 128 bits

Even better (without a StringBuilder):

byte[] key = new byte[16];
for (int i = 0; i < 16; i+=2)
{
    byte[] unicodeBytes = BitConverter.GetBytes(stringToConvert[i % stringToConvert.Length]);
    Array.Copy(unicodeBytes, 0, key, i, 2);
}
1
xanatos On

You simply calc the hash of your string (and resize it to 16, because SHA1 is 20 bytes)

string password = "shortstring";

using (SHA1 sha = new SHA1CryptoServiceProvider())
{
    // This is one implementation of the abstract class SHA1.
    byte[] result = sha.ComputeHash(Encoding.UTF8.GetBytes(password));
    Array.Resize(ref result, 16);
}

This is still wrong. You should use the Rfc2898 that describe how to strengthen passwords. In the end the basic principle is to repeatedly call hash functions on the result of previous hash functions.

string password = "shortstring";
byte[] salt = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }; // this is fixed... It would be better you used something different for each user

// You can raise 1000 to greater numbers... more cycles = more security. Try
// balancing speed with security.
Rfc2898DeriveBytes pwdGen = new Rfc2898DeriveBytes(password, salt, 1000);

// generate key
byte[] key = pwdGen.GetBytes(16);