📄 encryptpasswordrsa.cs
字号:
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Xml;
namespace Encryption
{
class EncryptPasswordRSA
{
public void SavePassword(string cleartext)
{
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
//Create a new instance of RSAParameters.
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo = ReadPublicKeyXML(RSAKeyInfo);
//Import key parameters into RSA.
rsaProvider.ImportParameters(RSAKeyInfo);
//Encrypt the supplied data
byte[] cipherText =
rsaProvider.Encrypt(new UnicodeEncoding().GetBytes(cleartext), false);
//Save the Cipher-Text
using (System.IO.StreamWriter sw =
new System.IO.StreamWriter(GetApplicationDirectory() + @"\UserKeyCipher.txt", false))
{
sw.Write(Convert.ToBase64String(cipherText));
sw.Flush();
}
}
private RSAParameters ReadPublicKeyXML(RSAParameters RSAKeyInfo)
{
// Read the public key from the XML file with a reader.
using (Stream stm = File.OpenRead(GetApplicationDirectory() + @"\PublicKey.xml"))
{
XmlTextReader reader = new XmlTextReader(stm);
// Do performant ref comparison
string ev = reader.NameTable.Add("RSAKeyValue");
while (reader.Read())
{
if (reader.LocalName == ev)
{
// Process it!
int eventDepth = reader.Depth;
reader.Read();
while (reader.Depth > eventDepth)
{
if (reader.MoveToContent() == XmlNodeType.Element)
{
switch (reader.Name)
{
case "Modulus":
RSAKeyInfo.Modulus = Convert.FromBase64String(reader.ReadString());
break;
case "Exponent":
RSAKeyInfo.Exponent = Convert.FromBase64String(reader.ReadString());
break;
}
}
reader.Read();
}
}
}
}
return RSAKeyInfo;
}
private string GetApplicationDirectory()
{
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -