简体   繁体   English

在 C# 中加密和解密对象

[英]Encrypt And Decrypt An Object In C#

I am sending Data from a Server to a Client over the Internet using WCF web services in form of Data Objects.我使用 WCF Web 服务以数据对象的形式通过 Internet 从服务器向客户端发送数据。 I have created a Class, which is Serializable, and using this class to send my data.我创建了一个可序列化的类,并使用这个类来发送我的数据。

Below is an example of my class:下面是我的班级的一个例子:

[Serializable]
public class DBOList
{
    public string A{ get; set; }
    public string B { get; set; }
}

Is it possible for me to Encrypt the data in this object, and send it to the client as a stream?我是否可以加密此对象中的数据,并将其作为流发送给客户端?

If not What is the best approach to achive this?如果不是,实现这一目标的最佳方法是什么?

Encryption Code:加密代码:

        DBOList NewLst = new DBOList();
        NewLst.A = "Value 1";
        NewLst.B = "Value 2";

        byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 };
        byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };

        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        // Encryption
        using (var fs = new MemoryStream())
        {
            var cryptoStream = new CryptoStream(fs, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
            BinaryFormatter formatter = new BinaryFormatter();

            // This is where you serialize the class
            formatter.Serialize(cryptoStream, NewLst);
            cryptoStream.FlushFinalBlock();
        }

It is best to use SSL instead, which will add all the security you need, while avoiding most pitfalls.最好改用 SSL,这将增加您需要的所有安全性,同时避免大多数陷阱。

Short of that, you can of course use a CryptoStream .除此之外,您当然可以使用CryptoStream You can only encrypt bytes, but you already indicated that you understand this by mentioning Serializable .您只能加密字节,但您已经通过提及Serializable表示您理解这一点。

Note that if you want to create your own secure stream you will need:请注意,如果您想创建自己的安全流,您将需要:

  • two securely generated keys, and encryption and a MAC key两个安全生成的密钥,以及加密和 MAC 密钥
  • a secure cipher such as AesManaged安全密码,例如AesManaged
  • set using (the defaults) CBC and PKCS7Padding使用(默认值)CBC 和 PKCS7Padding 设置
  • retrieve the randomly generated IV and prepend it to the ciphertext检索随机生成的 IV 并将其添加到密文中
  • create a HMACSHA256 over the result在结果上创建一个HMACSHA256

to be reasonably safe.是相当安全的。 If this does not ring any bells, use the most up to date TLS implementation .如果这没有响起任何铃声,请使用最新的 TLS 实现

AES encryption and decryption an class object in C# AES加密解密C#中的一个类对象

This is the best way for AES encryption and decryption an class object in C#.这是在 C# 中对类对象进行 AES 加密和解密的最佳方式。 Here i'm explain about AES Key and AES IV usage.这里我解释一下 AES Key 和 AES IV 的用法。 And provide an example to write and read byte[] into filestream using AES encryption and decryption an class object in C# .并提供一个示例,使用 AES 加密和解密 C# 中的类对象将 byte[] 写入和读取到文件流中

  1. Create new class创建新班级
    public class Profile
    {
        [JsonPropertyName("name")]
        [JsonProperty(PropertyName = "name")]
        internal string Name { get; set; }

        [JsonPropertyName("password")]
        [JsonProperty(PropertyName = "password")]
        internal string Password { get; set; }

        [JsonPropertyName("profileData")]
        [JsonProperty(PropertyName = "profileData")]
        public byte[] ProfileData { get; set; }
    }
  1. AES KEY used the secret key for the symmetric algorithm. AES KEY使用对称算法的密钥。 This is secret key, is something you keep secret.这是秘钥,是你保密的东西。 Anyone who knows your key (or can guess it) can decrypt any data you've encrypted with it (or forge any authentication codes you've calculated with it, etc.).任何知道您的密钥(或能猜到它)的人都可以解密您用它加密的任何数据(或伪造您用它计算的任何身份验证代码等)。

  2. AES IV used as initialization vector (IV) for the symmetric algorithm. AES IV用作对称算法的初始化向量 (IV)。 Initialization vector is, in its broadest sense, just the initial value used to start some iterated process.从最广泛的意义上讲,初始化向量只是用于启动某些迭代过程的初始值。 So you can maintain in your code itself.所以你可以维护你的代码本身。

        private readonly static byte[] Key = Convert.FromBase64String("AsISxq9OwdZag1163OJqwovXfSWG98m+sPjVwJecfe4=");

        private readonly static byte[] IV = Convert.FromBase64String("Aq0UThtJhjbuyWXtmZs1rw==");
  1. Example for write and read byte[] into filestream using AES encryption and decryption an class object in C#.在 C# 中使用 AES 加密和解密类对象将 byte[] 写入和读取到文件流的示例。
class Program
    {
        private readonly static byte[] Key = Convert.FromBase64String("AsISxq9OwdZag1163OJqwovXfSWG98m+sPjVwJecfe4=");

        private readonly static byte[] IV = Convert.FromBase64String("Aq0UThtJhjbuyWXtmZs1rw==");

        public static Profile Profile { get; set; }

        static void Main(string[] args)
        {
            Profile = new Profile();
            string fileName = "D:\\Profile.txt";
            Profile.Name = "Ramesh";
            Profile.Password = "Password";
            Console.WriteLine("Enter your option:");
            Console.WriteLine("1. Encryption");
            Console.WriteLine("2. Decryption");
            string option = Console.ReadLine();

            if (option == "1")
            {
                FileStream fsWrite = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                string serializeProfile = Newtonsoft.Json.JsonConvert.SerializeObject(Profile);
                Profile.ProfileData = EncryptStringToBytes(serializeProfile);
                fsWrite.Write(Profile.ProfileData, 0, Profile.ProfileData.Length);
                fsWrite.Close();
            }
            else
            {
                FileStream fsRead = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fsRead);
                long numBytes = new FileInfo(fileName).Length;
                string decryptedText = DecryptStringFromBytes(br.ReadBytes((int)numBytes));
                Profile DeserializeProfile = Newtonsoft.Json.JsonConvert.DeserializeObject<Profile>(decryptedText);
                Console.WriteLine("Name :" + DeserializeProfile.Name);
                Console.WriteLine("Password :" + DeserializeProfile.Password);
                Console.ReadKey();
                fsRead.Close();
            }
        }

        private static byte[] EncryptStringToBytes(string profileText)
        {
            byte[] encryptedAuditTrail;

            using (Aes newAes = Aes.Create())
            {
                newAes.Key = Key;
                newAes.IV = IV;

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

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(profileText);
                        }
                        encryptedAuditTrail = msEncrypt.ToArray();
                    }
                }
            }

            return encryptedAuditTrail;
        }

        private static string DecryptStringFromBytes(byte[] profileText)
        {
            string decryptText;

            using (Aes newAes = Aes.Create())
            {
                newAes.Key = Key;
                newAes.IV = IV;

                ICryptoTransform decryptor = newAes.CreateDecryptor(Key, IV);

                using (MemoryStream msDecrypt = new MemoryStream(profileText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            decryptText = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }


            return decryptText;
        }
    }
  1. Console output snap控制台输出快照

Console Output snap控制台输出快照

  1. GitHub link : https://strramesh.github.io/EncryptionAndDecryption/ GitHub 链接: https : //strramesh.github.io/EncryptionAndDecryption/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM