Welcome

首页 / 软件开发 / 数据结构与算法 / 详解.Net下的加密解密算法(6) 玩转非对称加密

详解.Net下的加密解密算法(6) 玩转非对称加密2013-08-19 csdn ghostbear本博文来聊聊怎么玩转非对称加密吧,这里主要介绍.NET算法下的3种非对称加密算法:DSA,RSA,ECDsa。上两篇博文分别为Hash家族和非对称加密家族找到了lead,现在我们就为非对称加密技术找个合适的lead吧。

首先创建一个接口:“IEncryptAndDecrypt”,然后为上面的3中算法分别创建3个实现类并让这些类实现接口“IEncryptAndDecrypt”。它们的情况如下图:

这下我们把这些哥们都召集起来了,现在我们就给他们找一个lead:“EncryptAndDecryptInvoker”。以后我们要找这些非对称加密家族的哥们的时候就可以直接联系lead啦!来瞧瞧现在的队伍吧:

看上去挺不错的,我们来看看咱们的lead是否能胜任它的工作吧:

EncryptAndDecryptInvoker lead;string data = "我们是非对称加密家族!";//执行环境CryptogramSetting setting = new CryptogramSetting();byte[] bData;//加密处理前byte[] aData;//机密处理后byte[] tmp;Encoding encoding = System.Text.Encoding.UTF8;sys_cryptography.DSA tmp_dsa = sys_cryptography.DSA.Create();string DSA_PublicKey = tmp_dsa.ToXmlString(false);string DSA_PrivateKey = tmp_dsa.ToXmlString(true);sys_cryptography.RSA tmp_rsa = sys_cryptography.RSA.Create();string RSA_PublicKey = tmp_rsa.ToXmlString(false);string RSA_PrivateKey = tmp_rsa.ToXmlString(true);sys_cryptography.ECDsa tmp_ecdsa = sys_cryptography.ECDsa.Create();string ECDsa_PublicKey = tmp_ecdsa.ToXmlString(false);string ECDsa_PrivateKey = tmp_ecdsa.ToXmlString(true);//DSAHashtable dsaKey = new Hashtable();dsaKey["publickey"] = DSA_PublicKey;dsaKey["privatekey"] = DSA_PrivateKey;setting.CryptogramType = CryptogramType.UnsymmetryEncryptAndDecrypt;setting.PublicKeyAndPrivateKey = dsaKey;lead = new EncryptAndDecryptInvoker(new DSA(), setting);Console.WriteLine("DSA:");tmp = lead.Encrypt(encoding.GetBytes(data));Console.WriteLine("签名:"+Convert.ToBase64String(tmp));lead.SetVertifyData(encoding.GetBytes(data));//验证签名bool isOriginal = lead.Decrypt(tmp)[0] == 1 ? true : false ;Console.WriteLine("签名结果:" + isOriginal);//RSAHashtable rsaKey = new Hashtable();rsaKey["publickey"] = RSA_PublicKey;rsaKey["privatekey"] = RSA_PrivateKey;setting.CryptogramType = CryptogramType.UnsymmetryEncryptAndDecrypt;setting.PublicKeyAndPrivateKey = rsaKey;lead = new EncryptAndDecryptInvoker(new RSA(), setting);Console.WriteLine("RSA:");tmp = lead.Encrypt(encoding.GetBytes(data));Console.WriteLine("加密:" + Convert.ToBase64String(tmp));tmp = lead.Decrypt(tmp);Console.WriteLine("解密:" + encoding.GetString(tmp));//ECDsa问题:ECDsa不能到处公匙和私匙Hashtable ecdsaKey = new Hashtable();ecdsaKey["publickey"] = ECDsa_PublicKey;ecdsaKey["privatekey"] = ECDsa_PrivateKey;setting.CryptogramType = CryptogramType.UnsymmetryEncryptAndDecrypt;setting.PublicKeyAndPrivateKey = ecdsaKey;lead = new EncryptAndDecryptInvoker(new ECDsa(), setting);Console.WriteLine("ECDsa:");tmp = lead.Encrypt(encoding.GetBytes(data));Console.WriteLine("加密:" + Convert.ToBase64String(tmp));tmp = lead.Decrypt(tmp);Console.WriteLine("解密:" + encoding.GetString(tmp));Console.ReadKey();