Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.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#_Encryption - Fatal编程技术网

C# 这是加密的好方法吗?

C# 这是加密的好方法吗?,c#,encryption,C#,Encryption,目前我正在使用System.Security.Cryptography,这是我的密码: private static SymmetricAlgorithm createCryptoServiceProvider(string key, string IV) { byte[] password; using (MD5 md5 = MD5.Create()) password = md5.ComputeHash(Encodin

目前我正在使用System.Security.Cryptography,这是我的密码:

    private static SymmetricAlgorithm createCryptoServiceProvider(string key, string IV)
    {
        byte[] password;

        using (MD5 md5 = MD5.Create())
            password = md5.ComputeHash(Encoding.UTF8.GetBytes(key));
        var crypt = new TripleDESCryptoServiceProvider();
        byte[] iv = Encoding.UTF8.GetBytes(IV);
        crypt.IV = iv;
        crypt.Key = password;
        return crypt;
    }
    public static byte[] Serialize(object obj, string key, string key2)
    {
        var provider = createCryptoServiceProvider(key, key2);
        using (MemoryStream memory = new MemoryStream())
        {
            using (CryptoStream stream = new CryptoStream(memory, provider.CreateEncryptor(), CryptoStreamMode.Write))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);
            }
            return memory.ToArray();
        }

    }
    public static object Deserialize(byte[] inBytes, string key, string key2)
    {
        var provider = createCryptoServiceProvider(key, key2);

        using(MemoryStream memory = new MemoryStream(inBytes))
        {
            using (CryptoStream stream = new CryptoStream(memory, provider.CreateDecryptor(), CryptoStreamMode.Read))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(stream);
            }
        }
    }

当我准备通过套接字发送数据时,我使用它创建一个对象,该对象将在一个私有字段中包含密钥,并保留该密钥,以便它知道该密钥,当在另一个客户端上接收到该对象时,它在发送的对象中使用一个函数,该函数使用该私有字符串密钥key2;并将消息加密为字节,并将密钥设置为“”,然后将保留字节的对象发回。所以现在只有原始发送者才能解密它。这是一个好方法还是有更好的方法

不要尝试自己进行加密


示例代码使用TcpClient,但它应该与任何流IO一起工作,因此直接套接字也应该可以。

不要尝试自己进行加密


示例代码使用TcpClient,但它应该可以与任何流IO一起工作,因此直接套接字也可以。

同意。虽然加密很有趣,但在我看来,没有必要重新发明轮子。祝你的代码好运!好的,谢谢你的快速回复,我看到了很多关于如何加密的问题,但我不知道哪一个是最好的。同意。虽然加密很有趣,但在我看来,没有必要重新发明轮子。祝你的代码好运!好的,谢谢你的快速回复,我看到了很多关于如何加密的问题,但我不知道哪一个是最好的。