您的位置:首页 > 编程语言 > C#

C# 算法加密解密

2013-09-22 21:07 507 查看
不用想,没错,我就是用C++做客户端,用C#做服务端的,所以,服务端一样得有RC4的算法实现。

这次的RC4有个基类CryptoBase,这个基类,是为了为多种加密算法提供统一接口而设计的,我这里实现了RC4、DES、RSA三种算法。和C++中一样,C#这里也要有一个十六进制字符串转换函数来编码解码。

经过测试,客户端C++的RC4能够很好的和服务端C#中的RC4结合工作,也就是说,一端加密的数据,另一端完全可以解密。很遗憾,实在找不到能和C#中的RSA算法对应的C++实现的RSA算法,希望得到高人指点……

代码文件有两个:

CryptoBase.cs文件:

以下是代码片段:

using System;

using System.Collections.Generic;

using System.Text;

namespace NewLife.Cryptography

{

/// <summary>

/// 加密类基类

/// </summary>

public class CryptoBase

{

/// <summary>

/// 编码转换器,用于字节码和字符串之间的转换,默认为本机编码

/// </summary>

static public Encoding Encode = Encoding.Default;

public enum EncoderMode { Base64Encoder, HexEncoder };

/// <summary>

/// 带编码模式的字符串加密

/// </summary>

/// <param name="data">要加密的数据</param>

/// <param name="pass">密码</param>

/// <param name="em">编码模式</param>

/// <returns>加密后经过编码的字符串</returns>

public String Encrypt(String data, String pass, CryptoBase.EncoderMode em)

{

if (data == null || pass == null) return null;

if (em == EncoderMode.Base64Encoder)

return Convert.ToBase64String(EncryptEx(Encode.GetBytes(data), pass));

else

return ByteToHex(EncryptEx(Encode.GetBytes(data), pass));

}

/// <summary>

/// 带编码模式的字符串解密

/// </summary>

/// <param name="data">要解密的数据</param>

/// <param name="pass">密码</param>

/// <param name="em">编码模式</param>

/// <returns>明文</returns>

public String Decrypt(String data, String pass, CryptoBase.EncoderMode em)

{

if (data == null || pass == null) return null;

if (em == EncoderMode.Base64Encoder)

return Encode.GetString(DecryptEx(Convert.FromBase64String(data), pass));

else

return Encode.GetString(DecryptEx(HexToByte(data), pass));

}

/// <summary>

/// 加密

/// </summary>

/// <param name="data">要加密的数据</param>

/// <param name="pass">密码</param>

/// <returns>加密后经过默认编码的字符串</returns>

public String Encrypt(String data, String pass)

{

return Encrypt(data, pass, EncoderMode.Base64Encoder);

}

/// <summary>

/// 解密

/// </summary>

/// <param name="data">要解密的经过编码的数据</param>

/// <param name="pass">密码</param>

/// <returns>明文</returns>

public String Decrypt(String data, String pass)

{

return Decrypt(data, pass, EncoderMode.Base64Encoder);

}

/// <summary>

/// 加密

/// </summary>

/// <param name="data">要加密的数据</param>

/// <param name="pass">密钥</param>

/// <returns>密文</returns>

virtual public Byte[] EncryptEx(Byte[] data, String pass) { return null; }

/// <summary>

/// 解密

/// </summary>

/// <param name="data">要解密的数据</param>

/// <param name="pass">密码</param>

/// <returns>明文</returns>

virtual public Byte[] DecryptEx(Byte[] data, String pass) { return null; }

static public Byte[] HexToByte(String szHex)

{

// 两个十六进制代表一个字节

Int32 iLen = szHex.Length;

if (iLen <= 0 || 0 != iLen % 2)

{

return null;

}

Int32 dwCount = iLen / 2;

UInt32 tmp1, tmp2;

20000
Byte[] pbBuffer = new Byte[dwCount];

for (Int32 i = 0; i < dwCount; i++)

{

tmp1 = (UInt32)szHex[i * 2] - (((UInt32)szHex[i * 2] >= (UInt32)'A') ? (UInt32)'A' - 10 : (UInt32)'0');

if (tmp1 >= 16) return null;

tmp2 = (UInt32)szHex[i * 2 + 1] - (((UInt32)szHex[i * 2 + 1] >= (UInt32)'A') ? (UInt32)'A' - 10 : (UInt32)'0');

if (tmp2 >= 16) return null;

pbBuffer[i] = (Byte)(tmp1 * 16 + tmp2);

}

return pbBuffer;

}

static public String ByteToHex(Byte[] vByte)

{

if (vByte == null || vByte.Length < 1) return null;

StringBuilder sb = new StringBuilder(vByte.Length * 2);

for (int i = 0; i < vByte.Length; i++)

{

if ((UInt32)vByte[i] < 0) return null;

UInt32 k = (UInt32)vByte[i] / 16;

sb.Append((Char)(k + ((k > 9) ? 'A' - 10 : '0')));

k = (UInt32)vByte[i] % 16;

sb.Append((Char)(k + ((k > 9) ? 'A' - 10 : '0')));

}

return sb.ToString();

}

}

interface ICrypto

{

/// <summary>

/// 加密

/// </summary>

/// <param name="data">要加密的数据</param>

/// <param name="pass">密钥</param>

/// <returns>密文</returns>

Byte[] EncryptEx(Byte[] data, String pass);

/// <summary>

/// 解密

/// </summary>

/// <param name="data">要解密的数据</param>

/// <param name="pass">密码</param>

/// <returns>明文</returns>

Byte[] DecryptEx(Byte[] data, String pass);

}

}

