securityhelper.cs

来自「基于Asp.net、MS sql sever 2000、C# 论坛系统源码」· CS 代码 · 共 71 行

CS
71
字号
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography;

namespace DBCustomAction
{
	/// <summary>
	/// SecurityHelper 的摘要说明。
	/// </summary>
	public abstract class SecurityHelper
	{
		#region 数据库连接字符串的操作
		/// <summary>
		/// 解密数据库连接字符串
		/// </summary>
		/// <param name="InputConnectionString">加密后的数据库连接字符串</param>
		/// <returns>解密后的数据库连接字符串</returns>
		/// <remarks>
		/// 来自pethsop3
		/// </remarks>
		public static string DecryptDBConnectionString(string InputConnectionString)
		{

			// If the variable is blank, return the input
			if(InputConnectionString.Equals(string.Empty))
			{
				return InputConnectionString;
			}

			// Create an instance of the encryption API
			// We assume the key has been encrypted on this machine and not by a user
			DataProtector dp = new DataProtector(Store.Machine);

			// Use the API to decrypt the connection string
			// API works with bytes so we need to convert to and from byte arrays
			byte[] decryptedData = dp.Decrypt( Convert.FromBase64String( InputConnectionString ), null );
			
			// Return the decyrpted data to the string
			return Encoding.ASCII.GetString( decryptedData );
		}

		/// <summary>
		/// 加密数据库连接字符串
		/// </summary>
		/// <param name="encryptedString">未加密的数据库连接字符串</param>
		/// <returns>加密后数据库连接字符串</returns>
		/// <remarks>
		/// 来自pethsop3
		/// </remarks>
		public static string EncryptDBConnectionString(string encryptedString)
		{

			// Create an instance of the encryption API
			// We assume the key has been encrypted on this machine and not by a user
			DataProtector dp = new DataProtector(Store.Machine);

			// Use the API to encrypt the connection string
			// API works with bytes so we need to convert to and from byte arrays
			byte[] dataBytes = Encoding.ASCII.GetBytes( encryptedString );
			byte[] encryptedBytes = dp.Encrypt( dataBytes, null );

			// Return the encyrpted data to the string
			return Convert.ToBase64String( encryptedBytes );
		}

		#endregion

	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?