コード例 #1
0
        public void SaveDataAsPdf(string outputFileName)
        {
            var base32 = GetDataAsBase32String();

            var pdfDocument = new PdfDocument();

            var pages     = base32.Split(MaxLettersPerPage);
            var pageIndex = 1;

            foreach (var page in pages)
            {
                var qrCode = GetQrCodeAsBmpImage(new MetaData
                {
                    TotalDataSize = (uint)base32.Length,
                    DataChunkSize = (uint)page.Length,
                    ChunkId       = (uint)pageIndex,
                    Checksum      = Sha1Helper.ComputeSha1Checksum(page)
                });
                var pdfPage = pdfDocument.AddPage();
                var gfx     = XGraphics.FromPdfPage(pdfPage);
                AddQrCodeToPage(qrCode, gfx);
                WriteTextOnPage(page.Split(MaxLettersPerRow), gfx);

                pageIndex++;
            }

            pdfDocument.Save(outputFileName);
        }
コード例 #2
0
        private static TServerDHParamsOk SerializeResponse(TPQInnerData pqInnerData, TServerDHInnerData dhInnerData)
        {
            var dhInnerDataBuffer = Serializer.Serialize(dhInnerData);

            byte[] answer;
            try
            {
                answer = dhInnerDataBuffer.ToArray();
            }
            finally
            {
                dhInnerDataBuffer.SafeRelease();
            }

            var hashsum = Sha1Helper.ComputeHashsum(answer);

            var answerWithHash = hashsum.Concat(answer).ToArray();

            AesHelper.ComputeAesParameters(pqInnerData.NewNonce, pqInnerData.ServerNonce, out var aesKeyData);

            var encryptedAnswer = AES.EncryptAes(aesKeyData, answerWithHash);

            return(new TServerDHParamsOk
            {
                EncryptedAnswerAsBinary = encryptedAnswer,
                Nonce = pqInnerData.Nonce,
                ServerNonce = pqInnerData.ServerNonce
            });
        }
コード例 #3
0
        private static RequestSetClientDHParams SerializeRequest(TClientDHInnerData clientDhInnerData, AesKeyData aesKeyData)
        {
            var dhInnerDataBuffer = Serializer.Serialize(clientDhInnerData);

            byte[] innerData;
            try
            {
                Serializer.Serialize(clientDhInnerData);
                innerData = dhInnerDataBuffer.ToArray();
            }
            finally
            {
                dhInnerDataBuffer.SafeRelease();
            }

            var hashsum = Sha1Helper.ComputeHashsum(innerData);

            var answerWithHash = hashsum.Concat(innerData).ToArray();

            var encryptedAnswer = AES.EncryptAes(aesKeyData, answerWithHash);

            return(new RequestSetClientDHParams
            {
                EncryptedDataAsBinary = encryptedAnswer,
                Nonce = clientDhInnerData.Nonce,
                ServerNonce = clientDhInnerData.ServerNonce
            });
        }
コード例 #4
0
        public async Task <HttpResponseMessage> GetTicket([FromUri] string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, Error.LackInfo));
            }

            string openid = await OpenIdHelper.GetOpenIdAsync(code);

            //string openid = "o5dhF1EKpj54qs6-GNoYtLPUSUOA";
            if (string.IsNullOrEmpty(openid))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, Error.LackInfo));
            }

            EmployeeMap employeeMap = new EmployeeMap();

            employeeMap.OpenId = openid;
            employeeMap.Code   = code;

            string sql = @"select * from Employee where OpenId = @OpenId";

            try
            {
                using (IDbConnection connection = new SqlConnection(DBHelper.GetConnectionString()))
                {
                    var employeeMaps = connection.Query <EmployeeMap>(sql, employeeMap);
                    if (employeeMaps == null || employeeMaps.Count() <= 0)
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound, Error.NotFound));
                    }

                    sql = @"select top 1 * from AccessToken order by ExpireTime desc";
                    var tickets = connection.Query <AccessToken>(sql);
                    if (tickets == null || tickets.Count() <= 0)
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound, Error.NotFound));
                    }

                    string noncestr  = ConfigurationManager.AppSettings["noncestr"].ToString();
                    string timestamp = ConfigurationManager.AppSettings["timestamp"].ToString();
                    string url       = HttpContext.Current.Request.UrlReferrer.AbsoluteUri;
                    string ticket    = tickets.ToList()[0].Ticket;

                    string  signature = Sha1Helper.SHA1Encrypt($"jsapi_ticket={ticket}&noncestr={noncestr}&timestamp={timestamp}&url={url}");
                    JObject result    = new JObject();
                    result["sig"]    = signature;
                    result["openid"] = openid;
                    return(Request.CreateResponse(HttpStatusCode.OK, result));
                    //HttpContext.Current.Response.Write(result);
                    //HttpContext.Current.Response.End();
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, Error.Server));
            }
        }
コード例 #5
0
        /// <summary>
        /// 和达第三方登陆
        /// </summary>
        /// <param name="hdAcc">用户名</param>
        /// <param name="hdStamp">时间戳</param>
        /// <param name="hdSSOKey">公钥</param>
        /// <param name="systemType">登陆类型 1:web 3手机App 4c/s</param>
        /// <returns></returns>
        public MessageEntity HDLogin(string hdAcc, string hdStamp, string hdSSOKey, int systemType = 1)
        {
            if (string.IsNullOrEmpty(hdAcc))
            {
                return(MessageEntityTool.GetMessage(ErrorType.OprationError, "", "用户名不能为空"));
            }
            if (string.IsNullOrEmpty(hdStamp))
            {
                return(MessageEntityTool.GetMessage(ErrorType.OprationError, "", "时间戳不能为空"));
            }
            if (string.IsNullOrEmpty(hdSSOKey))
            {
                return(MessageEntityTool.GetMessage(ErrorType.OprationError, "", "公钥不能为空"));
            }
            string hdKey = string.Empty;

            try
            {
                hdKey = Sha1Helper.Encryption(ConfigurationManager.AppSettings["hdSalt"].ToString() + hdAcc + hdStamp);
            }
            catch (Exception e)
            {
                return(MessageEntityTool.GetMessage(ErrorType.FieldError, e.Message));
            }
            if (hdKey.ToLower().Equals(hdSSOKey.Trim().ToString().ToLower()))
            {
                var admin = base.CommonDAL.GetUserInfoByName(hdAcc, out string errorMsg);
                if (admin != null && admin.cAdminName != null)
                {
                    admin.cAdminPassWord = "";

                    admin.Token = CreateAuthention(admin);
                    var funcs = base.CommonDAL.GetUserAuthority(admin.iAdminID.ToString(), systemType, out string userAuthorityErrorMsg);

                    if (funcs != null && funcs.Count() > 0)
                    {
                        admin.UserAuthority = funcs;
                    }

                    var result = MessageEntityTool.GetMessage(1, admin, true, "登陆成功", 1);

                    return(result);
                }
                else if (string.IsNullOrEmpty(errorMsg))
                {
                    return(MessageEntityTool.GetMessage(ErrorType.NoLogin, "", "没有该用户"));
                }
                else
                {
                    return(MessageEntityTool.GetMessage(ErrorType.SystemError, errorMsg));
                }
            }
            else
            {
                return(MessageEntityTool.GetMessage(ErrorType.NoAuthority, "", "第三方登陆验证失败"));
            }
        }
コード例 #6
0
ファイル: AuthKey.cs プロジェクト: zzz8415/OpenTl.Common
        public AuthKey(byte[] data)
        {
            Guard.That(data.Length, nameof(data)).IsEqual(256);

            Data = data;

            var hashsum = Sha1Helper.ComputeHashsum(data);

            _auxHash = BitConverter.ToUInt64(hashsum, 0);
            Id       = BitConverter.ToInt64(hashsum, 8 + 4);
        }
