参照加密方法我们很快的实现RSA的解密方法,同样我们从流中读取密钥,然后传递给FromXmlString()方法,最后对密文进行解密,注意调用的是RSA算法的Decrypt()方法,在使用胶水代码时千万别忘记修改了。
现在我们终于完成了通用的加密解密方法,接下来肯定是要测试一下这些方法的效果如何,这次我使用单元测试。
[TestMethod] public void TestStart() { try { string cipherText; string plainText; #region Hash Algo cipherText = CryptographyUtils.Encrypt( CryptographyUtils.CreateHashAlgoMd5(), @"您们好(Hello everyone)."); Assert.IsTrue(CryptographyUtils.IsHashMatch( CryptographyUtils.CreateHashAlgoMd5(), cipherText, @"您们好(Hello everyone).")); cipherText = CryptographyUtils.Encrypt( CryptographyUtils.CreateHashAlgoSHA1(), @"您们好(Hello everyone)."); Assert.IsTrue(CryptographyUtils.IsHashMatch( CryptographyUtils.CreateHashAlgoSHA1(), cipherText, @"您们好(Hello everyone).")); #endregion #region Asymm Algo CryptographyUtils.GenerateRSAKey(CryptographyUtils.CreateAsymmAlgoRSA()); cipherText = CryptographyUtils.Encrypt( CryptographyUtils.CreateAsymmAlgoRSA(), @"%dk>JK.RusH", @"c579D-E>?$)_"); plainText = CryptographyUtils.Decrypt( CryptographyUtils.CreateAsymmAlgoRSA(), cipherText, @"c579D-E>?$)_"); Assert.AreEqual<string>(@"%dk>JK.RusH", plainText); #endregion #region Symm Algo cipherText = CryptographyUtils.Encrypt( CryptographyUtils.CreateSymmAlgoAes(), "JK_huangJK_huangJK_huang黄钧航", "JK_huangJK_huang", 256); plainText = CryptographyUtils.Decrypt( CryptographyUtils.CreateSymmAlgoAes(), cipherText, "JK_huangJK_huang", 256); Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航", plainText); cipherText = CryptographyUtils.Encrypt( CryptographyUtils.CreateSymmAlgoDES(), "JK_huangJK_huangJK_huang黄钧航", "JK_huangJK_huang", 64); plainText = CryptographyUtils.Decrypt( CryptographyUtils.CreateSymmAlgoDES(), cipherText, "JK_huangJK_huang", 64); Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航", plainText); cipherText = CryptographyUtils.Encrypt( CryptographyUtils.CreateSymmAlgoRC2(), "JK_huangJK_huangJK_huang黄钧航", "JK_huangJK_huang", 128); plainText = CryptographyUtils.Decrypt(CryptographyUtils.CreateSymmAlgoRC2(), cipherText, "JK_huangJK_huang", 128); Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航", plainText); cipherText = CryptographyUtils.Encrypt( CryptographyUtils.CreateSymmAlgoRijndael(), "JK_huangJK_huangJK_huang黄钧航", "JK_huangJK_huang", 256); plainText = CryptographyUtils.Decrypt( CryptographyUtils.CreateSymmAlgoRijndael(), cipherText, "JK_huangJK_huang", 256); Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航", plainText); cipherText = CryptographyUtils.Encrypt( CryptographyUtils.CreateSymmAlgoTripleDes(), "JK_huangJK_huangJK_huang黄钧航", "JK_huangJK_huang", 192); plainText = CryptographyUtils.Decrypt( CryptographyUtils.CreateSymmAlgoTripleDes(), cipherText, "JK_huangJK_huang", 192); Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航", plainText); #endregion } catch (Exception ex) { Debug.Assert(false, ex.Message); } }
图6 单元测试结果
1.1.3 总结
本文给出了.NET中的一些加密算法的通用实现(哈希加密,对称加密和非对称加密算法),由于加密和解密的方法都是比较固定,而且每中算法有具有其特性,所以这里我们给出了它们的实现,而且我们可以把上的方法封装在一个加密Helper类,这样可以大大提高我们开发效率,而且它充分的利用多态性使得加密算法灵活性和维护性大大提高。