非对称密码体制35页PPT
- 格式:ppt
- 大小:3.22 MB
- 文档页数:35
非对称加密(公钥加密)指加密和解密使用不同密钥的加密算法,也称为公私钥加密。
假设两个用户要加密交换数据,双方交换公钥,使用时一方用对方的公钥加密,另一方即可用自己的私钥解密。
如果企业中有n个用户,企业需要生成n对密钥,并分发n个公钥。
由于公钥是可以公开的,用户只要保管好自己的私钥即可,因此加密密钥的分发将变得十分简单。
同时,由于每个用户的私钥是唯一的,其他用户除了可以可以通过信息发送者的公钥来验证信息的来源是否真实,还可以确保发送者无法否认曾发送过该信息。
非对称加密的缺点是加解密速度要远远慢于对称加密,在某些极端情况下,甚至能比非对称加密慢上1000倍。
这里非对称加密采用RSA算法为例,具体使用时下面代码中带有说明,C#完整程序代码如下:using System;using System.Collections.Generic;using System.Text;using System.Security.Cryptography;using System.Windows.Forms;using System.Globalization;namespace WindowsApplication12{class RSA{/// <summary>/// generate private key and public key arr[0] for private key arr[1] for public key/// </summary>/// <returns></returns>public static string[] GenerateKeys(){string[] sKeys = new String[2];RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();//从XML文件中读取公钥和私钥sKeys[0] = rsa.ToXmlString(true);sKeys[1] = rsa.ToXmlString(false);return sKeys;}/// <summary>/// RSA Encrypt/// </summary>/// <param name="sSource" >Source string</param>/// <param name="sPublicKey" >public key</param>/// <returns></returns>public static string EncryptString(string sSource, string sPublicKey) {try{RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();string plaintext = sSource;rsa.FromXmlString(sPublicKey);byte[] cipherbytes;byte[] byteEn = rsa.Encrypt(Encoding.UTF8.GetBytes("a"), false); cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(plaintext), false);StringBuilder sbString = new StringBuilder();for (int i = 0; i < cipherbytes.Length; i++){sbString.Append(cipherbytes[i] + ",");}return sbString.ToString();}catch{MessageBox.Show("数据错误");return null;}}/// <summary>/// RSA Decrypt/// </summary>/// <param name="sSource">Source string</param>/// <param name="sPrivateKey">Private Key</param>/// <returns></returns>public static string DecryptString(String sSource, string sPrivateKey) {try{RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();rsa.FromXmlString(sPrivateKey);byte[] byteEn = rsa.Encrypt(Encoding.UTF8.GetBytes("a"), false); string[] sBytes = sSource.Split(',');for (int j = 0; j < sBytes.Length; j++){if (sBytes[j] != ""){byteEn[j] = Byte.Parse(sBytes[j]);}}byte[] plaintbytes = rsa.Decrypt(byteEn, false);return Encoding.UTF8.GetString(plaintbytes);}catch{MessageBox.Show("数据错误");return null;}}}}Hash算法(哈希值)Hash算法特别的地方在于它是一种单向算法,用户可以通过Hash算法对目标信息生成一段特定长度的唯一的Hash值,却不能通过这个Hash值重新获得目标信息。