非对称性加解密原理: 通过RSACryptoServiceProvider 类,生成一对 公钥,私钥。公钥加密数据必须用私钥才能解密,反之,私钥加密数据必须使用公钥才能解密。
私钥自己保留,公钥对外公布。使用公钥加密,然后用自己保留的私钥解密数据。
程序初始化时生成一对私钥,公钥。
输入明文,点击“加密” 后将加密数据Base64位转换然后显示
点击“解密”后将转换后的Base64位数据转换为byte[] 然后使用私钥解密。
代码:
string PublicKey, PrivateKey; RSACryptoServiceProvider rsaProvider; Encoding mybase = Encoding.GetEncoding("utf-8"); public MainWindow() { InitializeComponent(); Init(); } private void Init() { rsaProvider = new RSACryptoServiceProvider(1024); PublicKey = rsaProvider.ToXmlString(false); PrivateKey = rsaProvider.ToXmlString(true); txt_publickey.Text = PublicKey; txt_privatekey.Text = PrivateKey; } /// <summary> /// 使用公钥加密 /// </summary> /// <param name="data"></param> /// <returns></returns> byte[] EncryptData(byte[] data) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024); rsa.FromXmlString(PublicKey); return rsa.Encrypt(data, false); } /// <summary> /// 使用私钥解密 /// </summary> /// <param name="data"></param> /// <returns></returns> byte[] DecryptData(byte[] data) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024); rsa.FromXmlString(PrivateKey); return rsa.Decrypt(data,false); } /// <summary> /// 加密按钮事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Encrypt_Click(object sender, RoutedEventArgs e) { //原文转为字节数组 byte[] b = mybase.GetBytes(txt_fact.Text); //加密 byte[] encrypt = EncryptData(b); //转为64位字符串 txt_encrypt.Text = Convert.ToBase64String(encrypt); } /// <summary> /// 解密按钮事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Decrypt_Click(object sender, RoutedEventArgs e) { //解析64位字符串为字节数组 byte[] b = Convert.FromBase64String(txt_encrypt.Text); //解密字节字符串 byte[] decrypt = DecryptData(b); //将字节字符串转为原文 txt_Decrypt.Text = mybase.GetString(decrypt); } }