📄 form1.cs
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using Microsoft.Practices.Mobile.PasswordAuthentication;
namespace Encryption
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private byte[] encryptionKey;
private void menuItemSave_Click(object sender, EventArgs e)
{
// Ask user for a password from which we can derive a key
encryptionKey = GetEncryptionKey();
// Encrypt the data
string encryptedData = EncryptData(encryptionKey, textBox1.Text);
// Create the output file
using(StreamWriter sw = new StreamWriter(@"crypt.bin", false))
{
sw.Write(encryptedData);
}
// Display
textBox1.Text = encryptedData;
}
private byte[] GetEncryptionKey()
{
string password;
using (GetPasswordForm frm = new GetPasswordForm())
{
frm.ShowDialog();
password = frm.Password;
}
return DeriveKeyFromPassword(password);
}
private byte[] DeriveKeyFromPassword(string password)
{
byte[] key;
using (RsaAesCryptographyProvider provider =
new RsaAesCryptographyProvider("DevelopersHandbook"))
{
CryptNativeHelper crypto = new CryptNativeHelper(provider);
key = crypto.GetPasswordDerivedKey(password);
}
return key;
}
/// <summary>
/// Encrypts a string using Rijndael/AES symmetric key algorithm
/// </summary>
/// <param name="enckey">The encryption key</param>
/// <param name="plainText">String to be encrypted</param>
/// <returns>Encrypted data as a Base64 encoded string</returns>
private string EncryptData(byte[] key, string plainText)
{
// Get the bytes to encrypt
byte[] plaintextByte = System.Text.Encoding.Unicode.GetBytes(plainText);
// Create a Rijndael instance - automatically generates symmetric key
// and an initialization vector
RijndaelManaged rijndael = new RijndaelManaged();
// Set encryption mode
rijndael.Mode = CipherMode.ECB;
rijndael.Padding = PaddingMode.PKCS7;
// Create a random initialization vector
rijndael.GenerateIV();
byte[] iv = rijndael.IV;
string encodedText = "";
// Define memory stream which will be used to hold encrypted data.
MemoryStream memStrm = new MemoryStream();
// Write the IV length and the IV
memStrm.Write(BitConverter.GetBytes(iv.Length), 0, 4);
memStrm.Write(iv, 0, iv.Length);
// Create a symmetric encryptor
using (ICryptoTransform encryptor = rijndael.CreateEncryptor(key, iv))
{
// Create a CryptStream to write to the output file
CryptoStream cryptStrm = new CryptoStream(memStrm, encryptor, CryptoStreamMode.Write);
// Write the content to be encrypted
cryptStrm.Write(plaintextByte, 0, plaintextByte.Length);
cryptStrm.FlushFinalBlock();
// Convert encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = memStrm.ToArray();
// Close the treams
memStrm.Close();
cryptStrm.Close();
// Convert encrypted data into a base64-encoded string.
encodedText = Convert.ToBase64String(cipherTextBytes);
}
return encodedText;
}
private void menuItemRestore_Click(object sender, EventArgs e)
{
// Ask user for a password from which we can derive the key
encryptionKey = GetEncryptionKey();
// Read encrypted data from the file
string fileContents;
using (StreamReader sr = new StreamReader(@"crypt.bin"))
{
fileContents = sr.ReadToEnd();
}
// Write decrypted data back into the TextBox
textBox1.Text = DecryptData(encryptionKey, fileContents);
}
private string DecryptData(byte[] key, string encryptedData)
{
string retStr = "";
// Create a symmetric decryptor
RijndaelManaged rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.ECB;
rijndael.Padding = PaddingMode.PKCS7;
// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = Convert.FromBase64String(encryptedData);
// Define memory stream to use to read encrypted data.
MemoryStream inStream = new MemoryStream(cipherTextBytes);
// Read the IV length from the buffer
int ivLength = BitConverter.ToInt32(cipherTextBytes, 0);
// Reposition to after 'length' bytes in stream
inStream.Position = 4;
// Read the IV from the input stream
byte[] iv = new byte[ivLength];
inStream.Read(iv, 0, ivLength);
using (ICryptoTransform decryptor = rijndael.CreateDecryptor(key, iv))
{
// Create a CryptStream to read from the file
CryptoStream cryptStrm = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read);
// Create another MemoryStream for the output
MemoryStream memStrm = new MemoryStream();
byte[] buffer = new byte[2048];
int totalbytes = 0;
do
{
int bytesRead = cryptStrm.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
memStrm.Write(buffer, 0, bytesRead);
totalbytes += bytesRead;
} while (true);
// Write the content to be encrypted
memStrm.Flush();
memStrm.Seek(0, SeekOrigin.Begin);
// Get the string from the bytes we read
retStr = System.Text.Encoding.Unicode.GetString(memStrm.GetBuffer(), 0, totalbytes);
cryptStrm.Close();
}
return retStr;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -