问:如何使用C#编写对数据库链接进行加密和解密的核心代码?
南京北大青鸟柴老师:这位同学的问题问的很好,因为如果直接把数据库连接字符串写在程序里远程数据库,那么将会非常的不安全,常常导致网站或软件被黑等情况
下面展示一下使用C#对数据库链接进行加密和解密的操作
首先我们需要一个工具类,示例代码如下
南京北大青鸟柴老师:这位同学的问题问的很好,因为如果直接把数据库连接字符串写在程序里远程数据库,那么将会非常的不安全,常常导致网站或软件被黑等情况
下面展示一下使用C#对数据库链接进行加密和解密的操作
首先我们需要一个工具类,示例代码如下
using System;
using System.IO;
using System.Security.Cryptography;
namespace CryptInfoNameSpace
{
class CryptInfo
{
//加密
public static string Encrypt(string text)
{
Rijndael crypt=Rijndael.Create();
byte[] key=new byte[32]{0XA6,0X7D,0XE1,0X3F,0X35,0X0E,0XE1,0XA9,0X83,0XA5,0X62,0XAA,0X7A,0XAE,0X79,0X98,
0XA7,0X33,0X49,0XFF,0XE6,0XAE,0XBF,0X8D,0X8D,0X20,0X8A,0X49,0X31,0X3A,0X12,0X40};
byte[] iv=new byte[16]{0XF8,0X8B,0X01,0XFB,0X08,0X85,0X9A,0XA4,0XBE,0X45,0X28,0X56,0X03,0X42,0XF6,0X19};
crypt.Key=key;
crypt.IV=iv;
MemoryStream ms=new MemoryStream();
ICryptoTransform transformEncode=new ToBase64Transform();
//Base64编码
CryptoStream csEncode=new CryptoStream(ms,transformEncode,CryptoStreamMode.Write);
CryptoStream csEncrypt=new CryptoStream(csEncode,crypt.CreateEncryptor(),CryptoStreamMode.Write);
System.Text.UTF8Encoding enc=new System.Text.UTF8Encoding();
byte[] rawData=enc.GetBytes(text);
csEncrypt.Write(rawData,0,rawData.Length);
csEncrypt.FlushFinalBlock();
byte[] encryptedData=new byte[ms.Length];
ms.Position=0;
ms.Read(encryptedData,0,(int)ms.Length);
return enc.GetString(encryptedData);
}
//解密,加密解密中的 byte[] key,byte[] iv可以自行修改,加密解密的 数组值一定一致,否则无法对应加密 解密。
public static string Decrypt(string text)
{
Rijndael crypt=Rijndael.Create();
byte[] key=new byte[32]{0XA6,0X7D,0XE1,0X3F,0X35,0X0E,0XE1,0XA9,0X83,0XA5,0X62,0XAA,0X7A,0XAE,0X79,0X98,
0XA7,0X33,0X49,0XFF,0XE6,0XAE,0XBF,0X8D,0X8D,0X20,0X8A,0X49,0X31,0X3A,0X12,0X40};
byte[] iv=new byte[16]{0XF8,0X8B,0X01,0XFB,0X08,0X85,0X9A,0XA4,0XBE,0X45,0X28,0X56,0X03,0X42,0XF6,0X19};
crypt.Key=key;