使用一种函数以最简单的方式对字符串(而不是文件)进行解密/加密,如何实现?

时间:2013-06-13 15:43:50

标签: c# string function encryption

我想在我的程序中加密一个简短的文本框或字符串(而不是文件),以便为人类提供无法读取的内容,或者使用简单加密对其进行加密,以确保安全(如任何敏感密码等)。 在Visual Basic中很容易做到这五行,当我在那里复制它时,它在我的C#中不起作用。 我找不到合适的东西。 只有非常困难的例子需要大量的代码,这些代码主要会抛出很多错误,并且需要自己设置任何复杂的密钥或密钥对或哈希,utf编码或两者以使其工作而且它永远不会。 我不知道所有这些,我只需要一个简单的功能,它可以兼顾加密的两种方式。 无法为C#找到类似的东西,它确实可以正常工作,并且可以向前和向后工作。 在VB中加密了C#中不存在的XOR函数。

或者我如何在下面获得该代码示例,它是最有前途的: 如果我在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));
}

6 个答案:

答案 0 :(得分:1)

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

如果你真的需要加密,不要寻找快捷方式(自己实现,硬编码密码或密钥),因为你最终会看到一些看起来很安全的东西,但是真的可以在几分钟内被知道它们是什么的人攻击做。

答案 1 :(得分: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位是Triple DES的最小128位)和B)获取字节源字符串为ASCII加密,但解密后,使用UTF8编码。

答案 2 :(得分: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)
}

它是字符串中字节的一个微不足道的XOR。它不是加密,但它使字符串很难被人阅读。

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

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

更好的是......使用AES代替3DES。有关您在另一个SO answer.

中可以看到此处的原因的说明

以下是我使用的一些加密/解密方法。输入和输出是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;
}

以下是一些测试代码,因为我看到你在加密/解密中创建了Key / 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);

答案 5 :(得分: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);
                        }
                    }
                }
            }
        }
    }
}

}