如何使用C#中的对称密钥加密用密钥加密字符串? [英] How to encrypt a string with a key using symmetric key encryption in C#?

查看:98
本文介绍了如何使用C#中的对称密钥加密用密钥加密字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用密钥加密字符串。我试过这段代码。我收到了这个错误。请帮帮我。

任何对称密钥算法。



I want to encrypt a string with a key. i have tried this code. I got this error. Please help me.
Any Symmetric Key Algorithm.

Error	1	'string' does not contain a definition for 'CreateEncryptor' and no extension method 'CreateEncryptor' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)	G:\2nd Sem\Web Services\My WebService Projects in .NET\RecordProtocol\RecordProtocol\Form1.cs	68	64	RecordProtocol





我尝试了什么:





What I have tried:

private void button4_Click(object sender, EventArgs e)//Encrypt
{
            string PlainText = textBox6.Text;
            string key = textBox10.Text;
            textBox7.Text = Encrypt(PlainText,key);
}
public static string Encrypt(string PlainText, string key)
{
            MemoryStream ms = new MemoryStream();
            CryptoStream crypstream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(crypstream);
            sw.WriteLine(PlainText);
            sw.Close();
            crypstream.Close();
            byte[] buffer = ms.ToArray();
            ms.Close();
            string output;
            output = Encoding.ASCII.GetString(buffer);
            return output;           
}

推荐答案

如错误所示, CreateEncryptor 不是字符串函数 - 它是在所选加密算法上调用的方法。例如: SymmetricAlgorithm.CreateEncryptor方法(System.Security.Cryptography) [ ^ ]或

SymmetricAlgorithm.CreateEncryptor方法(Byte [],Byte [])(System.Security.Cryptography) [ ^ ]

如果您希望加密工作可靠 - 并且不可靠的加密对任何人都没用 - 我建议你开始阅读对称加密:加密数据 [ ^ ]

该链接包含工作示例。
As the error says, CreateEncryptor is not a string function - it's a method which is called on the selected encryption algorithm. For example: SymmetricAlgorithm.CreateEncryptor Method (System.Security.Cryptography)[^] or
SymmetricAlgorithm.CreateEncryptor Method (Byte[], Byte[]) (System.Security.Cryptography)[^]
If you want encryption to work reliably - and unreliable encryption is no use to anyone - I'd suggest you start reading up on symmetric encryption: Encrypting Data[^]
The link includes working examples.


public string Md5AddSecret(string pass)
    {
        string hashKey = "kuiygHJG564qwertynbv";
        string terminalId = "99999999";
        string reference = "0000008765";

        string x = Convert.ToBase64String(
            new SHA1CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(
                string.Concat(hashKey, terminalId, reference, pass))));

        return x;
    }


这篇关于如何使用C#中的对称密钥加密用密钥加密字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