首页 > 代码库 > 微软RC2CryptoServiceProvider 加解密
微软RC2CryptoServiceProvider 加解密
using System; using System.IO; using System.Text; using System.Security.Cryptography; namespace RC2CryptoServiceProvider_Examples { class MyMainClass1 { public static void Main() { // Create a new instance of the RC2CryptoServiceProvider class // and automatically generate a Key and IV. RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); Console.WriteLine("Effective key size is {0} bits.", rc2CSP.EffectiveKeySize); string strIV = "1234567"; // Get the key and IV. byte[] key = rc2CSP.Key; byte[] IV ;//= rc2CSP.IV; IV = ASCIIEncoding.ASCII.GetBytes(strIV); // Get an encryptor. ICryptoTransform encryptor = rc2CSP.CreateEncryptor(key, IV); // Encrypt the data as an array of encrypted bytes in memory. MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); // Convert the data to a byte array. string original = "Here is some data to encrypt."; byte[] toEncrypt = Encoding.ASCII.GetBytes(original); // Write all data to the crypto stream and flush it. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); // Get the encrypted array of bytes. byte[] encrypted = msEncrypt.ToArray(); /**/ /////////////////////////////////////////////////////// // This is where the data could be transmitted or saved. /**/ /////////////////////////////////////////////////////// //Get a decryptor that uses the same key and IV as the encryptor. ICryptoTransform decryptor = rc2CSP.CreateDecryptor(key, IV); // Now decrypt the previously encrypted message using the decryptor // obtained in the above step. MemoryStream msDecrypt = new MemoryStream(encrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); byte[] fromEncrypt = new byte[toEncrypt.Length]; // Read the data out of the crypto stream. csDecrypt.Read(fromEncrypt, 0, toEncrypt.Length); // Convert the byte array back into a string. String roundtrip = Encoding.ASCII.GetString(fromEncrypt); // Display the original data and the decrypted data. Console.WriteLine("Original: {0}", original); Console.WriteLine("Round Trip: {0}", roundtrip); Console.ReadLine(); } } }
微软RC2CryptoServiceProvider 加解密
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。