1

我想在我的程序中加密一个短文本框或字符串(不是文件),以使其内容不可读,或者使用简单的安全加密(如任何敏感密码等)对其进行加密。在 Visual Basic 中,很容易做到这一点,当我在那里复制它时,它们在我的 C# 中不起作用。我找不到合适的东西。只有非常困难的示例需要大量代码,这些代码通常会引发很多错误,并且需要您自己设置任何复杂的密钥或密钥对或散列、utf 编码或两者兼而有之以使其正常工作,但它永远不会。我对这一切一无所知,我只需要一个简单的函数,它可以双向加密。对于 C# 来说找不到类似的东西,它确实可以正常工作并且可以向前和向后执行作业。

或者我将如何让下面的代码示例工作,这是最有希望的一个:如果我在 button1_click 事件中将它复制到我的 C# 中,它会给我很多错误:

错误 1:类型或命名空间定义或预期文件结尾

错误 2:找不到类型或命名空间“TripleDESCryptoServiceProvider”

错误 3:当前上下文中不存在“CipherMode”

错误4:当前上下文中不存在“Getkey”

错误 5:当前上下文中不存在“PaddingMode”错误 6:错误 8 找不到类型或命名空间名称“ICryptoTransform”(您是否缺少 using 指令或 essemble 引用?)

public static string Encrypt(string data)
{
    TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

    DES.Mode = CipherMode.ECB;
    DES.Key = GetKey("a1!B78s!5(");

    DES.Padding = PaddingMode.PKCS7;
    ICryptoTransform DESEncrypt = DES.CreateEncryptor();
    Byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(data);

    return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
}

public static string Decrypt(string data)
{
    TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

    DES.Mode = CipherMode.ECB;
    DES.Key = GetKey("a1!B78s!5(");

    DES.Padding = PaddingMode.PKCS7;
    ICryptoTransform DESEncrypt = DES.CreateDecryptor();
    Byte[] Buffer = Convert.FromBase64String(data.Replace(" ","+"));

    return Encoding.UTF8.GetString(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
}
4

6 回答 6

1

如果您真正想做的只是屏蔽文本输入框的内容。在 Windows 窗体中,使用 TextBox 控件并将 PasswordChar 属性设置为一个字符。在 WPF 中,使用 PasswordBox 并可选择将 PasswordChar 属性设置为一个字符。

如果你真的需要加密,不要寻找捷径(自己实现,硬编码密码或密钥),因为你最终会得到看起来安全的东西,但实际上可以在几分钟内被知道他们在做什么的人破解。

于 2013-06-13T16:07:05.977 回答
1

在这里,您的方法现在可以这样工作:

public static string Encrypt(string data)
{
    using (var des = new TripleDESCryptoServiceProvider { Mode = CipherMode.ECB, Key = GetKey("a1!B78s!5(j$S1c%"), Padding = PaddingMode.PKCS7 })
    using (var desEncrypt = des.CreateEncryptor())
    {
        var buffer = Encoding.UTF8.GetBytes(data);

        return Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));
    }
}

public static string Decrypt(string data)
{
    using (var des = new TripleDESCryptoServiceProvider { Mode = CipherMode.ECB, Key = GetKey("a1!B78s!5(j$S1c%"), Padding = PaddingMode.PKCS7 })
    using (var desEncrypt = des.CreateDecryptor())
    {
        var buffer = Convert.FromBase64String(data.Replace(" ", "+"));

        return Encoding.UTF8.GetString(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));
    }
}

问题是 A)无效的密钥长度(我猜是由于缺乏GetKey()定义 - 但每个字符 16 个字符乘 8 位是三重 DES 的最小 128 位)和 B)获取源字符串的字节作为 ASCII 进行加密,但解密后,使用UTF8编码。

于 2013-06-13T16:09:21.437 回答
1

除了我在链接问题中的回答之外,您还可以执行以下操作,

public static string Obfuscate(string before)
{
    var beforeArray = Encoding.Unicode.GetBytes(before);
    var count = beforeArray.Length;
    var resultArray = new byte[count];
    var o = count % 32;

    for (var i = 0; i < count; i++)
    {
       var xor = o + 32;
       resultArray[i] = (byte)(beforeArray[i] ^ xor);
       o = ++o % 32;
    }

    return Encoding.Unicode.GetString(resultArray)
}

它是字符串中字节的简单异或。它不是加密,但它使人类难以阅读字符串。

如果你真的想要强加密,你必须从避免 TDES 开始。

于 2013-06-13T16:11:42.207 回答
1

补充 Jesse C. Slicer 接受的答案,这里是“GetKey”代码,我在这里找到了

  private static byte[] GetKey(string password)
  {
     string pwd = null;

     if (Encoding.UTF8.GetByteCount(password) < 24)
     {
         pwd = password.PadRight(24, ' ');
     }
     else
     {
         pwd = password.Substring(0, 24);
     }
     return Encoding.UTF8.GetBytes(pwd);
  }
于 2015-05-12T09:55:41.500 回答
0

更好的是……使用 AES 而不是 3DES。有关为什么您可以在另一个SO 答案中看到这里的解释。

以下是我使用的一些加密/解密方法。输入和输出是base64Strings。

static string EncryptStringToBase64String(string plainText, byte[] Key, byte[] IV)
{
    // Check arguments. 
    if (plainText == null || plainText.Length <= 0)
        throw new ArgumentNullException("plainText");
    if (Key == null || Key.Length <= 0)
        throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
        throw new ArgumentNullException("Key");
    byte[] encrypted;
    // Create an RijndaelManaged object 
    // with the specified key and IV. 
    using (RijndaelManaged rijAlg = new RijndaelManaged())
    {
        rijAlg.Key = Key;
        rijAlg.IV = IV;

        // Create a decrytor to perform the stream transform.
        ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

        // Create the streams used for encryption. 
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    //Write all data to the stream.
                    swEncrypt.Write(plainText);
                }
                encrypted = msEncrypt.ToArray();
            }
        }
    }

    // return encrypted bytes converted to Base64String
    return Convert.ToBase64String(encrypted);
}

static string DecryptStringFromBase64String(string cipherText, byte[] Key, byte[] IV)
{
    // Check arguments. 
    if (cipherText == null || cipherText.Length <= 0)
        throw new ArgumentNullException("cipherText");
    if (Key == null || Key.Length <= 0)
        throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
        throw new ArgumentNullException("Key");

    // Declare the string used to hold 
    // the decrypted text. 
    string plaintext = null;

    // Create an RijndaelManaged object 
    // with the specified key and IV. 
    using (RijndaelManaged rijAlg = new RijndaelManaged())
    {
        rijAlg.Key = Key;
        rijAlg.IV = IV;

        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

        // Create the streams used for decryption. 
        using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {
                    // Read the decrypted bytes from the decrypting stream 
                    // and place them in a string.
                    plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
    }

    return plaintext;
}

这是一些测试代码,因为我看到您在加密/解密中创建了密钥/IV。

    var inputString = "SomeText";
    var r = RijndaelManaged.Create();
    r.GenerateKey();
    r.GenerateIV();
    var key = r.Key;
    var iv = r.IV;

    var a = EncryptStringToBase64String(inputString, key, iv);
    var b = DecryptStringFromBase64String(a, key, iv);
    Assert.AreEqual(b, inputString);
    Assert.AreNotEqual(a, inputString);
于 2013-06-13T16:22:25.823 回答
0

使用 System.Security.Cryptography;;

public class StringCipher
{

    private const int keysize = 256;

    public static string Encrypt(string plainText)
    {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        using (PasswordDeriveBytes password = new PasswordDeriveBytes("123", null))
        {
            byte[] keyBytes = password.GetBytes(keysize / 8);
            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                symmetricKey.Mode = CipherMode.CBC;
                using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            byte[] cipherTextBytes = memoryStream.ToArray();
                            return Convert.ToBase64String(cipherTextBytes);
                        }
                    }
                }
            }
        }
    }

    public static string Decrypt(string cipherText)
    {
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        using (PasswordDeriveBytes password = new PasswordDeriveBytes("123", null))
        {
            byte[] keyBytes = password.GetBytes(keysize / 8);
            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                symmetricKey.Mode = CipherMode.CBC;
                using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                {
                    using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
    }
}

}

于 2015-03-11T08:16:28.403 回答