コード例 #7
0
        private static TDhGenOk SerializeResponse(RequestSetClientDHParams setClientDhParams, byte[] newNonce, BigInteger agreement)
        {
            var newNonceHash = Sha1Helper.ComputeHashsum(newNonce).Skip(4).ToArray();

            var authKeyAuxHash = Sha1Helper.ComputeHashsum(agreement.ToByteArrayUnsigned()).Take(8).ToArray();

            return(new TDhGenOk
            {
                Nonce = setClientDhParams.Nonce,
                ServerNonce = setClientDhParams.ServerNonce,
                NewNonceHash1 = newNonceHash.Concat((byte)1).Concat(authKeyAuxHash).ToArray()
            });
        }
コード例 #8
0
 /// <summary>
 /// 验证是否来自微信
 /// </summary>
 /// <param name="token"></param>
 /// <param name="reqModel"></param>
 /// <returns></returns>
 private bool checkSignature(string token, WechatApiReqModel reqModel)
 {
     try
     {
         var signArr = new string[] { token, reqModel.timestamp, reqModel.nonce };
         Array.Sort(signArr);
         string signature = Sha1Helper.GetSHA1(string.Join("", signArr));
         return(signature.Equals(reqModel.signature, StringComparison.CurrentCultureIgnoreCase));
     }
     catch
     {
         return(false);
     }
 }
コード例 #9
0
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="fileId">文件id</param>
        /// <param name="saveFilePath">本地保存的文件路径</param>
        /// <param name="version">下载版本号</param>
        /// <param name="checkSha1">是否检查文件sha1值。如果sha1值和服务器不一致,会删除已经下载的文件,返回false</param>
        /// <returns>是否成功</returns>
        public bool Download(long fileId, string saveFilePath, int version = 0, bool checkSha1 = false)
        {
            var downloadUrl = GetDownloadUrl(fileId, version);

            this._transport.SendDownloadRequest(saveFilePath, new Uri(downloadUrl));
            if (checkSha1)
            {
                var fileInfo = this.Info(fileId);
                if (Sha1Helper.ComputeSha1(saveFilePath) != fileInfo.Sha1)
                {
                    File.Delete(saveFilePath);
                    return(false);
                }
            }
            return(true);
        }
コード例 #10
0
        private bool CheckSignature(Validation validation)
        {
            string token = ConfigurationManager.AppSettings["token"].ToString();

            string[] arr = { token, validation.Timestamp, validation.Nonce };
            Array.Sort(arr);
            string result = Sha1Helper.SHA1Encrypt(string.Join("", arr));

            if (result == validation.Signature)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #11
0
        private static TPQInnerData DeserializeRequest(RequestReqDHParams reqDhParams, string privateKey)
        {
            var encryptedData = reqDhParams.EncryptedDataAsBinary;

            var innerDataWithHash = RSAHelper.RsaDecryptWithPrivate(encryptedData, privateKey);

            var shaHashsum = innerDataWithHash.Take(20).ToArray();

            var innerData = innerDataWithHash.Skip(20).ToArray();

            var hashsum = Sha1Helper.ComputeHashsum(innerData);

            Guard.That(shaHashsum).IsItemsEquals(hashsum);

            var innerDataBuffer = PooledByteBufferAllocator.Default.Buffer(innerData.Length);

            innerDataBuffer.WriteBytes(innerData);

            return(Serializer.Deserialize(innerDataBuffer).Is <TPQInnerData>());
        }
コード例 #12
0
ファイル: Application.cs プロジェクト: miroslavpokorny/smap
        private DecodedLetters DecodeExtractedLetters(IEnumerable <IEnumerable <CsvRow> > lettersCollections, QrReaderData qrData)
        {
            string currentResult     = null;
            var    isChecksumCorrect = false;

            foreach (var letters in lettersCollections)
            {
                var csvReader        = DataOutput.GetCsvParser(letters);
                var targetName       = "class";
                var featureNames     = csvReader.EnumerateRows(c => c != targetName).First().ColumnNameToIndex.Keys.ToArray();
                var testObservations = csvReader.EnumerateRows(featureNames).ToF64Matrix();
                testObservations.Map(p => p / 255);

                var model       = ClassificationNeuralNetModel.Load(() => new StreamReader("network.xml"));
                var predictions = model.Predict(testObservations);

                var stringBuilder = new StringBuilder();
                foreach (var prediction in predictions)
                {
                    stringBuilder.Append(Math.Abs(prediction - -1) < 0.01 ? '-' : Alphabet.Base32Alphabet.ToString()[(int)prediction]);
                }

                currentResult = stringBuilder.ToString();

                isChecksumCorrect = Sha1Helper.IsChecksumCorrect(currentResult, qrData.MetaData.Checksum);

                if (isChecksumCorrect)
                {
                    break;
                }
            }

            return(new DecodedLetters {
                Letters = currentResult, IsChecksumOk = isChecksumCorrect
            });
        }
コード例 #13
0
 public void Add(User user)
 {
     user.Password = Sha1Helper.HashPassword(user.Password + Constants.Salt);
     _repository.Add(user);
 }
コード例 #14
0
        public static RequestReqDHParams GetRequest(TResPQ resPq, string publicKey, out byte[] newNonce)
        {
            var pq = new BigInteger(resPq.PqAsBinary);
            var f1 = PollardRho.Factor(pq);
            var f2 = pq.Divide(f1);
            var p  = f1.Min(f2);
            var q  = f1.Max(f2);

            newNonce = new byte[32];
            Random.NextBytes(newNonce);

            var pqInnerData = new TPQInnerData
            {
                PqAsBinary  = pq.ToByteArrayUnsigned(),
                PAsBinary   = p.ToByteArrayUnsigned(),
                QAsBinary   = q.ToByteArrayUnsigned(),
                ServerNonce = resPq.ServerNonce,
                Nonce       = resPq.Nonce,
                NewNonce    = newNonce
            };

            var serializedData = Serializer.Serialize(pqInnerData);

            byte[] innerData;
            try
            {
                innerData = serializedData.ToArray();
            }
            finally
            {
                serializedData.SafeRelease();
            }

            var fingerprint = RSAHelper.GetFingerprint(publicKey);

            if (!resPq.ServerPublicKeyFingerprints.Contains(fingerprint))
            {
                throw new InvalidOperationException("The fingerprint is not found");
            }

            var hashsum = Sha1Helper.ComputeHashsum(innerData);

            var dataWithHash = PooledByteBufferAllocator.Default.Buffer();

            byte[] innerDataWithHash;
            try
            {
                dataWithHash.WriteBytes(hashsum);
                dataWithHash.WriteBytes(innerData);

                var paddingBytes = new byte[255 - dataWithHash.ReadableBytes];
                Random.NextBytes(paddingBytes);
                dataWithHash.WriteBytes(paddingBytes);
                innerDataWithHash = dataWithHash.ToArray();
            }
            finally
            {
                dataWithHash.SafeRelease();
            }

            var ciphertext = RSAHelper.RsaEncryptWithPublic(innerDataWithHash, publicKey);

            return(new RequestReqDHParams
            {
                Nonce = resPq.Nonce,
                PAsBinary = p.ToByteArrayUnsigned(),
                QAsBinary = q.ToByteArrayUnsigned(),
                ServerNonce = resPq.ServerNonce,
                PublicKeyFingerprint = fingerprint,
                EncryptedDataAsBinary = ciphertext
            });
        }
コード例 #15
0
 private string HashWithSalt(string source)
 {
     return(Sha1Helper.HashPassword(source + Constants.Salt));
 }
コード例 #16
0
ファイル: StringExtensions.cs プロジェクト: sergiorps/GThor
 public static string Sha1(this string valor)
 {
     return(Sha1Helper.Computar(valor));
 }