2

我正在尝试将长度在 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

4

2 回答 2

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);
于 2013-08-08T10:10:23.397 回答
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

更好(没有 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);
}
于 2013-08-08T09:41:21.067 回答