Procházet zdrojové kódy

增加SQLserver和MongoDB数据库连接密码加解密方法,由于发布频繁暂时未启用

Murphy před 2 roky
rodič
revize
9dd91e3ec6

+ 6 - 21
MicroServices/Business/Business.Application/ResourceExamineManagement/ResourceExamineAppService.cs

@@ -1,8 +1,8 @@
 using Business.Core.Enum;
 using Business.Core.MongoDBHelper;
 using Business.Core.Utilities;
+using Business.Dto;
 using Business.EntityFrameworkCore;
-using Business.ResourceExamineManagement.Dto;
 using Business.EntityFrameworkCore.SqlRepositories;
 using Business.Model.Bang;
 using Business.Model.MES.IC;
@@ -14,10 +14,15 @@ using Business.MongoModel.MES.IC;
 using Business.MongoModel.Production;
 using Business.MongoModel.SRM;
 using Business.MongoModel.Tech;
+using Business.PriorityManagement;
+using Business.Quartz;
+using Business.ResourceExamineManagement.Dto;
+using EFCore.BulkExtensions;
 using Microsoft.EntityFrameworkCore;
 using MongoDB.Driver;
 using MongoDB.Driver.Linq;
 using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -27,27 +32,7 @@ using Volo.Abp.Application.Services;
 using Volo.Abp.DependencyInjection;
 using Volo.Abp.Domain.Repositories;
 using Volo.Abp.MultiTenancy;
-using EFCore.BulkExtensions;
-using Business.Quartz;
-using MongoDB.Bson.Serialization.Attributes;
-using System.ComponentModel.DataAnnotations.Schema;
-using System.ComponentModel.DataAnnotations;
-using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics;
 using Volo.Abp.Uow;
