C# Encrypt Text Output

前端 未结 9 1275
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 13:37

I have created a few little programs that export data to a text file using StreamWriter and then I read them back in using StreamReader. This works great and does what I nee

相关标签:
9条回答
  • 2020-12-14 14:01

    If a program can access the information, a user usually can too. However you can produce data the user will not immediately understand.

    I would start by creating a class that holds all state information you want to save, isolating the problem. Coincidentally, the BinaryFormatter class will then allow you to easily save and load this class to/from a file. I don't know if it's results are "unreadable enough" - if not, apply Base64 encoding like Leon mentioned.

    0 讨论(0)
  • 2020-12-14 14:02

    Preventing unintentional string modification can be done using a checksum, as pointed in this answer.

    However, it's quite easy to generate such a checksum, as they are not that many widely used algorithms.

    Thus that doesn't protect you against intentional modification.

    To prevent that, people use digital signatures. That allows anyone to verify your data hasn't be tampered, but only you (the owner of the private secret) can generate the signature.

    Here is an example in C#.

    However, as others pointed out, you need to embed your private key somewhere in your binary, and a (not so) skilled programmer will be able to retrieve it, even if you obfuscate your .net dll or you make that in a separate native process.

    That would be enough for most concerns though.

    If you are really concerned by security, then you need to move on the cloud, and execute the code on a machine you own.

    0 讨论(0)
  • 2020-12-14 14:03

    Just to add another implementation of Leon's answer, and following the Microsoft docs

    Here a class example that encrypts and decrypts strings

        public static class EncryptionExample
    {
    
        #region internal consts
    
        internal const string passPhrase = "pass";
        internal const string saltValue = "salt";
        internal const string hashAlgorithm = "MD5";
        internal const int passwordIterations = 3;             // can be any number
        internal const string initVector = "0123456789abcdf"; // must be 16 bytes
        internal const int keySize = 64;                      // can be 192 or 256
    
        #endregion
    
        #region public static Methods
    
        public static string Encrypt(string data)
        {
            string res = string.Empty;
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(initVector);
                byte[] rgbSalt = Encoding.ASCII.GetBytes(saltValue);
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                byte[] rgbKey = new PasswordDeriveBytes(passPhrase, rgbSalt, hashAlgorithm, passwordIterations).GetBytes(keySize / 8);
                RijndaelManaged managed = new RijndaelManaged();
                managed.Mode = CipherMode.CBC;
                ICryptoTransform transform = managed.CreateEncryptor(rgbKey, bytes);
    
                byte[] inArray = null;
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, transform, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(buffer, 0, buffer.Length);
                        csEncrypt.FlushFinalBlock();
                        inArray = msEncrypt.ToArray();
                        res = Convert.ToBase64String(inArray);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Encrypt " + ex);
            }
    
            return res;
        }
    
        public static string Decrypt(string data)
        {
            string res = string.Empty;
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(initVector);
                byte[] rgbSalt = Encoding.ASCII.GetBytes(saltValue);
                byte[] buffer = Convert.FromBase64String(data);
                byte[] rgbKey = new PasswordDeriveBytes(passPhrase, rgbSalt, hashAlgorithm, passwordIterations).GetBytes(keySize / 8);
                RijndaelManaged managed = new RijndaelManaged();
                managed.Mode = CipherMode.CBC;
                ICryptoTransform transform = managed.CreateDecryptor(rgbKey, bytes);
    
                using (MemoryStream msEncrypt = new MemoryStream(buffer))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msEncrypt, transform, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            res = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
               Console.WriteLine("Decrypt " + ex);
            }
    
            return res;
        }
    }
    

    By the way, here is the "salt value" definition that I had googled to find out what it was.

    Salt value

    If an attacker does not know the password, and is trying to guess it with a brute-force attack, then every password he tries has to be tried with each salt value. So, for a one-bit salt (0 or 1), this makes the encryption twice as hard to break in this way.

    0 讨论(0)
  • 2020-12-14 14:07

    The simplest way is to Base-64 encode/decode this text. This is not secure, but will prevent a casual user from modifying the data.

    static public string EncodeTo64(string toEncode)
    {
      byte[] toEncodeAsBytes
            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
      string returnValue
            = System.Convert.ToBase64String(toEncodeAsBytes);
      return returnValue;
    }
    
    static public string DecodeFrom64(string encodedData)
    {
      byte[] encodedDataAsBytes
          = System.Convert.FromBase64String(encodedData);
      string returnValue =
         System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
      return returnValue;
    }
    

    EDIT: Real encryption

    #region Encryption
    
            string passPhrase = "Pasword";        // can be any string
            string saltValue = "sALtValue";        // can be any string
            string hashAlgorithm = "SHA1";             // can be "MD5"
            int passwordIterations = 7;                  // can be any number
            string initVector = "~1B2c3D4e5F6g7H8"; // must be 16 bytes
            int keySize = 256;                // can be 192 or 128
    
            private string Encrypt(string data)
            {
                byte[] bytes = Encoding.ASCII.GetBytes(this.initVector);
                byte[] rgbSalt = Encoding.ASCII.GetBytes(this.saltValue);
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                byte[] rgbKey = new PasswordDeriveBytes(this.passPhrase, rgbSalt, this.hashAlgorithm, this.passwordIterations).GetBytes(this.keySize / 8);
                RijndaelManaged managed = new RijndaelManaged();
                managed.Mode = CipherMode.CBC;
                ICryptoTransform transform = managed.CreateEncryptor(rgbKey, bytes);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
                byte[] inArray = stream.ToArray();
                stream.Close();
                stream2.Close();
                return Convert.ToBase64String(inArray);
            }
    
            private string Decrypt(string data)
            {
                byte[] bytes = Encoding.ASCII.GetBytes(this.initVector);
                byte[] rgbSalt = Encoding.ASCII.GetBytes(this.saltValue);
                byte[] buffer = Convert.FromBase64String(data);
                byte[] rgbKey = new PasswordDeriveBytes(this.passPhrase, rgbSalt, this.hashAlgorithm, this.passwordIterations).GetBytes(this.keySize / 8);
                RijndaelManaged managed = new RijndaelManaged();
                managed.Mode = CipherMode.CBC;
                ICryptoTransform transform = managed.CreateDecryptor(rgbKey, bytes);
                MemoryStream stream = new MemoryStream(buffer);
                CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read);
                byte[] buffer5 = new byte[buffer.Length];
                int count = stream2.Read(buffer5, 0, buffer5.Length);
                stream.Close();
                stream2.Close();
                return Encoding.UTF8.GetString(buffer5, 0, count);
            }
            #endregion
    
    0 讨论(0)
  • 2020-12-14 14:09

    You can use the Ionic zip libraries to zip those text files. If necessary you could also use features of Ionic zip like password protection and encryption. And you'll still be able to open the file (with zipping applications like, for example, 7zip) manually yourself using the same settings you used to create it in the first place.

    0 讨论(0)
  • 2020-12-14 14:14

    Try this code to encrypt and decrypt your text! It is quite easy and strong I think...

    public static class Crypto
    {
        private static readonly byte[] IVa = new byte[] { 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
    
    
        public static string Encrypt(this string text, string salt)
        {
            try
            {
                using (Aes aes = new AesManaged())
                {
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));
                    aes.Key = deriveBytes.GetBytes(128 / 8);
                    aes.IV = aes.Key;
                    using (MemoryStream encryptionStream = new MemoryStream())
                    {
                        using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            byte[] cleanText = Encoding.UTF8.GetBytes(text);
                            System.Diagnostics.Debug.WriteLine(String.Concat("Before encryption text data size: ", text.Length.ToString()));
                            System.Diagnostics.Debug.WriteLine(String.Concat("Before encryption byte data size: ", cleanText.Length.ToString()));
                            encrypt.Write(cleanText, 0, cleanText.Length);
                            encrypt.FlushFinalBlock();
                        }
    
                        byte[] encryptedData = encryptionStream.ToArray();
                        string encryptedText = Convert.ToBase64String(encryptedData);
    
                        System.Diagnostics.Debug.WriteLine(String.Concat("Encrypted text data size: ", encryptedText.Length.ToString()));
                        System.Diagnostics.Debug.WriteLine(String.Concat("Encrypted byte data size: ", encryptedData.Length.ToString()));
    
                        return encryptedText;
                    }
                }
            }
            catch(Exception e)
            {
                return String.Empty;
            }
        }
    
        public static string Decrypt(this string text, string salt)
        {
            try
            {
                using (Aes aes = new AesManaged())
                {
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt));
                    aes.Key = deriveBytes.GetBytes(128 / 8);
                    aes.IV = aes.Key;
    
                    using (MemoryStream decryptionStream = new MemoryStream())
                    {
                        using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            byte[] encryptedData = Convert.FromBase64String(text);
    
                            System.Diagnostics.Debug.WriteLine(String.Concat("Encrypted text data size: ", text.Length.ToString()));
                            System.Diagnostics.Debug.WriteLine(String.Concat("Encrypted byte data size: ", encryptedData.Length.ToString()));
    
                            decrypt.Write(encryptedData, 0, encryptedData.Length);
                            decrypt.Flush();
                        }
    
                        byte[] decryptedData = decryptionStream.ToArray();
                        string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
    
                        System.Diagnostics.Debug.WriteLine(String.Concat("After decryption text data size: ", decryptedText.Length.ToString()));
                        System.Diagnostics.Debug.WriteLine(String.Concat("After decryption byte data size: ", decryptedData.Length.ToString()));
    
                        return decryptedText;
                    }
                }
            }
            catch(Exception e)
            {
                return String.Empty;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题