如何在C#中加密和解密字符串

3

我希望使用C#编写一个加密和解密字符串的算法,使得同样的明文加密后得到相同的密文。例如,如果我加密一个字符串122ujhdheiwe,结果为uoi8asdf8asdf,再次加密同样的字符串122ujhdheiwe,结果应该是uoi8asdf8asdf。有哪些可能的加密算法可以使用?如何实现?


你想如何解密?你想用什么作为密钥(和盐值)?安全级别需要多高? - H H
安全在我的情况下不是一个问题,我只是不希望用户查看我在隐藏字段中保存的内容。 - Fraz Sundal
我使用了这个解决方案:https://dev59.com/fGkw5IYBdhLWcg3wDWTL#10177020 - GryzLi
6个回答

2

我这里有一个简单的解决方案:

http://remy.supertext.ch/2011/01/simple-c-encryption-and-decryption/

基本上它的工作原理是这样的:
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] Key = { 12, 13, 14, 15, 16, 17, 18, 19 };
byte[] IV =  { 12, 13, 14, 15, 16, 17, 18, 19 };

ICryptoTransform encryptor = des.CreateEncryptor(Key, IV);

byte[] IDToBytes = ASCIIEncoding.ASCII.GetBytes(source);
byte[] encryptedID = encryptor.TransformFinalBlock(IDToBytes, 0, IDToBytes.Length);
return Convert.ToBase64String(encryptedID);

然后反过来。


2
你可以使用 ProtectedData 类来实现简单的解决方案:
using System;
using System.Security.Cryptography;
using System.Text;

private void example()
{
    string data = "122ujhdheiwe";

    // Encrypt
    UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
    byte[] secret = ProtectedData.Protect(unicodeEncoding.GetBytes(data), null, DataProtectionScope.CurrentUser);
    Console.WriteLine(BitConverter.ToString(secret));

    // If you need it as a printable string, you can convert the binary to Base64
    string base64 = Convert.ToBase64String(secret);
    Console.WriteLine(base64);

    // Back to binary...
    byte[] backagain = Convert.FromBase64String(base64);

    // Decrypt
    byte[] clearbytes = ProtectedData.Unprotect(backagain, null, DataProtectionScope.CurrentUser);
    string roundtripped = unicodeEncoding.GetString(clearbytes);
    Console.WriteLine(roundtripped);
}

参考ProtectedDataClass

如果您希望加密后的数据与原始数据基本相同,就像您问题中的示例(122ujhdheiwe ==> uoi8asdf8asdf)一样,那么您需要的是格式保留加密--请参见此处,但我没有示例。

编辑:我刚刚注意到,在您的问题中,您写道您希望能够再次加密相同的字符串并获得相同的加密结果,在这种情况下,ProtectedData将无法工作,因为用于加密的密钥会随时间变化。


有点老的答案,但是我不得不说,这个解决方案在除了Windows以外的平台上都不可用。它会抛出UnsupportedPlatformException异常。 - badjuice

1

rot13(凯撒密码)也许是吗?它将所有字符按偏移量13进行移位。因此,应用两次,您将再次获得纯文本。


1

enter image description here

我编写了一个演示程序,需要源代码吗?我使用了以下命名空间:using System.Security.Cryptography;

还有这两个:

        public string encryptus(string x, string encrypt)//function
    {
        try
        {

            string y = x;
            byte[] etext = UTF8Encoding.UTF8.GetBytes(y);
            string Code = encrypt;
            MD5CryptoServiceProvider mdhash = new MD5CryptoServiceProvider();
            byte[] keyarray = mdhash.ComputeHash(UTF8Encoding.UTF8.GetBytes(Code));
            TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
            tds.Key = keyarray;
            tds.Mode = CipherMode.ECB;
            tds.Padding = PaddingMode.PKCS7;

            ICryptoTransform itransform = tds.CreateEncryptor();
            byte[] result = itransform.TransformFinalBlock(etext, 0, etext.Length);
            string encryptresult = Convert.ToBase64String(result);
            return encryptresult.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
        public string dencryptus(string x, string keyai)
    {
        try
        {
            string y = x.Replace("\0", null);
            byte[] etext = Convert.FromBase64String(y);
            string key = keyai;
            MD5CryptoServiceProvider mdhash = new MD5CryptoServiceProvider();
            byte[] keyarray = mdhash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
            tds.Key = keyarray;
            tds.Mode = CipherMode.ECB;
            tds.Padding = PaddingMode.PKCS7;

            ICryptoTransform itransform = tds.CreateDecryptor();
            byte[] result = itransform.TransformFinalBlock(etext, 0, etext.Length);
            string dencryptresult = UTF8Encoding.UTF8.GetString(result);
            return dencryptresult.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

并像这样使用它们:

Encrypted.Text = encryptus(Message.Text, EncryptCode.Text.ToString());
Decrypted.Text = dencryptus(Message.Text, EncryptCode.Text.ToString());

0

0

死灵术...

我只是想为任何正在寻找简单加密的人提供一个简单的复制粘贴:

public static class AesConverter
{     
    public static string Encrypt(string clearText)
    {
        var inputBytes = Encoding.Unicode.GetBytes(clearText);
        var outputBytes = AesConvert(inputBytes, aes => aes.CreateEncryptor());
        return Convert.ToBase64String(outputBytes);
    }

    public static string Decrypt(string cipherText)
    {
        var inputBytes = Convert.FromBase64String(cipherText.Replace(" ", "+"));
        var outputBytes = AesConvert(inputBytes, aes => aes.CreateDecryptor());
        return Encoding.Unicode.GetString(outputBytes);
    }

    private static byte[] AesConvert(byte[] inputBytes, Func<Aes, ICryptoTransform> convert)
    {
        using var aes = Aes.Create();
        var key = "populateThisFromAppSettings";
        var derivedBytes = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        aes.Key = derivedBytes.GetBytes(32);
        aes.IV = derivedBytes.GetBytes(16);
        using var ms = new MemoryStream();
        using var cs = new CryptoStream(ms, convert(aes), CryptoStreamMode.Write);
        cs.Write(inputBytes, 0, inputBytes.Length);
        cs.Close();
        return ms.ToArray();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接