static CertInfo ToCertInfo(X509Certificate2 cert) { var chain = new X509Chain(); chain.Build(cert); CertInfo certInfo = null; for (int i = chain.ChainElements.Count - 1; i >= 0; i--) { var certElement = chain.ChainElements[i]; certInfo = new CertInfo( certElement.Certificate.FriendlyName, certElement.Certificate.Subject, certElement.Certificate.Thumbprint, certElement.Certificate.SerialNumber, certElement.Certificate.NotBefore, certElement.Certificate.NotAfter, certInfo, certElement.Certificate.Verify(), certElement.ChainElementStatus.Select(x => x.StatusInformation.ToString()).ToArray()); } chain.Reset(); return(certInfo); }
/// <summary> /// Процедура-обработчик /// </summary> static void ThreadProcess(Object stateInfo) { StateInfo s = (StateInfo)stateInfo; try { List <CertInfo> certinfo = new List <CertInfo>(); certinfo = CertInfo.CertificateInfo(s.filename, "sign"); s.locker.WaitOne(); Thread.Sleep(5); using (StreamWriter writer = new StreamWriter(s.wpath + "data.csv", true, Encoding.Default)) { foreach (var e in certinfo) { Console.WriteLine("{0} {1}", e.CNuc, e.CertHash); writer.WriteLine(e.CNuc + "|" + e.INN + "|" + e.KPP + "|" + e.OGRN + "|" + e.SNILS + "|" + e.CertHash + "|" + e.SerialNumber + "|" + e.DateSince + "|" + e.DateExpiration + "|" + e.CNholder + "|" + e.CNuser + "|" + e.Department + "|" + e.Dolgnost + "|" + e.EmailHolder + "|" + e.region + "|" + e.City + "|" + e.Street + "|" + e.sign); writer.Flush(); } } Console.WriteLine("Thread is done!"); s.locker.ReleaseMutex(); } catch { Console.WriteLine("Something wrong!"); } finally { if (Interlocked.Decrement(ref numberOfThreads) == 0) { _doneEvent.Set(); } } }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (CredentialID != null) { hashCode = hashCode * 59 + CredentialID.GetHashCode(); } if (Certificates != null) { hashCode = hashCode * 59 + Certificates.GetHashCode(); } if (CertInfo != null) { hashCode = hashCode * 59 + CertInfo.GetHashCode(); } if (AuthInfo != null) { hashCode = hashCode * 59 + AuthInfo.GetHashCode(); } if (Lang != null) { hashCode = hashCode * 59 + Lang.GetHashCode(); } if (ClientData != null) { hashCode = hashCode * 59 + ClientData.GetHashCode(); } return(hashCode); } }
public override bool onVerifyCertificate(CertInfo certificate) { Console.WriteLine("Received certificate..."); Console.WriteLine("Checksum: " + certificate.Checksum); Console.WriteLine("Cipher: " + certificate.Cipher); Console.WriteLine("CommonName: " + certificate.CommonName); Console.WriteLine("Compression: " + certificate.Compression); Console.WriteLine("Country: " + certificate.Country); Console.WriteLine("FingerPrintMd5: " + certificate.FingerPrintMd5); Console.WriteLine("FingerPrintSha1: " + certificate.FingerPrintSha1); Console.WriteLine("HandshakeMethod: " + certificate.HandshakeMethod); Console.WriteLine("IssuerCommonName: " + certificate.IssuerCommonName); Console.WriteLine("IssuerCountry: " + certificate.IssuerCountry); Console.WriteLine("IssuerOrganization: " + certificate.IssuerOrganization); Console.WriteLine("KeyAlgorithm: " + certificate.KeyAlgorithm); Console.WriteLine("Locality: " + certificate.Locality); Console.WriteLine("Organization: " + certificate.Organization); Console.WriteLine("State: " + certificate.State); Console.WriteLine("Unit: " + certificate.Unit); Console.WriteLine("ValidFrom: " + certificate.ValidFrom); Console.WriteLine("ValidTo: " + certificate.ValidTo); if (new CertForm(certificate.ImgCertificate).ShowDialog() != DialogResult.OK) { return(false); } return(true); }
public EpiWebWrapper(string config) { try { expired = false; string certFile = config.Substring(9).Split('@')[0]; string key = config.Substring(9).Split('@')[1]; string contents = Epi.Configuration.DecryptFileToString(certFile, key); certInfo = JsonConvert.DeserializeObject <CertInfo>(contents); if (certInfo.ExpirationDate < DateTime.Now) { expired = true; } } catch (CryptographicException ce) { Epi.Windows.MsgBox.ShowError("Invalid org key or certificate file"); } catch (JsonSerializationException je) { Epi.Windows.MsgBox.ShowError("Certificate file is malformed. Please ask your Epi Info administrator for a new certificate file."); } catch (Exception ex) { Epi.Windows.MsgBox.ShowError(ex.ToString()); } }
/// <summary> /// Validates an SSL certficate /// </summary> /// <param name="sender"></param> /// <param name="certificate"></param> /// <param name="chain"></param> /// <param name="sslpolicyerrors"></param> /// <param name="hostInformation"></param> /// <returns></returns> private bool UserCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors, ref HostInformation hostInformation) { if (certificate == null) { return(false); } var subject = certificate.Subject; var issuer = certificate.Issuer; if (string.IsNullOrWhiteSpace(subject)) { return(false); } if (string.IsNullOrWhiteSpace(issuer)) { return(false); } chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; chain.ChainPolicy.UrlRetrievalTimeout = TimeSpan.FromSeconds(5); chain.ChainPolicy.VerificationTime = DateTime.Now; var valid = chain.Build(new X509Certificate2(certificate)); hostInformation.Cert = new CertInfo { Subject = CertInfo.DecodeCNID(subject), Issuer = CertInfo.DecodeCNID(issuer), CertValid = valid }; return(valid); }
public MsgServerEncryption(bool UseUdp, CertInfo certificate, byte[] Key, uint OrgKeyHash) : base() { this.UseUdp = UseUdp; this.certificate = certificate; this.Key = Key; this.KeyHash = OrgKeyHash; }
/// <summary> /// 更新凭证密码 /// </summary> public bool UpdateCertPwdByUserId(string userId, string newPassword) { CertInfo certInfo = new CertInfo(); certInfo.UserId = userId; certInfo.CertPwd = newPassword; SqlMapper.Instance().Update("CertInfo.UpdateCertByUserId", certInfo); return(true); }
public Task CertView([FromForm] string content) { CertInfo result = HttpsHelper.GetFirstCertInfo(content); if (!result.Success) { return(this.ShowError(result.Message)); } return(this.GetResult(result.ToString())); }
public void SHA256() { X509Store store = new X509Store(); store.Open(OpenFlags.ReadOnly); var c = store.Certificates[0]; var ci = CertInfo.FromX509(c); Assert.False(string.IsNullOrEmpty(ci.SHA256)); Console.WriteLine(ci.SHA256); }
/// <summary> /// 验证凭证 /// </summary> /// <param name="ht">UserCode, CustomerCode, CertPwd, UserId, CertId</param> public bool Validate(Hashtable ht, ref CertInfo certInfo) { IList <CertInfo> list = null; list = SqlMapper.Instance().QueryForList <CertInfo>("CertInfo.GetCerts", ht); if (list != null && list.Count > 0) { certInfo = list[0]; return(true); } return(false); }
/// <summary> /// GetCertToken /// </summary> public CertTokenInfo GetCertToken(string userId) { CertInfo certInfo = null; Dex.Services.AuthService service = new Services.AuthService(); certInfo = service.GetCertByUserId(userId); var contract = Validate(TransType.JSON, certInfo.UserCode, certInfo.CustomerCode, certInfo.CertPwd, string.Empty); CertTokenInfo certTokenInfo = null; certTokenInfo = service.GetCertTokenByCertId(certInfo.CertId); return(certTokenInfo); }
/// <summary> /// 添加SSL证书 /// </summary> /// <param name="cert"></param> /// <returns></returns> public bool SaveCertInfo(SiteDomainCert cert) { if (cert.SiteID == 0) { return(this.FaildMessage("没有指定站点")); } if (string.IsNullOrEmpty(cert.PEM)) { return(this.FaildMessage("未选择证书")); } if (string.IsNullOrEmpty(cert.KEY)) { return(this.FaildMessage("未选择密钥")); } CertInfo info = HttpsHelper.GetFirstCertInfo(cert.PEM); if (!info.Success) { return(this.FaildMessage(info.Message)); } cert.Name = info.Message; cert.Domain = string.Join(",", info.Domain); cert.Expire = info.ExpireAt; cert.CreateAt = DateTime.Now; if (this.ReadDB.Exists <SiteDomainCert>(t => t.SiteID == cert.SiteID && t.ID != cert.ID && t.Name == cert.Name)) { return(this.FaildMessage("已存在同名的证书")); } bool success = false; using (DbExecutor db = NewExecutor(IsolationLevel.ReadUncommitted)) { if (cert.ID == 0) { success = cert.Add(db); } else { success = cert.Update(db) == 1; } db.Commit(); } return(success && AccountInfo.Log(LogType.Site, string.Format("设定域名证书 {0}", cert.Name))); }
/// <summary> /// Returns true if InputCredentialsInfo instances are equal /// </summary> /// <param name="other">Instance of InputCredentialsInfo to be compared</param> /// <returns>Boolean</returns> public bool Equals(InputCredentialsInfo other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( CredentialID == other.CredentialID || CredentialID != null && CredentialID.Equals(other.CredentialID) ) && ( Certificates == other.Certificates || Certificates != null && Certificates.Equals(other.Certificates) ) && ( CertInfo == other.CertInfo || CertInfo != null && CertInfo.Equals(other.CertInfo) ) && ( AuthInfo == other.AuthInfo || AuthInfo != null && AuthInfo.Equals(other.AuthInfo) ) && ( Lang == other.Lang || Lang != null && Lang.Equals(other.Lang) ) && ( ClientData == other.ClientData || ClientData != null && ClientData.Equals(other.ClientData) )); }
/// <summary> /// Процедура-обработчик /// </summary> /// <param name="file">имя файла</param> /// <param name="mut">мьютекс</param> /// <param name="workpath">рабочая директория программы</param> public static void ThreadProcess(string file, Mutex mut, string workpath) { try { List <CertInfo> certinfo = new List <CertInfo>(); certinfo = CertInfo.CertificateInfo(file, "sign"); mut.WaitOne(); Thread.Sleep(50); using (StreamWriter writer = new StreamWriter(workpath + "data.csv", true, Encoding.Default)) { foreach (var e in certinfo) { Console.WriteLine("{0} {1}", e.CNuc, e.CertHash); writer.WriteLine(e.CNuc + "|" + e.INN + "|" + e.KPP + "|" + e.OGRN + "|" + e.SNILS + "|" + e.CertHash + "|" + e.SerialNumber + "|" + e.DateSince + "|" + e.DateExpiration + "|" + e.CNholder + "|" + e.CNuser + "|" + e.Department + "|" + e.Dolgnost + "|" + e.EmailHolder + "|" + e.region + "|" + e.City + "|" + e.Street + "|" + e.sign); writer.Flush(); } } Console.WriteLine("Thread is done!"); mut.ReleaseMutex(); } catch { Console.WriteLine("Something wrong!"); } }
/// <summary> /// 插入凭证 /// </summary> public bool InsertCert(CertInfo certInfo) { ConfigService cfgService = new ConfigService(); if (certInfo.CertTypeId == null) { certInfo.CertTypeId = cfgService.GetPosBsCertTypeCodeCfg(); } if (certInfo.CertStatus == null) { certInfo.CertStatus = "0"; } if (certInfo.CreateTime == null) { certInfo.CreateTime = Utils.GetNow(); } if (certInfo.ModifyTime == null) { certInfo.ModifyTime = Utils.GetNow(); } SqlMapper.Instance().Insert("CertInfo.InsertCert", certInfo); return(true); }
private static string GetSignerNameFromStateData(IntPtr stateData) { // Well, here's a shitload of indirection for you... // 1. State data -> Provider data IntPtr provData = Win32.WTHelperProvDataFromStateData(stateData); if (provData == IntPtr.Zero) { return(null); } // 2. Provider data -> Provider signer IntPtr signerInfo = Win32.WTHelperGetProvSignerFromChain(provData, 0, false, 0); if (signerInfo == IntPtr.Zero) { return(null); } CryptProviderSgnr sngr = (CryptProviderSgnr)Marshal.PtrToStructure(signerInfo, typeof(CryptProviderSgnr)); if (sngr.CertChain == IntPtr.Zero) { return(null); } if (sngr.CertChainCount == 0) { return(null); } // 3. Provider signer -> Provider cert CryptProviderCert cert = (CryptProviderCert)Marshal.PtrToStructure(sngr.CertChain, typeof(CryptProviderCert)); if (cert.Cert == IntPtr.Zero) { return(null); } // 4. Provider cert -> Cert context CertContext context = (CertContext)Marshal.PtrToStructure(cert.Cert, typeof(CertContext)); if (context.CertInfo != IntPtr.Zero) { // 5. Cert context -> Cert info CertInfo certInfo = (CertInfo)Marshal.PtrToStructure(context.CertInfo, typeof(CertInfo)); unsafe { using (MemoryAlloc buffer = new MemoryAlloc(0x200)) { int length; // 6. Cert info subject -> Subject X.500 string length = Win32.CertNameToStr( 1, new IntPtr(&certInfo.Subject), 3, buffer, buffer.Size / 2 ); if (length > buffer.Size / 2) { buffer.ResizeNew(length * 2); length = Win32.CertNameToStr( 1, new IntPtr(&certInfo.Subject), 3, buffer, buffer.Size / 2 ); } string name = buffer.ReadUnicodeString(0); // 7. Subject X.500 string -> CN or OU value string value = GetX500Value(name, "CN"); if (string.IsNullOrEmpty(value)) { value = GetX500Value(name, "OU"); } return(value); } } } return(null); }
/// <summary> /// 获取日志接口 /// </summary> public GetLogContract GetLog(TransType transType, string userId, string userPwd, string logId) { string bizId = Utils.NewGuid(); string methodKey = "LogService.GetLog"; string ifCode = "C013"; var data = new GetLogContract(); Hashtable htLogExt = new Hashtable(); htLogExt["customer_code"] = null; htLogExt["customer_id"] = null; htLogExt["unit_code"] = null; htLogExt["unit_id"] = null; htLogExt["user_code"] = null; htLogExt["user_id"] = userId; htLogExt["if_code"] = ifCode; htLogExt["app_code"] = AppType.Client; try { Hashtable htParams = new Hashtable(); htParams.Add("trans_type", transType); htParams.Add("user_id", userId); htParams.Add("user_pwd", userPwd); htParams.Add("log_id", logId); LogService.WriteTrace(bizId, methodKey, TraceLogType.Params.ToString(), htParams, userId, htLogExt); bool statusFlag = true; Hashtable htError = null; CertInfo certInfo = null; // 检查参数 Hashtable htResult = new Hashtable(); bool paramCheckFlag = false; #region Check Length htResult = ErrorService.CheckLength("用户ID", userId, 1, 32, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogContract>(htResult)); } htResult = ErrorService.CheckLength("密码", userPwd, 1, 32, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogContract>(htResult)); } htResult = ErrorService.CheckLength("日志ID", logId, 1, 32, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogContract>(htResult)); } #endregion Dex.Services.AuthService authService = new Dex.Services.AuthService(); // 检查User Hashtable htUser = new Hashtable(); htUser.Add("UserId", userId); htUser.Add("CertPwd", userPwd); statusFlag = authService.Validate(htUser, ref certInfo); if (!statusFlag) { htError = ErrorService.OutputError(ErrorCode.A009, "用户ID与密码不匹配", true); data.status = Utils.GetStatus(false); data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } // 获取数据 Services.LogDBService logDBService = new Services.LogDBService(); LogInfo log = logDBService.GetLogById(logId); if (log != null) { LogContract logContract = new LogContract(); logContract.log_id = log.LogId; logContract.biz_id = log.BizId; logContract.biz_name = log.BizName; logContract.log_type_id = log.LogTypeId; logContract.log_type_code = log.LogTypeCode; logContract.log_code = log.LogCode; logContract.log_body = log.LogBody; logContract.create_time = log.CreateTime; logContract.create_user_id = log.CreateUserId; logContract.modify_time = log.ModifyTime; logContract.modify_user_id = log.ModifyUserId; logContract.customer_code = log.CustomerCode; logContract.customer_id = log.CustomerId; logContract.unit_code = log.UnitCode; logContract.unit_id = log.UnitId; logContract.user_code = log.UserCode; logContract.user_id = log.UserId; logContract.if_code = log.IfCode; logContract.app_code = log.AppCode; data.Log = logContract; } data.status = Utils.GetStatus(statusFlag); LogService.WriteTrace(bizId, methodKey, TraceLogType.Return.ToString(), data.ToString(), userId, htLogExt); } catch (Exception ex) { data.status = Utils.GetStatus(false); data.error_code = ErrorCode.A000.ToString(); data.error_full_desc = ex.ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); } return(data); }
/// <summary> /// 获取日志集合接口 /// </summary> public GetLogsContract GetLogs(TransType transType, string userId, string userPwd, long startRow, long rowsCount, LogQueryInfo queryInfo) { string bizId = Utils.NewGuid(); string methodKey = "LogService.GetLogs"; string ifCode = "C011"; var data = new GetLogsContract(); Hashtable htLogExt = new Hashtable(); htLogExt["customer_code"] = null; htLogExt["customer_id"] = null; htLogExt["unit_code"] = null; htLogExt["unit_id"] = null; htLogExt["user_code"] = null; htLogExt["user_id"] = userId; htLogExt["if_code"] = ifCode; htLogExt["app_code"] = AppType.Client; try { Hashtable htParams = new Hashtable(); htParams.Add("trans_type", transType); htParams.Add("user_id", userId); htParams.Add("user_pwd", userPwd); htParams.Add("start_row", startRow); htParams.Add("rows_count", rowsCount); htParams.Add("query_info", queryInfo); LogService.WriteTrace(bizId, methodKey, TraceLogType.Params.ToString(), htParams, userId, htLogExt); bool statusFlag = true; Hashtable htError = null; CertInfo certInfo = null; // 检查参数 Hashtable htResult = new Hashtable(); bool paramCheckFlag = false; #region Check Length htResult = ErrorService.CheckLength("用户ID", userId, 1, 32, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("密码", userPwd, 1, 32, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } // queryInfo htResult = ErrorService.CheckLength("日志ID", queryInfo.log_id, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("业务ID", queryInfo.biz_id, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("业务名称", queryInfo.biz_name, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("日志类型ID", queryInfo.log_type_id, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("日志类型代码", queryInfo.log_type_code, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("日志代码", queryInfo.log_code, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("日志内容", queryInfo.log_body, 0, 200, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("开始创建时间", queryInfo.create_time_begin, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("结束创建时间", queryInfo.create_time_end, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("创建人ID", queryInfo.create_user_id, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("开始修改时间", queryInfo.modify_time_begin, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("结束修改时间", queryInfo.modify_time_end, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("修改人ID", queryInfo.modify_user_id, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("客户代码", queryInfo.customer_code, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("客户ID", queryInfo.customer_id, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("门店代码", queryInfo.unit_code, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("门店ID", queryInfo.unit_id, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("用户代码", queryInfo.user_code, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("用户ID", queryInfo.user_id, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("接口代码", queryInfo.if_code, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } htResult = ErrorService.CheckLength("平台代码", queryInfo.app_code, 0, 50, true, true, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <GetLogsContract>(htResult)); } #endregion Hashtable htQueryInfo = new Hashtable(); htQueryInfo.Add("LogId", queryInfo.log_id); htQueryInfo.Add("BizId", queryInfo.biz_id); htQueryInfo.Add("BizName", queryInfo.biz_name); htQueryInfo.Add("LogTypeId", queryInfo.log_type_id); htQueryInfo.Add("LogTypeCode", queryInfo.log_type_code); htQueryInfo.Add("LogCode", queryInfo.log_code); htQueryInfo.Add("LogBody", queryInfo.log_body); htQueryInfo.Add("CreateTimeBegin", queryInfo.create_time_begin); htQueryInfo.Add("CreateTimeEnd", queryInfo.create_time_end); htQueryInfo.Add("CreateUserId", queryInfo.create_user_id); htQueryInfo.Add("ModifyTimeBegin", queryInfo.modify_time_begin); htQueryInfo.Add("ModifyTimeEnd", queryInfo.modify_time_end); htQueryInfo.Add("ModifyUserId", queryInfo.modify_user_id); htQueryInfo.Add("CustomerCode", queryInfo.customer_code); htQueryInfo.Add("CustomerId", queryInfo.customer_id); htQueryInfo.Add("UnitCode", queryInfo.unit_code); htQueryInfo.Add("UnitId", queryInfo.unit_id); htQueryInfo.Add("UserCode", queryInfo.user_code); htQueryInfo.Add("UserId", queryInfo.user_id); htQueryInfo.Add("IfCode", queryInfo.if_code); htQueryInfo.Add("AppCode", queryInfo.app_code); Dex.Services.AuthService authService = new Dex.Services.AuthService(); // 检查User Hashtable htUser = new Hashtable(); htUser.Add("UserId", userId); htUser.Add("CertPwd", userPwd); statusFlag = authService.Validate(htUser, ref certInfo); if (!statusFlag) { htError = ErrorService.OutputError(ErrorCode.A009, "用户ID与密码不匹配", true); data.status = Utils.GetStatus(false); data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } // 获取数据 Services.LogDBService logDBService = new Services.LogDBService(); IList <LogInfo> logs = logDBService.GetLogs(htQueryInfo, startRow, rowsCount); if (logs != null) { data.Logs = new List <LogContract>(); foreach (var log in logs) { LogContract logContract = new LogContract(); logContract.log_id = log.LogId; logContract.biz_id = log.BizId; logContract.biz_name = log.BizName; logContract.log_type_id = log.LogTypeId; logContract.log_type_code = log.LogTypeCode; logContract.log_code = log.LogCode; logContract.log_body = log.LogBody; logContract.create_time = log.CreateTime; logContract.create_user_id = log.CreateUserId; logContract.modify_time = log.ModifyTime; logContract.modify_user_id = log.ModifyUserId; logContract.customer_code = log.CustomerCode; logContract.customer_id = log.CustomerId; logContract.unit_code = log.UnitCode; logContract.unit_id = log.UnitId; logContract.user_code = log.UserCode; logContract.user_id = log.UserId; logContract.if_code = log.IfCode; logContract.app_code = log.AppCode; data.Logs.Add(logContract); } } data.status = Utils.GetStatus(statusFlag); LogService.WriteTrace(bizId, methodKey, TraceLogType.Return.ToString(), data.ToString(), userId, htLogExt); } catch (Exception ex) { data.status = Utils.GetStatus(false); data.error_code = ErrorCode.A000.ToString(); data.error_full_desc = ex.ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); } return(data); }
static void TestSignAndVerifyPDF() { bool TestSign = true; bool TestVerify = true; string input = @"test1.pdf"; string output = @"test1.signed.pdf"; if (TestSign) { X509Certificate2Collection keyStore = new X509Certificate2Collection(); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); keyStore.AddRange(store.Certificates); store.Close(); //Chung thu so nguoi ky X509Certificate2 cert = null; //[1] Chon chung thu so Console.WriteLine("Chon chung thu so ky"); try { cert = X509Certificate2UI.SelectFromCollection(keyStore, "Chứng thư số ký", "Chọn chứng thư số ký", X509SelectionFlag.SingleSelection)[0]; Console.WriteLine(cert.Subject); } catch { } if (cert == null) { Console.WriteLine("Chua chon chung thu so ky"); return; } //[3] Ky so PdfSigner pdf = new PdfSigner(input, output, cert); pdf.Location = "Hà Nội"; //Hiển thị chữ ký trên tài liệu dạng thông tin miêu tả pdf.SignatureAppearance = PdfSignatureAppearance.RenderingMode.DESCRIPTION; //Hiển thị chữ ký trên tài liệu dạng thông tin miêu tả và hình ảnh //pdf.SignatureAppearance = PdfSignatureAppearance.RenderingMode.GraphicAndDescription; //pdf.SignatureImage = (Bitmap)image; pdf.TsaUrl = "http://ca.gov.vn/tsa"; try { pdf.Sign(1, 0, 0, 250, 50, 0); //iPage: trang; llx: toa do X, lly: Toa do y; iWidth: rong; iHeight: cao Console.WriteLine("Ky so thanh cong!"); } catch (Exception ex) { Console.WriteLine("Loi: " + ex.Message); return; } } if (TestVerify) { //[4] Xac thuc PdfVerifier verifier = new PdfVerifier(output); verifier.AllowedOnlineChecking = true; List <SignatureInfo> list = verifier.Verify(); if (list.Count <= 0) { Console.WriteLine("Van ban chua duoc ky so!"); } else { foreach (SignatureInfo info in list) { string str = string.Empty; string str2 = string.Empty; CertInfo info2 = null; bool flag = false; bool flag2 = false; try { info2 = new CertInfo(info.SigningCertificate); str = info2.ToString(); } catch { str = "N/A"; } string str3 = string.Format("{0}: Ky boi {1}", info.SignatureName, str); Console.WriteLine(str3); Console.WriteLine("- Tinh trang xac thuc:"); if (!info.ValidityErrors.ContainsKey(SignatureValidity.DocumentModified)) { Console.WriteLine("-- Tai lieu chua bi thay doi."); } else { Console.WriteLine("-- Tai lieu da bi thay doi."); flag = true; } if (info.ValidityErrors.ContainsKey(SignatureValidity.InvalidSigningCertificate)) { Console.WriteLine("-- Chung thu so khong hop le: " + info.ValidityErrors[SignatureValidity.InvalidSigningCertificate]); flag = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.ErrorCheckingSigningCertificate)) { Console.WriteLine("-- Loi kiem tra chung thu so: " + info.ValidityErrors[SignatureValidity.ErrorCheckingSigningCertificate]); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.NonCheckingRevokedSigningCert)) { Console.WriteLine("-- Chung thu so khong duoc kiem tra trang thai truc tuyen."); flag2 = true; } else { Console.WriteLine("-- Chung thu so hop le."); } if (info.ValidityErrors.ContainsKey(SignatureValidity.NotTimestamped)) { Console.WriteLine("-- Chu ky khong duoc gan dau thoi gian tin cay."); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.InvalidTimestampImprint)) { Console.WriteLine("-- Dau thoi gian khong hop le."); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.InvalidTSACertificate)) { Console.WriteLine("-- Chung thu so TSA khong hop le:" + info.ValidityErrors[SignatureValidity.InvalidTSACertificate]); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.ErrorCheckingTSACertificate)) { Console.WriteLine("-- Loi kiem tra chung thu so TSA: " + info.ValidityErrors[SignatureValidity.ErrorCheckingTSACertificate]); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.NonCheckingRevokedTSACert)) { Console.WriteLine("--Chung thu so TSA khong duoc kiem tra trang thai truc tuyen."); flag2 = true; } else { Console.WriteLine("-- Dau thoi gian hop le."); } if (!flag && !flag2) { Console.WriteLine("==> Chu ky hop le!"); } else if (flag) { Console.WriteLine("==> Chu ky khong hop le!"); } else { Console.WriteLine("==> Khong du thong tin xac thuc!"); } Console.WriteLine("--Thong tin chu ky"); if (!info.IsTsp) { try { str2 = info.SigningTime.ToString("dd/MM/yyyy HH:mm:ss zzz"); } catch { str2 = "N/A"; } Console.WriteLine(string.Format("--- Thoi gian ky: {0}", str2)); } else { Console.WriteLine("--- Chu ky la dau thoi gian"); } if (!info.ValidityErrors.ContainsKey(SignatureValidity.NotTimestamped)) { Console.WriteLine("--Thong tin dau thoi gian"); try { str2 = info.TimeStampDate.ToString("dd/MM/yyyy HH:mm:ss zzz"); } catch { str2 = "N/A"; } Console.WriteLine(string.Format("--- Gia tri dau thoi gian: {0}", str2)); if (!info.IsTsp) { try { str = new CertInfo(info.TimeStampCertificate).ToString(); } catch { str = "N/A"; } Console.WriteLine(string.Format("--- Chung thu so TSA: {0}", str)); } } try { Console.WriteLine(string.Format("--- Chu ky tren trang {0}", info.PageIndex.ToString())); continue; } catch { continue; } } } } Console.ReadLine(); }
public override bool onVerifyCertificate(CertInfo certificate) { return(true); }
/// <summary> /// 禁用凭证By UserId /// </summary> public bool DisableCertByUserId(CertInfo certInfo) { SqlMapper.Instance().Update("CertInfo.DisableCertByUserId", certInfo); return(true); }
public abstract bool onVerifyCertificate(CertInfo certificate);
public static Signer GetSignerFromStateData(IntPtr StateData) { // Sanity check if (StateData == IntPtr.Zero) { return(null); } // 1. Get provider data from state data IntPtr pProvData = WTHelperProvDataFromStateData(StateData); if (pProvData == IntPtr.Zero) { return(null); } CryptProviderData provData = (CryptProviderData)Marshal.PtrToStructure(pProvData, typeof(CryptProviderData)); // 2. Get provider signer from provider data IntPtr pSgnr = WTHelperGetProvSignerFromChain(pProvData, 0, false, 0); if (pSgnr == IntPtr.Zero) { return(null); } CryptProviderSgnr sgnr = (CryptProviderSgnr)Marshal.PtrToStructure(pSgnr, typeof(CryptProviderSgnr)); if (sgnr.pasCertChain == null) { return(null); } if (sgnr.csCertChain == 0) { return(null); } // 3. Get provider cert from provider signer var providerCerts = new List <CryptProviderCert>(); var ptr = sgnr.pasCertChain; int sizeof_cryptProviderCert = Marshal.SizeOf(new CryptProviderCert()); // Collect certificate chain into a list for (int i = 0; i < sgnr.csCertChain; i++) { providerCerts.Add((CryptProviderCert)Marshal.PtrToStructure(ptr, typeof(CryptProviderCert))); ptr = (IntPtr)((int)ptr + sizeof_cryptProviderCert); // Sanity check const int MAX_CERT_CHAIN_LENGTH = 20; // Arbitrary max length of a chain I'm willing to use if (i > MAX_CERT_CHAIN_LENGTH) { break; } } // This is actually a list, but I only care about the first element CryptProviderCert cert = providerCerts[0]; // 4. Get cert context CertContext certContext = (CertContext)Marshal.PtrToStructure(cert.pCert, typeof(CertContext)); // 5. Get cert info CertInfo certInfo = (CertInfo)Marshal.PtrToStructure(certContext.pCertInfo, typeof(CertInfo)); if (certInfo == null) { return(null); } CRYPTOAPI_BLOB subject = certInfo.Subject; // 6. Get subject X.500 string string issuer = GetCertIssuerString(subject); // Get the best name for identifying this cert X500DistinguishedName x500DN = new X500DistinguishedName(issuer); string signerName = getBestName(x500DN); // Clean up the signer name signerName = signerName.Replace("\"", ""); signerName = signerName.Trim(); // Remove trailing "\x0d" int serialNumberLen = certInfo.SerialNumber.cbData; if (serialNumberLen < 0 || serialNumberLen > 256) { // TODO Should throw an error } var serialNumber = new byte[serialNumberLen]; Marshal.Copy(certInfo.SerialNumber.pbData, serialNumber, 0, serialNumberLen); // Byte order seems to be reversed, so I'm flipping it here Array.Reverse(serialNumber, 0, serialNumberLen); var certEntity = new Certificate { Version = certInfo.dwVersion, Issuer = issuer, SerialNumber = serialNumber, DigestAlgorithm = certInfo.SignatureAlgorithm.pszObjId, DigestEncryptionAlgorithm = certInfo.SubjectPublicKeyInfoAlgo.Algorithm.pszObjId }; var signer = new Signer { Name = signerName, Timestamp = DateTime.FromFileTime((long)sgnr.sftVerifyAsOf), SigningCert = certEntity }; return(signer); }
/// <summary> /// 修改用户密码接口 /// </summary> public BaseContract ChangePassword(TransType transType, string userId, string token, string unitId, string newPassword) { string bizId = Utils.NewGuid(); string methodKey = "AuthService.ChangePassword"; string ifCode = "C029"; var data = new BaseContract(); Hashtable htLogExt = new Hashtable(); htLogExt["customer_code"] = null; htLogExt["customer_id"] = null; htLogExt["unit_code"] = null; htLogExt["unit_id"] = unitId; htLogExt["user_code"] = null; htLogExt["user_id"] = userId; htLogExt["if_code"] = ifCode; htLogExt["app_code"] = AppType.Client; try { Hashtable htParams = new Hashtable(); htParams.Add("trans_type", transType); htParams.Add("user_id", userId); htParams.Add("token", token); htParams.Add("unit_id", unitId); htParams.Add("new_password", newPassword); LogService.WriteTrace(bizId, methodKey, TraceLogType.Params.ToString(), htParams, null, htLogExt); bool statusFlag = false; Hashtable htError = null; CertInfo certInfo = null; Dex.Services.AuthService authService = new Dex.Services.AuthService(); // 检查参数 Hashtable htResult = new Hashtable(); bool paramCheckFlag = false; #region Check Length htResult = ErrorService.CheckLength("用户ID", userId, 1, 32, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <BaseContract>(htResult)); } //htResult = ErrorService.CheckLength("令牌", token, 1, 32, true, false, ref paramCheckFlag); //if (!paramCheckFlag) return ErrorConvert.Export<BaseContract>(htResult); htResult = ErrorService.CheckLength("门店ID", unitId, 1, 32, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <BaseContract>(htResult)); } htResult = ErrorService.CheckLength("用户新密码", newPassword, 1, 40, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <BaseContract>(htResult)); } #endregion // 检查User和Customer certInfo = authService.GetCertByUserId(userId); if (certInfo == null) { htError = ErrorService.OutputError(ErrorCode.A006, "用户ID不存在", true); data.status = Utils.GetStatus(false); data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } statusFlag = true; // 检查Token是否不匹配或过期 //statusFlag = authService.CheckCertToken(token, certInfo.CertId, userId); //if (!statusFlag) //{ // htError = ErrorService.OutputError(ErrorCode.A005, "令牌不匹配或过期", true); // data.status = Utils.GetStatus(false); // data.error_code = htError["error_code"].ToString(); // data.error_full_desc = htError["error_desc"].ToString(); // LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); // return data; //} // 查询凭证 certInfo = authService.GetCertByUserId(userId); if (certInfo == null || certInfo.CustomerId == null || certInfo.CustomerId.Length == 0) { htError = ErrorService.OutputError(ErrorCode.A007, "获取后台数据(客户ID)失败", true); data.status = Utils.GetStatus(false); data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } string customerId = certInfo.CustomerId; htLogExt["customer_code"] = certInfo.CustomerCode; htLogExt["customer_id"] = certInfo.CustomerId; htLogExt["user_code"] = certInfo.UserCode; // 提交 var bsAuthService = new ServicesBs.AuthService(); bsAuthService.ChangePassword(customerId, unitId, userId, newPassword); authService.UpdateCertPwdByUserId(userId, newPassword); data.status = Utils.GetStatus(statusFlag); LogService.WriteTrace(bizId, methodKey, TraceLogType.Return.ToString(), data.ToString(), userId, htLogExt); } catch (Exception ex) { data.status = Utils.GetStatus(false); data.error_code = ErrorCode.A000.ToString(); data.error_full_desc = ex.ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), null, htLogExt); } return(data); }
public override bool onHandshake() { DiffieHellman diffieHellman = new DiffieHellman(256); //send RSA public key RSAEncryption RSA = KeyHandler.GetPrivateKey(); base.SendMessage(new MsgRsaPublicKey(RSA.Parameters)); //Calculate and apply the public key as key //If the key is spoofed the next packet that's being send could fail if public key is generated wrong :) byte[] SecretHash = SHS_KeyExchange.CalculateSecretHash(RSA.Parameters.Modulus, RSA.Parameters.Exponent); Client.Connection.protection.ApplyPrivateKey(SecretHash);//apply our secret hash based on the public key //generate a big random key byte[] encryptionKey = new byte[65535]; new Random(DateTime.Now.Millisecond).NextBytes(encryptionKey); //encrypt the key with RSA byte[] cryptedKey = RSA.Encrypt(encryptionKey, 0, encryptionKey.Length); diffieHellman = KeyHandler.GetDiffieHellman(); byte[] diffieStr = diffieHellman.GetDiffie(); long index = Client.PrivateKeyOffset % 65535; if (index <= 4) { index = 10; } byte[] diffieLen = BitConverter.GetBytes(diffieStr.Length); //create a backup of encrypted RSA data //byte[] RsaBackup = new byte[diffieLen.Length + diffieStr.Length]; //Array.Copy(cryptedKey, index - 4, RsaBackup, 0, RsaBackup.Length); //Rsa Backup Data Array.Copy(diffieLen, 0, cryptedKey, index - 4, diffieLen.Length); //write Diffie-Hellman key length Array.Copy(diffieStr, 0, cryptedKey, index, diffieStr.Length); //copy the diffie-hellman key in between random data //maybe not secure adding this at the end of the encrypted data but whatever for now //Array.Resize(ref cryptedKey, cryptedKey.Length + RsaBackup.Length); //Array.Copy(RsaBackup, 0, cryptedKey, cryptedKey.Length - RsaBackup.Length, RsaBackup.Length); uint KeyHash = BitConverter.ToUInt32(new CRC32().ComputeHash(cryptedKey), 0); CertInfo certificate = new CertInfo(serverProperties.ServerCertificate); certificate.FingerPrintMd5 = BitConverter.ToString(MD5.Create().ComputeHash(serverProperties.ServerCertificate.PrivateKey)).Replace("-", ""); certificate.FingerPrintSha1 = BitConverter.ToString(SHA1.Create().ComputeHash(serverProperties.ServerCertificate.PrivateKey)).Replace("-", ""); certificate.KeyAlgorithm = "RSA with " + Connection.RSA_KEY_SIZE + "bit"; certificate.Compression = ""; //serverProperties.Compression.ToString(); certificate.Cipher = ""; // serverProperties.Encryption.ToString(); certificate.HandshakeMethod = "RSA" + Connection.RSA_KEY_SIZE + "-DiffieHellman-AES256"; if (!serverProperties.ServerCertificate.ShowProtectionMethods) { certificate.Cipher = ""; certificate.Compression = ""; certificate.HandshakeMethod = ""; certificate.KeyAlgorithm = ""; } Client.Certificate = certificate; //Convert bytes to UINT uint[] TempKey = new uint[SecretHash.Length]; for (int i = 0; i < TempKey.Length; i++) { TempKey[i] = SecretHash[i]; } //Encrypt the diffie-hellman key with our SecretHash which is generated by our Public RSA UnsafeXor XorEncryption = new UnsafeXor(TempKey, true); XorEncryption.Encrypt(ref cryptedKey, 0, cryptedKey.Length); //send encryption info + diffie-hellman base.SendMessage(new MsgServerEncryption(serverProperties.AllowUdp, certificate, cryptedKey, KeyHash)); //apply the Encrypted Key, Yes the Encrypted Key, if spoofed the key should change at the client side ;) Client.Connection.protection.ApplyPrivateKey(cryptedKey); if (!base.ReceiveMessage((IMessage message) => { MsgDiffiehellman diffie = message as MsgDiffiehellman; if (diffie != null) { try { diffieHellman.HandleResponse(new PayloadReader(diffie.DiffieHellman)); Client.Connection.protection.ApplyPrivateKey(diffieHellman.Key); //apply diffie-hellman key return(true); } catch { return(false); } } return(false); }).Wait <bool>(false, 30000)) { Client.Disconnect(DisconnectReason.TimeOut); Client.onException(new Exception("Handshake went wrong, SHS_KeyExchange"), ErrorType.Core); return(false); } return(true); }
public void ReloadCerts() { if (Certs == null) { Certs = new ObservableCollection<CertInfo>(); } Certs.Clear(); var allCerts = CertificateUtil.GetAll(xCert => new CertInfo { Title = xCert.FriendlyName, Issuer = xCert.Issuer, Serial = xCert.SerialNumber, Subject = xCert.Subject, ValidAfter = xCert.NotBefore, ValidBefore = xCert.NotAfter }).OrderBy(ci => ci.Title); foreach (var certInfo in allCerts) { Certs.Add(certInfo); } SelectedCertInfo = Certs.FirstOrDefault(); }
/// <summary> /// 删除凭证 /// </summary> public bool DeleteCert(CertInfo certInfo) { SqlMapper.Instance().Update("CertInfo.DeleteCert", certInfo); return(true); }
/// <summary> /// 用户凭证验证 /// </summary> public ValidateContract Validate(TransType transType, string userCode, string customerCode, string password, string type) { string bizId = Utils.NewGuid(); string methodKey = "AuthService.Validate"; string ifCode = "C003"; var data = new ValidateContract(); Hashtable htLogExt = new Hashtable(); htLogExt["customer_code"] = customerCode; htLogExt["customer_id"] = null; htLogExt["unit_code"] = null; htLogExt["unit_id"] = null; htLogExt["user_code"] = userCode; htLogExt["user_id"] = null; htLogExt["if_code"] = ifCode; htLogExt["app_code"] = AppType.Client; try { Hashtable htParams = new Hashtable(); htParams.Add("trans_type", transType); htParams.Add("user_code", userCode); htParams.Add("customer_code", customerCode); htParams.Add("password", password); htParams.Add("type", type); LogService.WriteTrace(bizId, methodKey, TraceLogType.Params.ToString(), htParams, null, htLogExt); bool statusFlag = false; Hashtable htError = null; string userId = string.Empty; string token = string.Empty; CertInfo certInfo = null; if (type == null || type == string.Empty) { type = CertType.POS.ToString(); } Dex.Services.AuthService authService = new Dex.Services.AuthService(); // 检查参数 Hashtable htResult = new Hashtable(); bool paramCheckFlag = false; #region Check Length htResult = ErrorService.CheckLength("用户代码", userCode, 1, 40, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <ValidateContract>(htResult)); } htResult = ErrorService.CheckLength("用户密码", password, 1, 40, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <ValidateContract>(htResult)); } if (type == CertType.POS.ToString()) { htResult = ErrorService.CheckLength("客户代码", customerCode, 1, 40, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <ValidateContract>(htResult)); } } else { htResult = ErrorService.CheckLength("客户代码", customerCode, 0, 40, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <ValidateContract>(htResult)); } } #endregion // 查询用户或客户是否存在 //certInfo = authService.GetCertByUserId(userId); //if (certInfo == null) //{ // htError = ErrorService.OutputError(ErrorCode.A006, "用户ID不存在", true); // data.status = Utils.GetStatus(false); // data.error_code = htError["error_code"].ToString(); // data.error_desc = htError["error_desc"].ToString(); // LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId); // return data; //} // 查询凭证 Hashtable htCert = new Hashtable(); htCert["UserCode"] = userCode; htCert["CustomerCode"] = customerCode; htCert["CertPwd"] = password; if (type == CertType.MOBILE.ToString()) { htCert["CustomerCode"] = null; htCert["CertTypeCode"] = type.ToLower(); } statusFlag = authService.Validate(htCert, ref certInfo); if (!statusFlag) { htError = ErrorService.OutputError(ErrorCode.A009, "用户代码与密码/用户代码与客户代码不匹配", true); if (type == CertType.MOBILE.ToString()) { htError = ErrorService.OutputError(ErrorCode.A009, "用户代码与密码不匹配", true); } data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); } else { userId = certInfo.UserId; // 获取令牌 var certTokenInfo = GetCertToken(certInfo.CertId, certInfo.UserId, true); token = certTokenInfo.CertToken; data.user_id = userId; data.token = token; htLogExt["user_id"] = userId; } data.status = Utils.GetStatus(statusFlag); LogService.WriteTrace(bizId, methodKey, TraceLogType.Return.ToString(), data.ToString(), userId, htLogExt); } catch (Exception ex) { data.status = Utils.GetStatus(false); data.error_code = ErrorCode.A000.ToString(); data.error_full_desc = ex.ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), null, htLogExt); } return(data); }
static SSL() { m_cvCallback += (preverified, depth, errCode, errMessage, ptr) => { if (CertificateVerify != null && ptr != IntPtr.Zero) { string errMsg = null; CertInfo ci = new CertInfo(); CertInfoIntenal cii = new CertInfoIntenal(); System.Runtime.InteropServices.Marshal.PtrToStructure(ptr, cii); ci.Set(cii); unsafe { if (errMessage != IntPtr.Zero) errMsg = new string((sbyte*)errMessage); } return (byte)(CertificateVerify.Invoke(preverified != 0, depth, errCode, errMsg, ci) ? 1 : 0); } return 1; }; ClientCoreLoader.SetCertificateVerifyCallback(m_cvCallback); }
/// <summary> /// 上传 MonitorLog 信息接口 /// </summary> public UploadContract UploadMonitorLog(TransType transType, MonitorLogContract order, string userId, string token, string unitId) { string bizId = Utils.NewGuid(); string methodKey = "ComService.UploadMonitorLog"; string ifCode = "C001"; var data = new UploadContract(); Hashtable htLogExt = new Hashtable(); htLogExt["customer_code"] = null; htLogExt["customer_id"] = null; htLogExt["unit_code"] = null; htLogExt["unit_id"] = unitId; htLogExt["user_code"] = null; htLogExt["user_id"] = userId; htLogExt["if_code"] = ifCode; htLogExt["app_code"] = AppType.Client; try { Hashtable htParams = new Hashtable(); htParams.Add("trans_type", transType); htParams.Add("order", order); htParams.Add("user_id", userId); htParams.Add("token", token); htParams.Add("unit_id", unitId); LogService.WriteTrace(bizId, methodKey, TraceLogType.Params.ToString(), htParams, userId, htLogExt); bool statusFlag = false; Hashtable htError = null; CertInfo certInfo = null; #region 检查参数 Hashtable htResult = new Hashtable(); bool paramCheckFlag = false; htResult = ErrorService.CheckLength("用户ID", userId, 1, 32, true, false, ref paramCheckFlag); if (!paramCheckFlag) { return(ErrorConvert.Export <UploadContract>(htResult)); } //htResult = ErrorService.CheckLength("令牌", token, 1, 32, true, false, ref paramCheckFlag); //if (!paramCheckFlag) return ErrorConvert.Export<UploadContract>(htResult); //htResult = ErrorService.CheckLength("门店ID", unitId, 1, 32, true, false, ref paramCheckFlag); //if (!paramCheckFlag) return ErrorConvert.Export<UploadContract>(htResult); #endregion #region 检查权限 Dex.Services.AuthService authService = new Dex.Services.AuthService(); // 检查User和Customer certInfo = authService.GetCertByUserId(userId); if (certInfo == null) { htError = ErrorService.OutputError(ErrorCode.A006, "用户ID不存在", true); data.status = Utils.GetStatus(false); data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } statusFlag = true; //// 检查Token是否不匹配或过期 //statusFlag = authService.CheckCertToken(token, certInfo.CertId, userId); //if (!statusFlag) //{ // htError = ErrorService.OutputError(ErrorCode.A005, "令牌不匹配或过期", true); // data.status = Utils.GetStatus(false); // data.error_code = htError["error_code"].ToString(); // data.error_full_desc = htError["error_desc"].ToString(); // LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); // return data; //} // 查询凭证 certInfo = authService.GetCertByUserId(userId); if (certInfo == null || certInfo.CustomerId == null || certInfo.CustomerId.Length == 0) { htError = ErrorService.OutputError(ErrorCode.A007, "获取后台数据(客户ID)失败", true); data.status = Utils.GetStatus(false); data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } string customerId = certInfo.CustomerId; htLogExt["customer_code"] = certInfo.CustomerCode; htLogExt["customer_id"] = certInfo.CustomerId; htLogExt["user_code"] = certInfo.UserCode; #endregion #region 检查单据参数 Dex.ServicesBs.ComService orderService = new Dex.ServicesBs.ComService(); if (order.user_id == null || order.user_id.Trim().Length == 0) { order.user_id = userId; } htError = orderService.CheckMonitorLog(order); if (!Convert.ToBoolean(htError["status"])) { data.status = Utils.GetStatus(false); data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } #endregion // 保存 ConfigService cfgService = new ConfigService(); bool enableConnectPosBS = cfgService.GetEnableConnectPosBSCfg(); if (enableConnectPosBS) { try { orderService.SaveMonitorLog(order, customerId, unitId, userId); } catch (Exception ex) { data.status = Utils.GetStatus(false); data.error_code = ErrorCode.A018.ToString(); data.error_full_desc = ex.ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } } else { htError = ErrorService.OutputError(ErrorCode.A012, "连接业务平台数据通道已关闭", true); data.status = Utils.GetStatus(false); data.error_code = htError["error_code"].ToString(); data.error_full_desc = htError["error_desc"].ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); return(data); } data.status = Utils.GetStatus(statusFlag); LogService.WriteTrace(bizId, methodKey, TraceLogType.Return.ToString(), data.ToString(), userId, htLogExt); } catch (Exception ex) { data.status = Utils.GetStatus(false); data.error_code = ErrorCode.A000.ToString(); data.error_full_desc = ex.ToString(); LogService.WriteError(bizId, methodKey, data.error_code, data.ToString(), userId, htLogExt); } return(data); }
/// <summary> /// D001-申请用户凭证方法 /// </summary> public Hashtable ApplyUserCertificate(AppType appType, string apply_user_id, string apply_user_pwd, string user_id, string user_code, string customer_id, string customer_code, string user_password, IList <UserRoleInfo> user_role_info_list) { Hashtable htResult = new Hashtable(); Hashtable ht = new Hashtable(); ht.Add("ApplyUserId", apply_user_id); ht.Add("ApplyUserPwd", apply_user_pwd); ht.Add("UserId", user_id); ht.Add("UserCode", user_code); ht.Add("CustomerId", customer_id); ht.Add("CustomerCode", customer_code); ht.Add("UserPassword", user_password); string bizId = Utils.NewGuid(); string methodKey = "AuthService.ApplyUserCertificate"; string ifCode = "D001"; Hashtable htLogExt = new Hashtable(); htLogExt["customer_code"] = customer_code; htLogExt["customer_id"] = customer_id; htLogExt["unit_code"] = null; htLogExt["unit_id"] = null; htLogExt["user_code"] = null; htLogExt["user_id"] = apply_user_id; htLogExt["if_code"] = ifCode; htLogExt["app_code"] = appType; LogService.WriteTrace(bizId, methodKey, TraceLogType.Params.ToString(), ht, apply_user_id, htLogExt); // 检查参数(可选步骤) bool paramCheckFlag = false; #region Check Length htResult = ErrorService.CheckLength("申请人ID", apply_user_id, 1, 50, false, false, ref paramCheckFlag); if (!paramCheckFlag) { return(htResult); } htResult = ErrorService.CheckLength("用户ID", user_id, 1, 50, false, false, ref paramCheckFlag); if (!paramCheckFlag) { return(htResult); } htResult = ErrorService.CheckLength("用户代码", user_code, 1, 50, false, false, ref paramCheckFlag); if (!paramCheckFlag) { return(htResult); } htResult = ErrorService.CheckLength("客户ID", customer_id, 1, 50, false, false, ref paramCheckFlag); if (!paramCheckFlag) { return(htResult); } htResult = ErrorService.CheckLength("客户代码", customer_code, 1, 50, false, false, ref paramCheckFlag); if (!paramCheckFlag) { return(htResult); } htResult = ErrorService.CheckLength("密码", user_password, 1, 50, false, false, ref paramCheckFlag); if (!paramCheckFlag) { return(htResult); } #endregion // 检查是否已经存在凭证 if (CheckCertByCode(ht)) { htResult["status"] = false; htResult["error_code"] = ErrorCode.A010.ToString(); htResult["error_desc"] = "用户凭证已存在"; return(htResult); } // 插入数据 CertInfo certInfo = new CertInfo(); certInfo.CertId = Utils.NewGuid(); certInfo.UserId = user_id; certInfo.UserCode = user_code; certInfo.CustomerId = customer_id; certInfo.CustomerCode = customer_code; certInfo.CertPwd = user_password; certInfo.CreateUserId = apply_user_id; certInfo.CreateTime = Utils.GetNow(); certInfo.ModifyUserId = apply_user_id; certInfo.ModifyTime = Utils.GetNow(); InsertCert(certInfo); // 插入或更新用户与门店关系信息 UpdateCertUnitRelation(certInfo.CertId, certInfo.UserId, user_role_info_list, apply_user_id); htResult["status"] = true; LogService.WriteTrace(bizId, methodKey, TraceLogType.Return.ToString(), htResult, apply_user_id, htLogExt); return(htResult); }