谁能帮我写几个最常见的加密解密,以供学习

我在深圳搬砖-Justin 2009-05-05 02:45:41
RT...
...全文
158 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zzxap 2009-05-05
  • 打赏
  • 举报
回复
[code=C#]
DES是Data Encryption Standard(数据加密标准)的缩写。它是由IBM公司研制的一种加密算法,美国国家标准局于1977年公布把它作为非机要部门使用的数据加密标准;它是一个分组加密算法,他以64位为分组对数据加密。同时DES也是一个对称算法:加密和解密用的是同一个算法。它的密匙长度是56位(因为每个第8 位都用作奇偶校验),密匙可以是任意的56位的数,而且可以任意时候改变.

/// <summary>
/// DES加密
/// </summary>
/// <param name="Data">被加密的明文</param>
/// <param name="Key">密钥</param>
/// <param name="Vector">向量</param>
/// <returns>密文</returns>
public static Byte[] DESEncrypt(Byte[] Data, String Key, String Vector)
{
Byte[] bKey = new Byte[8];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
Byte[] bVector = new Byte[8];
Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

Byte[] Cryptograph = null; // 加密后的密文

DESCryptoServiceProvider EncryptProvider = new DESCryptoServiceProvider();
EncryptProvider.Mode = CipherMode.CBC;
EncryptProvider.Padding = PaddingMode.Zeros;

try
{
// 开辟一块内存流
using (MemoryStream Memory = new MemoryStream())
{
// 把内存流对象包装成加密流对象
using (CryptoStream Encryptor = new CryptoStream(Memory,
EncryptProvider.CreateEncryptor(bKey, bVector),
CryptoStreamMode.Write))
{
// 明文数据写入加密流
Encryptor.Write(Data, 0, Data.Length);
Encryptor.FlushFinalBlock();

Cryptograph = Memory.ToArray();
}
}
}
catch
{
Cryptograph = null;
}

return Cryptograph;
}

/// <summary>
/// DES解密
/// </summary>
/// <param name="Data">被解密的密文</param>
/// <param name="Key">密钥</param>
/// <param name="Vector">向量</param>
/// <returns>明文</returns>
public static Byte[] DESDecrypt(Byte[] Data, String Key, String Vector)
{
Byte[] bKey = new Byte[8];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
Byte[] bVector = new Byte[8];
Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

Byte[] original = null;

DESCryptoServiceProvider CryptoProvider = new DESCryptoServiceProvider();
CryptoProvider.Mode = CipherMode.CBC;
CryptoProvider.Padding = PaddingMode.Zeros;

try
{
// 开辟一块内存流,存储密文
using (MemoryStream Memory = new MemoryStream(Data))
{
// 把内存流对象包装成加密流对象
using (CryptoStream Decryptor = new CryptoStream(Memory,
CryptoProvider.CreateDecryptor(bKey, bVector),
CryptoStreamMode.Read))
{
// 明文存储区
using (MemoryStream originalMemory = new MemoryStream())
{
Byte[] Buffer = new Byte[1024];
Int32 readBytes = 0;
while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
{
originalMemory.Write(Buffer, 0, readBytes);
}

original = originalMemory.ToArray();
}
}
}
}
catch
{
original = null;
}

return original;
}





AES算法描述简介:

DES数据加密标准算法由于密钥长度较小(56位),已经不适应当今分布式开放网络对数据加密安全性的要求,因此1997年NIST公开征集新的数据加密标准,即AES。经过三轮的筛选,比利时Joan Daeman和Vincent Rijmen提交的Rijndael算法被提议为AES的最终算法。此算法将成为美国新的数据加密标准而被广泛应用在各个领域中。尽管人们对AES还有不同的看法,但总体来说,AES作为新一代的数据加密标准汇聚了强安全性、高性能、高效率、易用和灵活等优点。AES设计有三个密钥长度:128,192,256位,相对而言,AES的128密钥比DES的56密钥强1021倍。

/// <summary>
/// AES加密
/// </summary>
/// <param name="Data">被加密的明文</param>
/// <param name="Key">密钥</param>
/// <param name="Vector">向量</param>
/// <returns>密文</returns>
public static Byte[] AESEncrypt(Byte[] Data, String Key, String Vector)
{
Byte[] bKey = new Byte[32];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
Byte[] bVector = new Byte[16];
Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

Byte[] Cryptograph = null; // 加密后的密文

Rijndael Aes = Rijndael.Create();
try
{
// 开辟一块内存流
using (MemoryStream Memory = new MemoryStream())
{
// 把内存流对象包装成加密流对象
using (CryptoStream Encryptor = new CryptoStream(Memory,
Aes.CreateEncryptor(bKey, bVector),
CryptoStreamMode.Write))
{
// 明文数据写入加密流
Encryptor.Write(Data, 0, Data.Length);
Encryptor.FlushFinalBlock();

Cryptograph = Memory.ToArray();
}
}
}
catch
{
Cryptograph = null;
}

return Cryptograph;
}

/// <summary>
/// AES解密
/// </summary>
/// <param name="Data">被解密的密文</param>
/// <param name="Key">密钥</param>
/// <param name="Vector">向量</param>
/// <returns>明文</returns>
public static Byte[] AESDecrypt(Byte[] Data, String Key, String Vector)
{
Byte[] bKey = new Byte[32];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
Byte[] bVector = new Byte[16];
Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

Byte[] original = null; // 解密后的明文

Rijndael Aes = Rijndael.Create();
try
{
// 开辟一块内存流,存储密文
using (MemoryStream Memory = new MemoryStream(Data))
{
// 把内存流对象包装成加密流对象
using (CryptoStream Decryptor = new CryptoStream(Memory,
Aes.CreateDecryptor(bKey, bVector),
CryptoStreamMode.Read))
{
// 明文存储区
using (MemoryStream originalMemory = new MemoryStream())
{
Byte[] Buffer = new Byte[1024];
Int32 readBytes = 0;
while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
{
originalMemory.Write(Buffer, 0, readBytes);
}

original = originalMemory.ToArray();
}
}
}
}
catch
{
original = null;
}

return original;
}
[/CODE]
mjjzg 2009-05-05
  • 打赏
  • 举报
回复
SHA

public static string SHA1Encrypt(string source)
{
//格式化目标字符串
byte[] sourcebytes = ASCIIEncoding.ASCII.GetBytes(source);
byte[] SHA1bytes = null;
//声明SHA-1加密算法类对象
SHA1Managed SHA1 = new SHA1Managed();
//将格式化后目标字节数组加密
SHA1bytes = SHA1.ComputeHash(sourcebytes);
string strSHA1 = "";
//遍历数组中的元素,若位数不足则按照64进制进行补位
for (int i = 0; i < SHA1bytes.Length; i++)
{
if (SHA1bytes[i] <= 15)
{
strSHA1 += ("0" + SHA1bytes[i].ToString("X"));
}
else
{
strSHA1 += SHA1bytes[i].ToString("X");
}
}
//释放内存中的对象
sourcebytes = null;
SHA1bytes = null;
SHA1.Clear();
return strSHA1;

}

public static string SHA256Encrypt(string source)
{
//格式化目标字符串
byte[] sourcebytes = ASCIIEncoding.ASCII.GetBytes(source);
byte[] SHA256bytes = null;
//声明SHA-1加密算法类对象
SHA256Managed SHA256 = new SHA256Managed();
//将格式化后目标字节数组加密
SHA256bytes = SHA256.ComputeHash(sourcebytes);
string strSHA256 = "";
//遍历数组中的元素,若位数不足则按照64进制进行补位
for (int i = 0; i < SHA256bytes.Length; i++)
{
if (SHA256bytes[i] <= 15)
{
strSHA256 += ("0" + SHA256bytes[i].ToString("X"));
}
else
{
strSHA256 += SHA256bytes[i].ToString("X");
}
}
//释放内存中的对象
sourcebytes = null;
SHA256bytes = null;
SHA256.Clear();
return strSHA256;
}

public static string SHA512Encrypt(string source)
{
//格式化目标字符串
byte[] sourcebytes = ASCIIEncoding.ASCII.GetBytes(source);
byte[] SHA512bytes = null;
//声明SHA-1加密算法类对象
SHA512Managed SHA512 = new SHA512Managed();
//将格式化后目标字节数组加密
SHA512bytes = SHA512.ComputeHash(sourcebytes);
string strSHA512 = "";
//遍历数组中的元素,若位数不足则按照64进制进行补位
for (int i = 0; i < SHA512bytes.Length; i++)
{
if (SHA512bytes[i] <= 15)
{
strSHA512 += ("0" + SHA512bytes[i].ToString("X"));
}
else
{
strSHA512 += SHA512bytes[i].ToString("X");
}
}
//释放内存中的对象
sourcebytes = null;
SHA512bytes = null;
SHA512.Clear();
return strSHA512;
}


mjjzg 2009-05-05
  • 打赏
  • 举报
回复
RSA

/// <summary>
/// RSA加密算法产生私钥和公钥
/// </summary>
/// <param name="xmlKeys">XML格式私钥</param>
/// <param name="xmlPublicKey">XML格式公钥</param>
public void RSAKey(out string xmlKeys, out string xmlPublicKey)
{
try
{
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
//私钥
xmlKeys = rsa.ToXmlString(true);
//公钥
xmlPublicKey = rsa.ToXmlString(false);
}
catch (Exception ex)
{
throw ex;
}
}
//##############################################################################
//RSA 方式加密
//说明KEY必须是XML的行式,返回的是字符串
//在有一点需要说明!!该加密方式有 长度 限制的!!
//##############################################################################

//RSA的加密函数
public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
{
try
{
byte[] PlainTextBArray;
byte[] CypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
PlainTextBArray = UnicodeEncoding.Unicode.GetBytes(m_strEncryptString);//(new UnicodeEncoding()).GetBytes(m_strEncryptString);
CypherTextBArray = rsa.Encrypt(PlainTextBArray,false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}

mjjzg 2009-05-05
  • 打赏
  • 举报
回复
MD5

public static string GetMd5HashString(string source)
{
//格式化目标字符串
byte[] sourcebytes = ASCIIEncoding.ASCII.GetBytes(source);
byte[] MD5bytes = null;
//声明MD5加密类对象
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
//生成MD5加密数组
MD5bytes = md5.ComputeHash(sourcebytes);
string strMd5 = "";
//遍历数组中的元素,若位数不足则按照十六进制进行补位
for (int i = 0; i < MD5bytes.Length; i++)
{
if (MD5bytes[i] <= 15)
{
strMd5 += ("0" + MD5bytes[i].ToString("X"));
}
else
{
strMd5 += MD5bytes[i].ToString("X");
}
}
//释放内存中保存的对象
sourcebytes = null;
MD5bytes = null;
md5.Clear();
return strMd5;


}
mjjzg 2009-05-05
  • 打赏
  • 举报
回复
DES

public string DesEncrypt(string strText, string strEncrKey)//加密函数
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byKey = UnicodeEncoding.Unicode.GetBytes(strEncrKey.Substring(0, strEncrKey.Length));
//for (int i = 0; i < 8; i++)
//{
//des.Key[i] = byKey[i];
//}
//des.IV = IV;
byte[] inputByteArray = UnicodeEncoding.Unicode.GetBytes(strText);
MemoryStream ms = new MemoryStream(inputByteArray);
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey,IV), CryptoStreamMode.Write);
cs.Flush();
return Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.None);
//return Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(inputByteArray, 0, inputByteArray.Length));
}
catch (System.Exception error)
{
return "error:" + error.Message + "\r\n" + error.StackTrace;
}
}

public string DesEncrypt(string strText, byte[] Key)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = UnicodeEncoding.Unicode.GetBytes(strText);
byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
MemoryStream ms = new MemoryStream(inputByteArray);
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
cs.Flush();
return Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.None);
//return Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer,0,buffer.Length));
}
/// <summary>
/// 得到解密后字符串
/// </summary>
/// <param name="strText">解密字符串</param>
/// <param name="sDecrKey">密钥</param>
/// <returns>解密后字符串</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
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byKey = UnicodeEncoding.Unicode.GetBytes(sDecrKey.Substring(0, sDecrKey.Length));
for (int i = 0; i < 8; i++)
{
des.Key[i] = byKey[i];
}
des.IV = IV;
inputByteArray = Convert.FromBase64String(strText);
return UnicodeEncoding.Unicode.GetString(des.CreateDecryptor().TransformFinalBlock(inputByteArray, 0, inputByteArray.Length));
}
catch (System.Exception error)
{
return "error:" + error.Message + "\r\n" + error.StackTrace;
}

}

public string DesDecrypt(string strText, byte[] Key)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] buffer = Convert.FromBase64String(strText);
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
MemoryStream ms = new MemoryStream(buffer);
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(Key, IV), CryptoStreamMode.Write);
cs.Flush();
return UnicodeEncoding.Unicode.GetString(ms.ToArray());
//return UnicodeEncoding.Unicode.GetString(des.CreateDecryptor().TransformFinalBlock(buffer,0,buffer.Length));
}
cpio 2009-05-05
  • 打赏
  • 举报
回复
DES(Data Encryption Standard)加密解密整
--------------------------------------------------------------------------------
2004-04-20 23:05:41 rexsp

  这个类是我在网上参考了几个文档总结出来的,测试过可以直接用,后面有一段MD5的,应该独立成一个类的,我懒,所以测试的时候就写到一个文件里了,感觉还是满实用的,如果有什么机密文件,就用这个东西处理一下,将来要看的时候再反过来处理一下,只是你不要忘记了密码就对了,如果你跟我一样懒,你直接把下面的代码拷贝下来直接用吧。
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Web;


namespace Test.Com
{
/// <summary>
/// DESEncryptor 的摘要说明。
/// </summary>
public class DESEncryptor
{
#region 私有成员
/// <summary>
/// 输入字符串
/// </summary>
private string inputString=null;
/// <summary>
/// 输出字符串
/// </summary>
private string outString=null;
/// <summary>
/// 输入文件路径
/// </summary>
private string inputFilePath=null;
/// <summary>
/// 输出文件路径
/// </summary>
private string outFilePath=null;
/// <summary>
/// 加密密钥
/// </summary>
private string encryptKey=null;
/// <summary>
/// 解密密钥
/// </summary>
private string decryptKey=null;
/// <summary>
/// 提示信息
/// </summary>
private string noteMessage=null;
#endregion
#region 公共属性
/// <summary>
/// 输入字符串
/// </summary>
public string InputString
{
get{return inputString;}
set{inputString=value;}
}
/// <summary>
/// 输出字符串
/// </summary>
public string OutString
{
get{return outString;}
set{outString=value;}
}
/// <summary>
/// 输入文件路径
/// </summary>
public string InputFilePath
{
get{return inputFilePath;}
set{inputFilePath=value;}
}
/// <summary>
/// 输出文件路径
/// </summary>
public string OutFilePath
{
get{return outFilePath;}
set{outFilePath=value;}
}
/// <summary>
/// 加密密钥
/// </summary>
public string EncryptKey
{
get{return encryptKey;}
set{encryptKey=value;}
}
/// <summary>
/// 解密密钥
/// </summary>
public string DecryptKey
{
get{return decryptKey;}
set{decryptKey=value;}
}
/// <summary>
/// 错误信息
/// </summary>
public string NoteMessage
{
get{return noteMessage;}
set{noteMessage=value;}
}
#endregion
#region 构造函数
public DESEncryptor()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
#endregion
#region DES加密字符串
/// <summary>
/// 加密字符串
/// 注意:密钥必须为8位
/// </summary>
/// <param name="strText">字符串</param>
/// <param name="encryptKey">密钥</param>
public void DesEncrypt()
{
byte[] byKey=null;
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(this.encryptKey.Substring(0,8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(this.inputString);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write) ;
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
this.outString=Convert.ToBase64String(ms.ToArray());
}
catch(System.Exception error)
{
this.noteMessage=error.Message;
}
}
#endregion
#region DES解密字符串
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="this.inputString">加了密的字符串</param>
/// <param name="decryptKey">密钥</param>
public void DesDecrypt()
{
byte[] byKey = null;
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
byte[] inputByteArray = new Byte[this.inputString.Length];
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0,8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(this.inputString);
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();
this.outString=encoding.GetString(ms.ToArray());
}
catch(System.Exception error)
{
this.noteMessage=error.Message;
}
}
#endregion
#region DES加密文件
/// <summary>
/// DES加密文件
/// </summary>
/// <param name="this.inputFilePath">源文件路径</param>
/// <param name="this.outFilePath">输出文件路径</param>
/// <param name="encryptKey">密钥</param>
public void FileDesEncrypt()
{
byte[] byKey=null;
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(this.encryptKey.Substring(0,8));
FileStream fin = new FileStream(this.inputFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(this.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)
{
this.noteMessage=error.Message.ToString();

}
}
#endregion
#region DES解密文件
/// <summary>
/// 解密文件
/// </summary>
/// <param name="this.inputFilePath">加密了的文件路径</param>
/// <param name="this.outFilePath">输出文件路径</param>
/// <param name="decryptKey">密钥</param>
public void FileDesDecrypt()
{
byte[] byKey = null;
byte[] IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0,8));
FileStream fin = new FileStream(this.inputFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(this.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)
{
this.noteMessage=error.Message.ToString();
}
}
#endregion
#region MD5
/// <summary>
/// MD5 Encrypt
/// </summary>
/// <param name="strText">text</param>
/// <returns>md5 Encrypt string</returns>
public void MD5Encrypt()
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(this.inputString));
this.outString=System.Text.Encoding.Default.GetString(result);
}
#endregion

}
}
jmh521 2009-05-05
  • 打赏
  • 举报
