自定义字符串为128位字符串

时间:2013-08-08 09:15:18

标签: c# 128-bit

我正在尝试将长度介于0到15之间的自定义字符串强制为128位字符串,因此我可以将其用作AesCryptoServiceProvider键。

我试图摆弄多种策略,最终得到以下结论:

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

我需要一个长度恰好为16个字符的字符串(16 * 8 = 128)。

我现在坚持下去,只需要伸出援助之手就可以解决这个问题 如果这看似简单,我会事先道歉。

例:
asd会成为 asdasdasdasdasda

2 个答案:

答案 0 :(得分:1)

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

更好(没有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 :(得分:1)

您只需计算字符串的哈希值(并将其大小调整为16,因为SHA1是20个字节)

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

这仍然是错误的。您应该使用描述如何加强密码的Rfc2898。 最后,基本原则是在先前哈希函数的结果上重复调用哈希函数。

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