C# 自定义字符串到128位字符串

C# 自定义字符串到128位字符串,c#,128-bit,C#,128 Bit,我试图将长度介于0和15之间的自定义字符串强制为128位字符串,以便将其用作AESCryptServiceProvider密钥 我尝试了多种策略,最终得出以下结论: if (stringToConvert.Length > 16) { StringBuilder sB = new StringBuilder(); char[] chA = stringToConvert.ToCharArray();

我试图将长度介于0和15之间的自定义字符串强制为128位字符串,以便将其用作
AESCryptServiceProvider
密钥

我尝试了多种策略,最终得出以下结论:

        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]);
                }
            }
        }
if(stringToConvert.Length>16)
{
StringBuilder sB=新的StringBuilder();
char[]chA=stringToConvert.ToCharArray();
int chAMaxLength=chA.Length;
对于(int i=0;i<16;i++)
{

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

这仍然是错误的。您应该使用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);

最后,,
stringToConvert=sB.ToString()
?“如果从未输入,因为要转换的字符串长度为0..15个字符,因此不超过16个字符。如果chA只有5个字符,最终结果将只有5个字符。我感觉你们不知道加密密钥或我需要什么。谢谢您的输入,但我不需要生成任何强度的密码。即使是
a
也可以:D我以后一定会记住这一点。
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);
}
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);
}
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);