|
|
|
|
private void button5_Click(object sender, EventArgs e) {
|
|
|
|
|
string mensaje = this.textBox4.Text;
|
|
|
|
|
string publicKeyFile = "publicKey.xml";
|
|
|
|
|
string privateKeyFile = "privateKey.xml";
|
|
|
|
|
generarClaves(publicKeyFile, privateKeyFile);
|
|
|
|
|
|
|
|
|
|
byte[] Encriptado = encriptar(publicKeyFile, Encoding.UTF8.GetBytes(mensaje));
|
|
|
|
|
byte[] Desencriptado = Desencriptar(privateKeyFile, Encriptado);
|
|
|
|
|
|
|
|
|
|
this.label7.Text = BitConverter.ToString(Encriptado);
|
|
|
|
|
this.label8.Text = Encoding.UTF8.GetString(Desencriptado);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void generarClaves(string publicKF, string privateKF) {
|
|
|
|
|
using (var rsa = new RSACryptoServiceProvider(2048)) {
|
|
|
|
|
rsa.PersistKeyInCsp = false;
|
|
|
|
|
|
|
|
|
|
if (File.Exists(publicKF))
|
|
|
|
|
File.Delete(publicKF);
|
|
|
|
|
if (File.Exists(privateKF))
|
|
|
|
|
File.Delete(privateKF);
|
|
|
|
|
|
|
|
|
|
string publicKey = rsa.ToXmlString(false);
|
|
|
|
|
File.WriteAllText(publicKF, publicKey);
|
|
|
|
|
string privateKey = rsa.ToXmlString(true);
|
|
|
|
|
File.WriteAllText(privateKF, privateKey);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static byte[] encriptar(string publicKF, byte[] textoPlano) {
|
|
|
|
|
byte[] encriptado;
|
|
|
|
|
using (var rsa = new RSACryptoServiceProvider(2048)) {
|
|
|
|
|
rsa.PersistKeyInCsp = false;
|
|
|
|
|
string publicKey = File.ReadAllText(publicKF);
|
|
|
|
|
rsa.FromXmlString(publicKey);
|
|
|
|
|
encriptado = rsa.Encrypt(textoPlano, true);
|
|
|
|
|
}
|
|
|
|
|
return (encriptado);
|
|
|
|
|
}
|
|
|
|
|
public static byte[] Desencriptar(string privateKF, byte[] textoEncriptado) {
|
|
|
|
|
byte[] Desencriptado;
|
|
|
|
|
using (var rsa = new RSACryptoServiceProvider(2048)) {
|
|
|
|
|
rsa.PersistKeyInCsp = false;
|
|
|
|
|
string privateKey = File.ReadAllText(privateKF);
|
|
|
|
|
rsa.FromXmlString(privateKey);
|
|
|
|
|
Desencriptado = rsa.Decrypt(textoEncriptado, true);
|
|
|
|
|
}
|
|
|
|
|
return (Desencriptado);
|
|
|
|
|
}
|