【问题标题】:Custom string to 128-bit string自定义字符串到 128 位字符串
【发布时间】:2013-08-09 22:33:07
【问题描述】:

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

【问题讨论】:

  • 到底,,, stringToConvert = sB.ToString(); ??
  • if 永远不会作为您要转换的字符串输入,其长度为 0 .. 15 个字符,因此不超过 16 个。
  • 如果 chA 只有 5 个字符长,则最终结果将只有 5 个字符。
  • 我感觉你们不知道加密密钥,或者我需要什么......

标签: c# 128-bit


【解决方案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);
}

【讨论】:

    【解决方案2】:

    您只需计算字符串的哈希值(并将其调整为 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。 归根结底,基本原理是对之前的hash函数的结果重复调用hash函数。

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

    【讨论】:

    • 感谢您的输入,但我不需要生成任何强度的密码。即使a 也可以:D 我以后一定会记住这一点。
    猜你喜欢
    • 1970-01-01
    • 2012-07-19
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多