RC4.cs文件:

以下是代码片段:

using System;

using System.Collections.Generic;

using System.Text;

namespace NewLife.Cryptography

{

public class RC4Crypto : CryptoBase

{

static public RC4Crypto RC4 = new RC4Crypto();

public override Byte[] EncryptEx(Byte[] data, String pass)

{

if (data == null || pass == null) return null;

Byte[] output = new Byte[data.Length];

Int64 i = 0;

Int64 j = 0;

Byte[] mBox = GetKey(Encode.GetBytes(pass), 256);

// 加密

for (Int64 offset = 0; offset < data.Length; offset++)

{

i = (i + 1) % mBox.Length;

j = (j + mBox[i]) % mBox.Length;

Byte temp = mBox[i];

mBox[i] = mBox[j];

mBox[j] = temp;

Byte a = data[offset];

//Byte b = mBox[(mBox[i] + mBox[j] % mBox.Length) % mBox.Length];

// mBox[j] 一定比 mBox.Length 小,不需要在取模

Byte b = mBox[(mBox[i] + mBox[j]) % mBox.Length];

output[offset] = (Byte)((Int32)a ^ (Int32)b);

}

return output;

}

public override Byte[] DecryptEx(Byte[] data, String pass)

{

return EncryptEx(data, pass);

}

/// <summary>

/// 打乱密码

/// </summary>

/// <param name="pass">密码</param>

/// <param name="kLen">密码箱长度</param>

/// <returns>打乱后的密码</returns>

static private Byte[] GetKey(Byte[] pass, Int32 kLen)

{

Byte[] mBox = new Byte[kLen];

for (Int64 i = 0; i < kLen; i++)

{

mBox[i] = (Byte)i;

}

Int64 j = 0;

for (Int64 i = 0; i < kLen; i++)

{

j = (j + mBox[i] + pass[i % pass.Length]) % kLen;

Byte temp = mBox[i];

mBox[i] = mBox[j];

mBox[j] = temp;

}

return mBox;

}

}

}

其它

1 、方法一 (不可逆加密)












public string EncryptPassword( string PasswordString, string PasswordFormat )


{


string encryptPassword = null ;


if (PasswordFormat = " SHA1 " ) {


encryptPassword = FormsAuthortication.HashPasswordForStoringInConfigFile(PasswordString




, " SHA1 " );


}


elseif (PasswordFormat = " MD5 " )


{ encryptPassword = FormsAuthortication.HashPasswordForStoringInConfigFile(PasswordString




, " MD5 " );


}


return encryptPassword ;


}






2 、方法二 (可逆加密)








public interface IBindesh


{


string encode( string str);


string decode( string str);


}




public class EncryptionDecryption : IBindesh


{


public string encode( string str)


{


string htext = "" ;




for ( int i = 0 ; i < str.Length; i ++ )


{


htext = htext + ( char ) (str[i] + 10 - 1 * 2 );


}


return htext;


}




public string decode( string str)


{


string dtext = "" ;




for ( int i = 0 ; i < str.Length; i ++ )


{


dtext = dtext + ( char ) (str[i] - 10 + 1 * 2 );


}


return dtext;


}








3 、方法三 (可逆加密)










const string KEY_64 = " VavicApp " ; // 注意了,是8个字符,64位




const string IV_64 = " VavicApp " ;


public string Encode( string data)


{


byte [] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);


byte [] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);




DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();


int i = cryptoProvider.KeySize;


MemoryStream ms = new MemoryStream();


CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey,




byIV), CryptoStreamMode.Write);




StreamWriter sw = new StreamWriter(cst);


sw.Write(data);


sw.Flush();


cst.FlushFinalBlock();


sw.Flush();


return Convert.ToBase64String(ms.GetBuffer(), 0 , ( int )ms.Length);




}




public string Decode( string data)


{


byte [] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);


byte [] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);




byte [] byEnc;


try


{


byEnc = Convert.FromBase64String(data);


}


catch


{


return null ;


}




DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();


MemoryStream ms = new MemoryStream(byEnc);


CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey,




byIV), CryptoStreamMode.Read);


StreamReader sr = new StreamReader(cst);


return sr.ReadToEnd();


}






4 、MD5不可逆加密




(32位加密)




public string GetMD5( string s, string _input_charset)


{




/**/ /// <summary>


/// 与ASP兼容的MD5加密算法


/// </summary>




MD5 md5 = new MD5CryptoServiceProvider();


byte [] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));


StringBuilder sb = new StringBuilder( 32 );


for ( int i = 0 ; i < t.Length; i ++ )


{


sb.Append(t[i].ToString( " x " ).PadLeft( 2 , ' 0 '));


}


return sb.ToString();


}


(16位加密)








public static string GetMd5Str( string ConvertString)


{


MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();


string t2 =




BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4 , 8 );


t2 = t2.Replace( " - " , "" );


return t2;


}






5 、加解文本文件








// 加密文件


private static void EncryptData(String inName, String outName, byte [] desKey, byte []




desIV)


{


// Create the file streams to handle the input and output files.


FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);


FileStream fout = new FileStream(outName, 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(desKey, desIV),




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();


}




// 解密文件


private static void DecryptData(String inName, String outName, byte [] desKey, byte []




desIV)


{


// Create the file streams to handle the input and output files.


FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);


FileStream fout = new FileStream(outName, 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(desKey, desIV),




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();


}






6 、




using System;


using System.Collections.Generic;


using System.Text;


using System.Security.Cryptography;


using System.IO;




namespace Component


{


public class Security


{


public Security()


{




}




// 默认密钥向量


private static byte [] Keys = { 0x12 , 0x34 , 0x56 , 0x78 , 0x90 , 0xAB , 0xCD , 0xEF } ;


/**/ /**/ /**/ /// <summary>


/// DES加密字符串


/// </summary>


/// <param name="encryptString"> 待加密的字符串 </param>


/// <param name="encryptKey"> 加密密钥,要求为8位 </param>


/// <returns> 加密成功返回加密后的字符串,失败返回源串 </returns>


public static string EncryptDES( string encryptString, string encryptKey)


{


try


{


byte [] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring( 0 , 8 ));


byte [] rgbIV = Keys;


byte [] inputByteArray = Encoding.UTF8.GetBytes(encryptString);


DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();


MemoryStream mStream = new MemoryStream();


CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey,




rgbIV), CryptoStreamMode.Write);


cStream.Write(inputByteArray, 0 , inputByteArray.Length);


cStream.FlushFinalBlock();


return Convert.ToBase64String(mStream.ToArray());


}


catch


{


return encryptString;


}


}




/**/ /**/ /**/ /// <summary>


/// DES解密字符串


/// </summary>


/// <param name="decryptString"> 待解密的字符串 </param>


/// <param name="decryptKey"> 解密密钥,要求为8位,和加密密钥相同 </param>


/// <returns> 解密成功返回解密后的字符串,失败返源串 </returns>


public static string DecryptDES( string decryptString, string decryptKey)


{


try


{


byte [] rgbKey = Encoding.UTF8.GetBytes(decryptKey);


byte [] rgbIV = Keys;


byte [] inputByteArray = Convert.FromBase64String(decryptString);


DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();


MemoryStream mStream = new MemoryStream();


CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey,




rgbIV), CryptoStreamMode.Write);


cStream.Write(inputByteArray, 0 , inputByteArray.Length);


cStream.FlushFinalBlock();


return Encoding.UTF8.GetString(mStream.ToArray());


}


catch


{


return decryptString;


}


}






}


}


C# DES 加密解密类


// 名称空间


using System;


using System.Security.Cryptography;


using System.IO;


using System.Text;




// 方法


// 加密方法


public string Encrypt( string pToEncrypt, string sKey)


{


DESCryptoServiceProvider des = new DESCryptoServiceProvider();


// 把字符串放到byte数组中


// 原来使用的UTF8编码,我改成Unicode编码了,不行


byte [] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);


// byte[] inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt);




// 建立加密对象的密钥和偏移量


// 原文使用ASCIIEncoding.ASCII方法的GetBytes方法


// 使得输入密码必须输入英文文本


des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);


des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);


MemoryStream ms = new MemoryStream();


CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(),CryptoStreamMode.Write);


// Write the byte array into the crypto stream


// (It will end up in the memory stream)


cs.Write(inputByteArray, 0 , inputByteArray.Length);


cs.FlushFinalBlock();


// Get the data back from the memory stream, and into a string


StringBuilder ret = new StringBuilder();


foreach ( byte b in ms.ToArray())


{


// Format as hex


ret.AppendFormat( " {0:X2} " , b);


}


ret.ToString();


return ret.ToString();


}




// 解密方法


public string Decrypt( string pToDecrypt, string sKey)


{


DESCryptoServiceProvider des = new DESCryptoServiceProvider();




// Put the input string into the byte array


byte [] inputByteArray = new byte [pToDecrypt.Length / 2 ];


for ( int x = 0 ; x < pToDecrypt.Length / 2 ; x ++ )


{


int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2 , 2 ), 16 ));


inputByteArray[x] = ( byte )i;


}




// 建立加密对象的密钥和偏移量,此值重要,不能修改


des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);


des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);


MemoryStream ms = new MemoryStream();


CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(),CryptoStreamMode.Write);


// Flush the data through the crypto stream into the memory stream


cs.Write(inputByteArray, 0 , inputByteArray.Length);


cs.FlushFinalBlock();




// Get the decrypted data back from the memory stream


// 建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象


StringBuilder ret = new StringBuilder();




return System.Text.Encoding.Default.GetString(ms.ToArray());


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: