给你一个
我下载的例子,供参考:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text; public class FileEncrypt
{
public FileEncrypt()
{
//
// TODO: 在此处添加构造函数逻辑
//
} public static Byte[] ConvertStringToByteArray(String s)
{
return (new UnicodeEncoding()).GetBytes(s);
} public static void Main()
{
//创建文件流
FileStream fs = new FileStream("EncryptedFile.txt",FileMode.Create,FileAccess.Write); Console.WriteLine("输入一些要存储在加密文件中的文本::");
String strinput = Console.ReadLine(); Byte[] bytearrayinput=ConvertStringToByteArray(strinput); //具有随机密钥的 DES 实例
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//从此实例创建 DES 加密器
ICryptoTransform desencrypt = des.CreateEncryptor(); //创建使用 des 加密转换文件流的加密流
CryptoStream cryptostream = new CryptoStream(fs,desencrypt,CryptoStreamMode.Write); //写出 DES 加密文件
cryptostream.Write(bytearrayinput,0,bytearrayinput.Length); cryptostream.Close(); //创建文件流以读回加密文件
FileStream fsread = new FileStream("EncryptedFile.txt",FileMode.Open,FileAccess.Read); //从此 des 实例创建 DES 解密器
ICryptoTransform desdecrypt = des.CreateDecryptor(); //创建加密流集合以便对传入的字节进行读取并执行 des 解密转换
CryptoStream cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);
//输出已解密文件的内容
Console.WriteLine( (new StreamReader(cryptostreamDecr, new UnicodeEncoding())).ReadToEnd() ); Console.WriteLine ();
Console.WriteLine ("按 Enter 键继续...");
Console.ReadLine();
}
}
我下载的例子,供参考:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text; public class FileEncrypt
{
public FileEncrypt()
{
//
// TODO: 在此处添加构造函数逻辑
//
} public static Byte[] ConvertStringToByteArray(String s)
{
return (new UnicodeEncoding()).GetBytes(s);
} public static void Main()
{
//创建文件流
FileStream fs = new FileStream("EncryptedFile.txt",FileMode.Create,FileAccess.Write); Console.WriteLine("输入一些要存储在加密文件中的文本::");
String strinput = Console.ReadLine(); Byte[] bytearrayinput=ConvertStringToByteArray(strinput); //具有随机密钥的 DES 实例
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//从此实例创建 DES 加密器
ICryptoTransform desencrypt = des.CreateEncryptor(); //创建使用 des 加密转换文件流的加密流
CryptoStream cryptostream = new CryptoStream(fs,desencrypt,CryptoStreamMode.Write); //写出 DES 加密文件
cryptostream.Write(bytearrayinput,0,bytearrayinput.Length); cryptostream.Close(); //创建文件流以读回加密文件
FileStream fsread = new FileStream("EncryptedFile.txt",FileMode.Open,FileAccess.Read); //从此 des 实例创建 DES 解密器
ICryptoTransform desdecrypt = des.CreateDecryptor(); //创建加密流集合以便对传入的字节进行读取并执行 des 解密转换
CryptoStream cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);
//输出已解密文件的内容
Console.WriteLine( (new StreamReader(cryptostreamDecr, new UnicodeEncoding())).ReadToEnd() ); Console.WriteLine ();
Console.WriteLine ("按 Enter 键继续...");
Console.ReadLine();
}
}
解决方案 »
- WINFORM 左侧导航栏 树型菜单
- winform从数据表中创建动态菜单时,怎样绑定其事件
- 通过网页连接访问并启动服务器上的 winfrom程序?????
- wince下的form怎么让它在wince中全屏(C#.2005开发的),有经验的进来指点下
- 急!!!!请问诸如连锁超市和连锁药店运用的软件是C/S模式还是B/S模式???
- 在.Net下实现PNG图片的保存比原来的容量大,这是为什么?
- 保存到数据库中的中文为“?”,急求解决方法,在线等!!!
- 谁能帮我把C的代码转换成C#能用的
- 100分求:一个类似于这个控件的源代码!不够再加分
- webservice二次开发
- C#泛型编程………怎么用?迷惑………
- 一个关于更新dataset的问题
使用Des,MD5 加密.解密.字符串.文件:
//加密字符串,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了)
public string DesEncrypt(string strText, string strEncrKey)
//解密字符串,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) public string DesDecrypt(string strText,string sDecrKey) //加密数据文件,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) public void DesEncrypt(string m_InFilePath,string m_OutFilePath,string strEncrKey) //解密数据文件,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) public void DesDecrypt(string m_InFilePath,string m_OutFilePath,string sDecrKey) //MD5加密 public string MD5Encrypt(string strText) */
/******************************************************************************************
* Cryptography class is for Cryptography
author:Jim
e_mail:[email protected]
* thanks:
* URI:
*
*
*****************************************************************************************/
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Windows.Forms ; namespace Netbee.Classes.Security
{
/// <summary>
///Cryptography
/// </summary>
public class Cryptography
{
public Cryptography()
{ }
/// <summary>
/// Encrypt the string
/// Attention:key must be 8 bits
/// </summary>
/// <param name="strText">string</param>
/// <param name="strEncrKey">key</param>
/// <returns></returns>
public string DesEncrypt(string strText, string strEncrKey)
{
byte[] byKey=null;
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0,8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write) ;
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch(System.Exception error)
{
MessageBox.Show(error.Message);
return "error:" +error.Message+"\r";
}
}
/// <summary>
/// Decrypt string
/// Attention:key must be 8 bits
/// </summary>
/// <param name="strText">Decrypt string</param>
/// <param name="sDecrKey">key</param>
/// <returns>output string</returns>
public string DesDecrypt(string strText,string sDecrKey)
{
byte[] byKey = null;
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
byte[] inputByteArray = new Byte[strText.Length];
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0,8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetString(ms.ToArray());
}
catch(System.Exception error)
{
MessageBox.Show(error.Message);
return "error:"+error.Message+"\r";
}
}
/// <summary>
/// Encrypt files
/// Attention:key must be 8 bits
/// </summary>
/// <param name="m_InFilePath">Encrypt file path</param>
/// <param name="m_OutFilePath">output file</param>
/// <param name="strEncrKey">key</param>
public void DesEncrypt(string m_InFilePath,string m_OutFilePath,string strEncrKey)
{
byte[] byKey=null;
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0,8));
FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time. DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
//Read from the input file, then encrypt and write to the output file.
while(rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
} encStream.Close();
fout.Close();
fin.Close();
}
catch(System.Exception error)
{
MessageBox.Show(error.Message.ToString()); }
}
/// <summary>
/// Decrypt files
/// Attention:key must be 8 bits
/// </summary>
/// <param name="m_InFilePath">Decrypt filepath</param>
/// <param name="m_OutFilePath">output filepath</param>
/// <param name="sDecrKey">key</param>
public void DesDecrypt(string m_InFilePath,string m_OutFilePath,string sDecrKey)
{
byte[] byKey = null;
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0,8));
FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time. DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
//Read from the input file, then encrypt and write to the output file.
while(rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
} encStream.Close();
fout.Close();
fin.Close(); }
catch(System.Exception error)
{
MessageBox.Show( "error:"+error.Message);
}
}
/// <summary>
/// MD5 Encrypt
/// </summary>
/// <param name="strText">text</param>
/// <returns>md5 Encrypt string</returns>
public string MD5Encrypt(string strText)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));
return System.Text.Encoding.Default.GetString(result);
}
}
}
{
class TextFileCrypt
{
public static void Main(string[] args)
{
string file = args[0];
string tempfile = Path.GetTempFileName();
//打开指定的文件
FileStream fsIn = File.Open(file,FileMode.Open,
FileAccess.Read);
FileStream fsOut = File.Open(tempfile, FileMode.Open,
FileAccess.Write);
//定义对称算法对象实例和接口
SymmetricAlgorithm symm = new RijndaelManaged();
ICryptoTransform transform = symm.CreateEncryptor();
CryptoStream cstream = new CryptoStream(fsOut,transform,
ryptoStreamMode.Write);BinaryReader br = new BinaryReader(fsIn);
// 读取源文件到cryptostream
cstream.Write(br.ReadBytes((int)fsIn.Length),0,(int)fsIn.Length);
cstream.FlushFinalBlock();
cstream.Close();
fsIn.Close();
fsOut.Close();Console.WriteLine("created encrypted file {0}", tempfile);
Console.WriteLine("will now decrypt and show contents");// 反向操作--解密刚才加密的临时文件
fsIn = File.Open(tempfile,FileMode.Open,FileAccess.Read);
transform = symm.CreateDecryptor();
cstream = new CryptoStream(fsIn,transform,
CryptoStreamMode.Read);StreamReader sr = new StreamReader(cstream);
Console.WriteLine("decrypted file text: " + sr.ReadToEnd());
fsIn.Close();
}
}
}
示例是一个TCP程序,分为服务器端和客户端。服务器端的工作流程是: 从客户端接收公共密钥。 使用公共密钥加密未来使用的对称密钥。 将加密了的对称密钥发送给客户端。 给客户端发送使用该对称密钥加密的信息。 代码如下:
namespace com.billdawson.crypto
{
public class CryptoServer
{
private const int RSA_KEY_SIZE_BITS = 1024;
private const int RSA_KEY_SIZE_BYTES = 252;
private const int TDES_KEY_SIZE_BITS = 192;public static void Main(string[] args)
{
int port;
string msg;
TcpListener listener;
TcpClient client;
SymmetricAlgorithm symm;
RSACryptoServiceProvider rsa;
//获取端口
try
{
port = Int32.Parse(args[0]);
msg = args[1];
}
catch
{
Console.WriteLine(USAGE);
return;
}
//建立监听
try
{
listener = new TcpListener(port);
listener.Start();
Console.WriteLine("Listening on port {0}...",port);client = listener.AcceptTcpClient();
Console.WriteLine("connection....");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return;
}try
{
rsa = new RSACryptoServiceProvider();
rsa.KeySize = RSA_KEY_SIZE_BITS;// 获取客户端公共密钥
rsa.ImportParameters(getClientPublicKey(client));symm = new TripleDESCryptoServiceProvider();
symm.KeySize = TDES_KEY_SIZE_BITS;//使用客户端的公共密钥加密对称密钥并发送给客。
encryptAndSendSymmetricKey(client, rsa, symm);//使用对称密钥加密信息并发送
encryptAndSendSecretMessage(client, symm, msg);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
finally
{
try
{
client.Close();
listener.Stop();
}
catch
{
//错误
}
Console.WriteLine("Server exiting...");
}
}private static RSAParameters getClientPublicKey(TcpClient client)
{
// 从字节流获取串行化的公共密钥,通过串并转换写入类的实例
byte[] buffer = new byte[RSA_KEY_SIZE_BYTES];
NetworkStream ns = client.GetStream();
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
RSAParameters result;int len = 0;
int totalLen = 0;while(totalLen (len = ns.Read(buffer,0,buffer.Length))>0)
{
totalLen+=len;
ms.Write(buffer, 0, len);
}ms.Position=0; result = (RSAParameters)bf.Deserialize(ms);
ms.Close();return result;}private static void encryptAndSendSymmetricKey(
TcpClient client,
RSACryptoServiceProvider rsa,
SymmetricAlgorithm symm)
{
// 使用客户端的公共密钥加密对称密钥
byte[] symKeyEncrypted;
byte[] symIVEncrypted;NetworkStream ns = client.GetStream();symKeyEncrypted = rsa.Encrypt(symm.Key, false);
symIVEncrypted = rsa.Encrypt(symm.IV, false);ns.Write(symKeyEncrypted, 0, symKeyEncrypted.Length);
ns.Write(symIVEncrypted, 0, symIVEncrypted.Length); }private static void encryptAndSendSecretMessage(TcpClient client,
SymmetricAlgorithm symm,
string secretMsg)
{
// 使用对称密钥和初始化矢量加密信息并发送给客户端
byte[] msgAsBytes;
NetworkStream ns = client.GetStream();
ICryptoTransform transform =
symm.CreateEncryptor(symm.Key,symm.IV);
CryptoStream cstream =
new CryptoStream(ns, transform, CryptoStreamMode.Write);msgAsBytes = Encoding.ASCII.GetBytes(secretMsg);cstream.Write(msgAsBytes, 0, msgAsBytes.Length);
cstream.FlushFinalBlock();
}
}
客户端的工作流程是: 建立和发送公共密钥给服务器。 从服务器接收被加密的对称密钥。 解密该对称密钥并将它作为私有的不对称密钥。 接收并使用不对称密钥解密信息。 代码如下:
{
public class CryptoClient
{
private const int RSA_KEY_SIZE_BITS = 1024;
private const int RSA_KEY_SIZE_BYTES = 252;
private const int TDES_KEY_SIZE_BITS = 192;
private const int TDES_KEY_SIZE_BYTES = 128;
private const int TDES_IV_SIZE_BYTES = 128;
public static void Main(string[] args)
{
int port;
string host;
TcpClient client;
SymmetricAlgorithm symm;
RSACryptoServiceProvider rsa;if (args.Length!=2)
{
Console.WriteLine(USAGE);
return;
}try
{
host = args[0];
port = Int32.Parse(args[1]);
}
catch
{
Console.WriteLine(USAGE);
return;
}try //连接
{
client = new TcpClient();
client.Connect(host,port);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.Write(e.StackTrace);
return;
}try
{
Console.WriteLine("Connected. Sending public key.");
rsa = new RSACryptoServiceProvider();
rsa.KeySize = RSA_KEY_SIZE_BITS;
sendPublicKey(rsa.ExportParameters(false),client);
symm = new TripleDESCryptoServiceProvider();
symm.KeySize = TDES_KEY_SIZE_BITS;MemoryStream ms = getRestOfMessage(client);
extractSymmetricKeyInfo(rsa, symm, ms);
showSecretMessage(symm, ms);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.Write(e.StackTrace);
}
finally
{
try
{
client.Close();
}
catch { //错误
}
}
}private static void sendPublicKey(
RSAParameters key,
TcpClient client)
{
NetworkStream ns = client.GetStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ns,key);
}private static MemoryStream getRestOfMessage(TcpClient client)
{
//获取加密的对称密钥、初始化矢量、秘密信息。对称密钥用公共RSA密钥
//加密,秘密信息用对称密钥加密
MemoryStream ms = new MemoryStream();
NetworkStream ns = client.GetStream();
byte[] buffer = new byte[1024];int len=0;// 将NetStream 的数据写入内存流
while((len = ns.Read(buffer, 0, buffer.Length))>0)
{
ms.Write(buffer, 0, len);
}
ms.Position = 0;
return ms;
}private static void extractSymmetricKeyInfo(
RSACryptoServiceProvider rsa,
SymmetricAlgorithm symm,
MemoryStream msOrig)
{
MemoryStream ms = new MemoryStream();// 获取TDES密钥--它被公共RSA密钥加密,使用私有密钥解密
byte[] buffer = new byte[TDES_KEY_SIZE_BYTES];
msOrig.Read(buffer,0,buffer.Length);
symm.Key = rsa.Decrypt(buffer,false);// 获取TDES初始化矢量
buffer = new byte[TDES_IV_SIZE_BYTES];
msOrig.Read(buffer, 0, buffer.Length);
symm.IV = rsa.Decrypt(buffer,false);
}private static void showSecretMessage(
SymmetricAlgorithm symm,
MemoryStream msOrig)
{
//内存流中的所有数据都被加密了
byte[] buffer = new byte[1024];
int len = msOrig.Read(buffer,0,buffer.Length);MemoryStream ms = new MemoryStream();
ICryptoTransform transform =
symm.CreateDecryptor(symm.Key,symm.IV);
CryptoStream cstream =new CryptoStream(ms, transform,
CryptoStreamMode.Write);
cstream.Write(buffer, 0, len);
cstream.FlushFinalBlock();// 内存流现在是解密信息,是字节的形式,将它转换为字符串
ms.Position = 0;
len = ms.Read(buffer,0,(int) ms.Length);
ms.Close();string msg = Encoding.ASCII.GetString(buffer,0,len);
Console.WriteLine("The host sent me this secret message:");
Console.WriteLine(msg);
}
}
}
http://www.icsharpcode.net/OpenSource/SharpZipLib/Default.aspx