-using Spire.Pdf.Exporting.XPS.Schema;
-using Business.PriorityManagement;
-using Newtonsoft.Json.Linq;
-using Business.Dto;
-using NetTopologySuite.Simplify;
-using System.Transactions;
-using Spire.Pdf.General.Render.Decode.Jpeg2000.j2k.codestream;
-using Volo.Abp.ObjectMapping;
-using SixLabors.ImageSharp;
-using static System.Formats.Asn1.AsnWriter;
-using System.Collections;
-using static Spire.Pdf.General.Render.Decode.Jpeg2000.j2k.codestream.HeaderInfo;
-using Spire.Pdf.General.Render.Decode.Jpeg2000.j2k.wavelet.synthesis;
 
 namespace Business.ResourceExamineManagement
 {

+ 1 - 0
MicroServices/Business/Business.Core/Business.Core.csproj

@@ -14,6 +14,7 @@
     <PackageReference Include="NLog" Version="5.1.2" />
     <PackageReference Include="NLog.Extensions.Logging" Version="5.2.2" />
     <PackageReference Include="NLog.Web.AspNetCore" Version="5.2.2" />
+    <PackageReference Include="RSAExtensions" Version="1.1.1" />
     <PackageReference Include="Spire.Barcode" Version="3.5.0" />
     <PackageReference Include="Spire.PDF" Version="4.11.3" />
     <PackageReference Include="ThoughtWorks.QRCode" Version="1.1.0" />

+ 411 - 0
MicroServices/Business/Business.Core/Utilities/Encrypt.cs

@@ -0,0 +1,411 @@
+using System.Text;
+using System;
+using System.Security.Cryptography;
+using System.Linq;
+using RSAExtensions;
+using Microsoft.AspNetCore.DataProtection.KeyManagement;
+
+namespace Business.Core.Utilities
+{
+    /// <summary>
+    /// 加密操作
+    /// </summary>
+    public static class Encrypt
+    {
+
+        #region Md5加密
+
+        /// <summary>
+        /// Md5加密,返回16位结果
+        /// </summary>
+        /// <param name="value">值</param>
+        public static string Md5By16(string value)
+        {
+            return Md5By16(value, Encoding.UTF8);
+        }
+
+        /// <summary>
+        /// Md5加密,返回16位结果
+        /// </summary>
+        /// <param name="value">值</param>
+        /// <param name="encoding">字符编码</param>
+        public static string Md5By16(string value, Encoding encoding)
+        {
+            return Md5(value, encoding, 4, 8);
+        }
+
+        /// <summary>
+        /// Md5加密
+        /// </summary>
+        private static string Md5(string value, Encoding encoding, int? startIndex, int? length)
+        {
+            if (string.IsNullOrWhiteSpace(value))
+                return string.Empty;
+            var md5 = MD5.Create();
+            string result;
+            try
+            {
+                var hash = md5.ComputeHash(encoding.GetBytes(value));
+                result = startIndex == null ? BitConverter.ToString(hash) : BitConverter.ToString(hash, startIndex.SafeValue(), length.SafeValue());
+            }
+            finally
+            {
+                md5.Clear();
+            }
+            return result.Replace("-", "");
+        }
+
+        /// <summary>
+        /// Md5加密,返回32位结果
+        /// </summary>
+        /// <param name="value">值</param>
+        public static string Md5By32(string value)
+        {
+            return Md5By32(value, Encoding.UTF8);
+        }
+
+        /// <summary>
+        /// Md5加密,返回32位结果
+        /// </summary>
+        /// <param name="value">值</param>
+        /// <param name="encoding">字符编码</param>
+        public static string Md5By32(string value, Encoding encoding)
+        {
+            return Md5(value, encoding, null, null);
+        }
+
+        #endregion
+
+        #region DES加密
+
+        /// <summary>
+        /// DES密钥,24位字符串
+        /// </summary>
+        public static string DesKey = "#s^un2ye21fcv%|f0XpR,+vh";
+
+        /// <summary>
+        /// DES加密
+        /// </summary>
+        /// <param name="value">待加密的值</param>
+        public static string DesEncrypt(object value)
+        {
+            return DesEncrypt(value, DesKey);
+        }
+
+        /// <summary>
+        /// DES加密
+        /// </summary>
+        /// <param name="value">待加密的值</param>
+        /// <param name="key">密钥,24位</param>
+        /// <param name="encoding">编码</param>
+        /// <param name="cipherMode">加密模式</param>
+        /// <param name="paddingMode">填充模式</param>
+        public static string DesEncrypt(object value, string key, Encoding encoding = null, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
+        {
+            string text = value.SafeString();
+            if (ValidateDes(text, key) == false)
+                return string.Empty;
+            using var transform = CreateDesProvider(key, cipherMode, paddingMode).CreateEncryptor();
+            return GetEncryptResult(text, encoding, transform);
+        }
+
+        /// <summary>
+        /// 验证Des加密参数
+        /// </summary>
+        private static bool ValidateDes(string text, string key)
+        {
+            if (text.IsEmpty() || key.IsEmpty())
+                return false;
+            return key.Length == 24;
+        }
+
+        /// <summary>
+        /// 创建Des加密服务提供程序
+        /// </summary>
+        private static TripleDES CreateDesProvider(string key, CipherMode cipherMode, PaddingMode paddingMode)
+        {
+            var result = TripleDES.Create();
+            result.Key = Encoding.ASCII.GetBytes(key);
+            result.Mode = cipherMode;
+            result.Padding = paddingMode;
+            return result;
+        }
+
+        /// <summary>
+        /// 获取加密结果
+        /// </summary>
+        private static string GetEncryptResult(string value, Encoding encoding, ICryptoTransform transform)
+        {
+            encoding ??= Encoding.UTF8;
+            var bytes = encoding.GetBytes(value);
+            var result = transform.TransformFinalBlock(bytes, 0, bytes.Length);
+            return System.Convert.ToBase64String(result);
+        }
+
+        /// <summary>
+        /// DES解密
+        /// </summary>
+        /// <param name="value">加密后的值</param>
+        public static string DesDecrypt(object value)
+        {
+            return DesDecrypt(value, DesKey);
+        }
+
+        /// <summary>
+        /// DES解密
+        /// </summary>
+        /// <param name="value">加密后的值</param>
+        /// <param name="key">密钥,24位</param>
+        /// <param name="encoding">编码</param>
+        /// <param name="cipherMode">加密模式</param>
+        /// <param name="paddingMode">填充模式</param>
+        public static string DesDecrypt(object value, string key, Encoding encoding = null, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
+        {
+            string text = value.SafeString();
+            if (!ValidateDes(text, key))
+                return string.Empty;
+            using var transform = CreateDesProvider(key, cipherMode, paddingMode).CreateDecryptor();
+            return GetDecryptResult(text, encoding, transform);
+        }
+
+        /// <summary>
+        /// 获取解密结果
+        /// </summary>
+        private static string GetDecryptResult(string value, Encoding encoding, ICryptoTransform transform)
+        {
+            encoding ??= Encoding.UTF8;
+            var bytes = System.Convert.FromBase64String(value);
+            var result = transform.TransformFinalBlock(bytes, 0, bytes.Length);
+            return encoding.GetString(result);
+        }
+
+        #endregion
+
+        #region AES加密
+
+        /// <summary>
+        /// 128位0向量
+        /// </summary>
+        private static byte[] _iv;
+        /// <summary>
+        /// 128位0向量
+        /// </summary>
+        private static byte[] Iv
+        {
+            get
+            {
+                if (_iv == null)
+                {
+                    var size = 16;
+                    _iv = new byte[size];
+                    for (int i = 0; i < size; i++)
+                        _iv[i] = 0;
+                }
+                return _iv;
+            }
+        }
+
+        /// <summary>
+        /// AES密钥
+        /// </summary>
+        public static string AesKey = "QaP1AF8utIarcBqdhYTZpVGbiNQ9M6IL";
+
+        /// <summary>
+        /// AES加密
+        /// </summary>
+        /// <param name="value">待加密的值</param>
+        public static string AesEncrypt(string value)
+        {
+            return AesEncrypt(value, AesKey);
+        }
+
+        /// <summary>
+        /// AES加密
+        /// </summary>
+        /// <param name="value">待加密的值</param>
+        /// <param name="key">密钥</param>
+        /// <param name="encoding">编码</param>
+        /// <param name="cipherMode">加密模式</param>
+        /// <param name="paddingMode">填充模式</param>
+        /// <param name="iv">初始化向量</param>
+        public static string AesEncrypt(string value, string key, Encoding encoding = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7, byte[] iv = null)
+        {
+            if (value.IsEmpty() || key.IsEmpty())
+                return string.Empty;
+            iv ??= Iv;
+            var aes = CreateAes(key, cipherMode, paddingMode, iv);
+            using var transform = aes.CreateEncryptor(aes.Key, aes.IV);
+            return GetEncryptResult(value, encoding, transform);
+        }
+
+        /// <summary>
+        /// 创建Aes
+        /// </summary>
+        private static Aes CreateAes(string key, CipherMode cipherMode, PaddingMode paddingMode, byte[] iv)
+        {
+            var result = Aes.Create();
+            result.Key = Encoding.ASCII.GetBytes(key);
+            result.Mode = cipherMode;
+            result.Padding = paddingMode;
+            result.IV = iv;
+            return result;
+        }
+
+        /// <summary>
+        /// AES解密
+        /// </summary>
+        /// <param name="value">加密后的值</param>
+        public static string AesDecrypt(string value)
+        {
+            return AesDecrypt(value, AesKey);
+        }
+
+        /// <summary>
+        /// AES解密
+        /// </summary>
+        /// <param name="value">加密后的值</param>
+        /// <param name="key">密钥</param>
+        /// <param name="encoding">编码</param>
+        /// <param name="cipherMode">加密模式</param>
+        /// <param name="paddingMode">填充模式</param>
+        /// <param name="iv">初始化向量</param>
+        public static string AesDecrypt(string value, string key, Encoding encoding = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7, byte[] iv = null)
+        {
+            if (value.IsEmpty() || key.IsEmpty())
+                return string.Empty;
+            iv ??= Iv;
+            var aes = CreateAes(key, cipherMode, paddingMode, iv);
+            using var transform = aes.CreateDecryptor(aes.Key, aes.IV);
+            return GetDecryptResult(value, encoding, transform);
+        }
+
+        #endregion
+
+        #region HmacSha256加密
+
+        /// <summary>
+        /// HMACSHA256加密
+        /// </summary>
+        /// <param name="value">值</param>
+        /// <param name="key">密钥</param>
+        /// <param name="encoding">字符编码</param>
+        public static string HmacSha256(string value, string key, Encoding encoding = null)
+        {
+            if (value.IsEmpty() || key.IsEmpty())
+                return string.Empty;
+            encoding ??= Encoding.UTF8;
+            var sha256 = new HMACSHA256(Encoding.ASCII.GetBytes(key));
+            var hash = sha256.ComputeHash(encoding.GetBytes(value));
+            return string.Join("", hash.ToList().Select(t => t.ToString("x2")).ToArray());
+        }
+
+        #endregion
+
+        #region RSA加密
+
+        /// <summary>
+        /// RSA签名
+        /// </summary>
+        /// <param name="value">待加密的值</param>
+        /// <param name="privateKey">私钥</param>
+        /// <param name="encoding">编码</param>
+        /// <param name="hashAlgorithm">加密算法,默认值: HashAlgorithmName.SHA1</param>
+        /// <param name="rsaKeyType">Rsa密钥类型,默认值: Pkcs1</param>
+        public static string RsaSign(string value, string privateKey, Encoding encoding = null, HashAlgorithmName? hashAlgorithm = null, RSAKeyType rsaKeyType = RSAKeyType.Pkcs1)
+        {
+            if (value.IsEmpty() || privateKey.IsEmpty())
+                return string.Empty;
+            var rsa = RSA.Create();
+            ImportPrivateKey(rsa, privateKey, rsaKeyType);
+            encoding ??= Encoding.UTF8;
+            hashAlgorithm ??= HashAlgorithmName.SHA1;
+            var result = rsa.SignData(encoding.GetBytes(value), hashAlgorithm.Value, RSASignaturePadding.Pkcs1);
+            return System.Convert.ToBase64String(result);
+        }
+
+        /// <summary>
+        /// 导入私钥
+        /// </summary>
+        private static void ImportPrivateKey(RSA rsa, string privateKey, RSAKeyType rsaKeyType)
+        {
+            rsa.ImportPrivateKey(rsaKeyType, privateKey);
+        }
+
+        /// <summary>
+        /// Rsa验签
+        /// </summary>
+        /// <param name="value">待验签的值</param>
+        /// <param name="publicKey">公钥</param>
+        /// <param name="sign">签名</param>
+        /// <param name="encoding">编码</param>
+        /// <param name="hashAlgorithm">加密算法,默认值: HashAlgorithmName.SHA1</param>
+        public static bool RsaVerify(string value, string publicKey, string sign, Encoding encoding = null, HashAlgorithmName? hashAlgorithm = null)
+        {
+            if (value.IsEmpty() || publicKey.IsEmpty() || sign.IsEmpty())
+                return false;
+            var rsa = RSA.Create();
+            ImportPublicKey(rsa, publicKey);
+            encoding ??= Encoding.UTF8;
+            var signData = System.Convert.FromBase64String(sign);
+            hashAlgorithm ??= HashAlgorithmName.SHA1;
+            return rsa.VerifyData(encoding.GetBytes(value), signData, hashAlgorithm.Value, RSASignaturePadding.Pkcs1);
+        }
+
+        /// <summary>
+        /// 导入公钥
+        /// </summary>
+        private static void ImportPublicKey(RSA rsa, string publicKey)
+        {
+            var key = System.Convert.FromBase64String(publicKey);
+            rsa.ImportSubjectPublicKeyInfo(key, out _);
+        }
+
+        /// <summary>
+        /// RSA加密
+        /// </summary>
+        /// <param name="value">待加密的值</param>
+        /// <param name="publicKey">公钥</param>
+        public static string RsaEncrypt(string value, string publicKey)
+        {
+            if (value.IsEmpty() || publicKey.IsEmpty())
+                return string.Empty;
+            var rsa = RSA.Create();
+            ImportPublicKey(rsa, publicKey);
+            return rsa.EncryptBigData(value, RSAEncryptionPadding.Pkcs1);
+        }
+
+        /// <summary>
+        /// RSA解密
+        /// </summary>
+        /// <param name="value">加密后的值</param>
+        /// <param name="privateKey">私钥</param>
+        public static string RsaDecrypt(string value, string privateKey)
+        {
+            if (value.IsEmpty() || privateKey.IsEmpty())
+                return string.Empty;
+            var rsa = RSA.Create();
+            ImportPrivateKey(rsa, privateKey, RSAKeyType.Pkcs1);
+            return rsa.DecryptBigData(value, RSAEncryptionPadding.Pkcs1);
+        }
+
+        /// <summary>
+        /// 密码解密之后的mongo连接地址
+        /// </summary>
+        public static string GetMongoDBConnectionSM4DecryptString(string connectionString)
+        {
+            if (connectionString.IndexOf("@") > 0)
+            {
+                var strAry = connectionString.Split("@");
+                var userInfo = strAry[0].Substring(10).Split(new char[1] { ':' });
+                string userInfoStr = string.Format("{0}:{1}", userInfo[0], AesDecrypt(userInfo[1]));
+                return string.Format("mongodb://{0}@{1}", userInfoStr, strAry[1]);
+            }
+            else
+            {
+                return connectionString;
+            }
+        }
+
+        #endregion
+    }
+}

+ 70 - 0
MicroServices/Business/Business.Core/Utilities/StringExtensions.cs

@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
 using System.Linq;
 using System.Text;
 using System.Text.RegularExpressions;
@@ -642,5 +643,74 @@ namespace Business.Core.Utilities
         {
             return string.IsNullOrWhiteSpace(url) ? string.Empty : Uri.UnescapeDataString(url).Replace("%27", "'");
         }
+
+        /// <summary>
+        /// 检测对象是否为null,为null则抛出<see cref="ArgumentNullException"/>异常
+        /// </summary>
+        /// <param name="obj">对象</param>
+        /// <param name="parameterName">参数名</param>
+        public static void CheckNull(this object obj, string parameterName)
+        {
+            if (obj == null)
+                throw new ArgumentNullException(parameterName);
+        }
+
+        /// <summary>
+        /// 是否为空
+        /// </summary>
+        /// <param name="value">值</param>
+        public static bool IsEmpty([NotNullWhen(false)] this string? value)
+        {
+            return string.IsNullOrWhiteSpace(value);
+        }
+
+        /// <summary>
+        /// 是否为空
+        /// </summary>
+        /// <param name="value">值</param>
+        public static bool IsEmpty(this Guid value)
+        {
+            return value == Guid.Empty;
+        }
+
+        /// <summary>
+        /// 是否为空
+        /// </summary>
+        /// <param name="value">值</param>
+        public static bool IsEmpty([NotNullWhen(false)] this Guid? value)
+        {
+            if (value == null)
+                return true;
+            return value == Guid.Empty;
+        }
+
+        /// <summary>
+        /// 是否为空
+        /// </summary>
+        /// <param name="value">值</param>
+        public static bool IsEmpty<T>(this IEnumerable<T> value)
+        {
+            if (value == null)
+                return true;
+            return !value.Any();
+        }
+
+        /// <summary>
+        /// 安全转换为字符串,去除两端空格,当值为null时返回""
+        /// </summary>
+        /// <param name="input">输入值</param>
+        public static string SafeString(this object input)
+        {
+            return input?.ToString()?.Trim() ?? string.Empty;
+        }
+
+        /// <summary>
+        /// 安全获取值,当值为null时,不会抛出异常
+        /// </summary>
+        /// <param name="value">可空值</param>
+        public static T SafeValue<T>(this T? value) where T : struct
+        {
+            return value ?? default;
+        }
     }
 }

+ 2 - 0
MicroServices/Business/Business.Domain/MoBaseEntity.cs

@@ -13,6 +13,7 @@ using Microsoft.EntityFrameworkCore;
 using MongoDB.Bson.Serialization.Attributes;
 using Business.Core.Utilities;
 using MongoDB.Bson;
+using System.ComponentModel.DataAnnotations.Schema;
 
 namespace Business.Domain
 {
@@ -29,6 +30,7 @@ namespace Business.Domain
         /// mysql表id
         /// </summary>
         [Comment("mysql表id")]
+        [NotMapped]
         public virtual long mysql_id { get; set; }
 
         /// <summary>