Search code examples
c#128-bit

Custom string to 128-bit string


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


Solution

  • 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);
    }