关于.net core连接数据库字符串加密查询 (DES加密)
des加密获取的乱码是相对一致的 所以只需要获取到加密乱码在api后台解密就好
1、创建一个控制台用来获取加密后的乱码
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Intrinsics.Arm; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Aes = System.Security.Cryptography.Aes; namespace desMssql { public class DesMS { //默认密钥向量 private static byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; /// <summary> /// DES加密字符串 /// </summary> /// <param name="encryptString">待加密的字符串</param> /// <param name="encryptKey">加密密钥,要求为16位</param> /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> public static string DESEncrypt(string encryptString, string encryptKey = "Key123Ace#321Key") { try { byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 16)); byte[] rgbIV = Keys; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); var DCSP = Aes.Create(); 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 (Exception ex) { return ex.Message + encryptString; } } } }
2、输出乱码 替换到api的相对连接数据库位置
class Program { static void Main(string[] args) { var sql = DesMS.DESEncrypt("Data Source=10.31.60.6;Initial Catalog=HONGSHI_SQLSERVER_DATA;User ID=sa;Pwd=123"); Console.WriteLine(sql);Console.ReadKey(); } } }
3、创建一个解密类 替换乱码
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace HONGSHI_Commando_Repository.Helpers { public static class DesMssql { //默认密钥向量 private static byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; /// <summary> /// DES解密字符串 /// </summary> /// <param name="MSSQL">待解密的字符串</param> /// <param name="decryptKey">解密密钥,要求为16位,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string DESDecrypt(string MSSQL, string decryptKey = "Key123Ace#321Key") { try { byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 16)); byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(MSSQL); var DCSP = Aes.Create(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); Byte[] inputByteArrays = new byte[inputByteArray.Length]; cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } catch (Exception ex) { return ex.Message + MSSQL; } } } }
替换
结束!!