回复
百度一下,很多的...不用在这儿浪费分..
cpio 2009-05-05
  • 打赏
  • 举报
回复
对称加密解密通用类库函数
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Common
{
/// <summary>
/// 加密解密通用类库函数
/// </summary>
public class Crypto
{
private string _CryptText; //待加密和解密的字符序列变量
private byte[] _CryptKey; //加密解密私钥变量
private byte[] _CryptIV; //加密解密初始化向量IV变量

/// <summary>
/// 待加密或解密的字符序列
/// </summary>
public string CryptText
{
set
{
_CryptText=value;
}
get
{
return _CryptText;
}
}

/// <summary>
/// 加密私钥
/// </summary>
public byte[] CryptKey
{
set
{
_CryptKey=value;
}
get
{
return _CryptKey;
}
}

/// <summary>
/// 加密的初始化向量IV
/// </summary>
public byte[] CryptIV
{
set
{
_CryptIV=value;
}
get
{
return _CryptIV;
}
}

public Crypto()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

/// <summary>
/// 加密函数,用于对字符串进行加密。需要提供相应的密钥和IV。
/// </summary>
/// <returns></returns>
public string Encrypt()
{
string strEnText=CryptText;
byte[] EnKey=CryptKey;
byte[] EnIV=CryptIV;

byte[] inputByteArray=System.Text.Encoding.UTF8.GetBytes(strEnText);

//此处也可以创建其他的解密类实例,但注意不同(长度)的加密类要求不同的密钥Key和初始化向量IV
RijndaelManaged RMCrypto = new RijndaelManaged();

MemoryStream ms=new MemoryStream();
CryptoStream cs=new CryptoStream(ms,RMCrypto.CreateEncryptor(EnKey,EnIV),CryptoStreamMode.Write);
cs.Write(inputByteArray,0,inputByteArray.Length);
cs.FlushFinalBlock();

return Convert.ToBase64String(ms.ToArray());
}

/// <summary>
/// 解密函数,用于经过加密的字符序列进行加密。需要提供相应的密钥和IV。
/// </summary>
/// <returns></returns>
public string Decrypt()
{
string strDeText=CryptText;
byte[] DeKey=CryptKey;
byte[] DeIV=CryptIV;

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

//此处也可以创建其他的解密类实例,但注意不同的加密类要求不同(长度)的密钥Key和初始化向量IV
RijndaelManaged RMCrypto = new RijndaelManaged();

MemoryStream ms=new MemoryStream();
CryptoStream cs=new CryptoStream(ms,RMCrypto.CreateDecryptor(DeKey,DeIV),CryptoStreamMode.Write);
cs.Write(inputByteArray,0,inputByteArray.Length);
cs.FlushFinalBlock();

return System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
}
}

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