Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C语言中加密和解密对象#_C#_Wcf_Encryption - Fatal编程技术网

C# 在C语言中加密和解密对象#

C# 在C语言中加密和解密对象#,c#,wcf,encryption,C#,Wcf,Encryption,我使用WCF web服务以数据对象的形式通过Internet将数据从服务器发送到客户端。我创建了一个可序列化的类,并使用该类发送数据 下面是我班的一个例子: [Serializable] public class DBOList { public string A{ get; set; } public string B { get; set; } } 我是否可以加密此对象中的数据,并将其作为流发送到客户端 如果不是,实现这一目标的最佳方法是什么 加密代码: D

我使用WCF web服务以数据对象的形式通过Internet将数据从服务器发送到客户端。我创建了一个可序列化的类,并使用该类发送数据

下面是我班的一个例子:

[Serializable]
public class DBOList
{
    public string A{ get; set; }
    public string B { get; set; }
}
我是否可以加密此对象中的数据,并将其作为流发送到客户端

如果不是,实现这一目标的最佳方法是什么

加密代码:

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

最好改用SSL,这将增加您需要的所有安全性,同时避免大多数陷阱

除此之外,您当然可以使用
加密流
。您只能加密字节,但您已经通过提到
Serializable
表明您理解这一点

请注意,如果要创建自己的安全流,则需要:

  • 两个安全生成的密钥、加密和一个MAC密钥
  • 一种安全的密码,如
    aes
  • 使用(默认值)CBC和PKCS7Padding进行设置
  • 检索随机生成的IV并将其前置到密文
  • 在结果上创建一个
    HMACSHA256
为了合理的安全。如果这不起任何作用,请使用最新的TLS实现。

AES加密和解密C中的类对象# 这是对C#中的类对象进行AES加密和解密的最佳方法。这里我将解释AES密钥和AES IV的用法。并提供一个示例,使用AES加密和解密C#中的类对象,将字节[]写入并读取到文件流中

  • 创建新类
  • AES密钥将密钥用于对称算法。这是秘密钥匙,是你要保密的东西。任何知道你的密钥(或者可以猜到)的人都可以解密你用它加密的任何数据(或者伪造你用它计算的任何身份验证码,等等)

  • AES IV用作对称算法的初始化向量(IV)。从最广泛的意义上讲,初始化向量只是用于启动某个迭代过程的初始值。因此,您可以在代码本身中进行维护

  • 使用AES加密和解密C#中的类对象将字节[]写入和读取到文件流的示例
  • 类程序
    {
    私有只读静态字节[]键=Convert.FromBase64String(“AsISxq9OwdZag1163OJqwovXfSWG98m+sPjVwJecfe4=”);
    private readonly static byte[]IV=Convert.FromBase64String(“Aq0UThtJhjbuyWXtmZs1rw==”;
    公共静态配置文件{get;set;}
    静态void Main(字符串[]参数)
    {
    Profile=新的Profile();
    字符串fileName=“D:\\Profile.txt”;
    Profile.Name=“Ramesh”;
    Profile.Password=“Password”;
    Console.WriteLine(“输入您的选项:”);
    Console.WriteLine(“1.加密”);
    控制台写入线(“2.解密”);
    字符串选项=Console.ReadLine();
    如果(选项==“1”)
    {
    FileStream fsWrite=newfilestream(文件名,FileMode.Create,FileAccess.Write);
    string serializeProfile=Newtonsoft.Json.JsonConvert.SerializeObject(配置文件);
    Profile.ProfileData=EncryptStringToBytes(序列化配置文件);
    写入(Profile.ProfileData,0,Profile.ProfileData.Length);
    fsWrite.Close();
    }
    其他的
    {
    FileStream fsRead=newfilestream(文件名,FileMode.Open,FileAccess.Read);
    BinaryReader br=新的BinaryReader(fsRead);
    long numBytes=新文件信息(fileName).Length;
    string decryptedText=DecryptStringFromBytes(br.ReadBytes((int)numBytes));
    Profile DeserializeProfile=Newtonsoft.Json.JsonConvert.DeserializeObject(decryptedText);
    Console.WriteLine(“名称:“+DeserializeProfile.Name”);
    Console.WriteLine(“密码:+DeserializeProfile.Password”);
    Console.ReadKey();
    fsRead.Close();
    }
    }
    私有静态字节[]EncryptStringToBytes(字符串配置文件文本)
    {
    字节[]EncryptedAuditRail;
    使用(Aes newAes=Aes.Create())
    {
    newAes.Key=Key;
    newAes.IV=IV;
    ICryptoTransform encryptor=newAes.CreateEncryptor(密钥,IV);
    使用(MemoryStream msEncrypt=new MemoryStream())
    {
    使用(CryptoStream csEncrypt=new CryptoStream(msEncrypt,encryptor,CryptoStreamMode.Write))
    {
    使用(StreamWriter swEncrypt=newstreamwriter(csEncrypt))
    {
    swEncrypt.Write(profileText);
    }
    EncryptedAuditRail=msEncrypt.ToArray();
    }
    }
    }
    返回EncryptedAuditRail;
    }
    私有静态字符串解密StringFromBytes(字节[]profileText)
    {
    字符串解密文本;
    使用(Aes newAes=Aes.Create())
    {
    newAes.Key=Key;
    newAes.IV=IV;
    ICryptoTransform decryptor=newAes.CreateDecryptor(密钥,IV);
    使用(MemoryStream msDecrypt=新的MemoryStream(profileText))
    {
    使用(CryptoStream csDecrypt=新加密流(msDecrypt、解密程序、CryptoStreamMode.Read))
    {
    使用(StreamReader srDecrypt=新的StreamReader(csDecrypt))
    {
    decryptText=srDecrypt.ReadToEnd();
    }
    }
    }
    }
    返回文本;
    }
    }
    
  • 控制台输出捕捉
  • GitHub链接:
  • WCF将为您提供此服务
        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; }
        }
    
            private readonly static byte[] Key = Convert.FromBase64String("AsISxq9OwdZag1163OJqwovXfSWG98m+sPjVwJecfe4=");
    
            private readonly static byte[] IV = Convert.FromBase64String("Aq0UThtJhjbuyWXtmZs1rw==");
    
    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;
            }
        }