public Task OnGeneratingClaims(TokenGeneratingContext context)
        {
            if (context.CurrentToken.Equals(TokenTypes.IdToken) ||
                context.CurrentToken.Equals(TokenTypes.AccessToken))
            {
                var   userId              = context.User.FindFirstValue(_options.ClaimsIdentity.UserIdClaimType);
                var   applicationId       = context.Application.FindFirstValue(IdentityServiceClaimTypes.ObjectId);
                var   unHashedSubjectBits = Encoding.ASCII.GetBytes($"{userId}/{applicationId}");
                var   hashing             = CryptographyHelpers.CreateSHA256();
                var   subject             = Base64UrlEncoder.Encode(hashing.ComputeHash(unHashedSubjectBits));
                Claim existingClaim       = null;
                foreach (var claim in context.CurrentClaims)
                {
                    if (claim.Type.Equals(IdentityServiceClaimTypes.Subject, StringComparison.Ordinal))
                    {
                        existingClaim = claim;
                    }
                }

                if (existingClaim != null)
                {
                    context.CurrentClaims.Remove(existingClaim);
                }

                context.CurrentClaims.Add(new Claim(IdentityServiceClaimTypes.Subject, subject));
            }

            return(Task.CompletedTask);
        }
        /// <summary>
        /// Stores an object into the LocalStorage.
        /// </summary>
        /// <param name="key">Unique key, can be any string, used for retrieving it later.</param>
        /// <param name="instance"></param>
        public void Store <T>(string key, T instance)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            var value = JsonConvert.SerializeObject(instance);

            if (Storage.Keys.Contains(key))
            {
                Storage.Remove(key);
            }

            if (_config.EnableEncryption)
            {
                value = CryptographyHelpers.Encrypt(_encryptionKey, _config.EncryptionSalt, value);
            }

            Storage.Add(key, value);
        }
        public void ValidateData_Failure()
        {
            byte[] testData = Encoding.UTF8.GetBytes("Hello world TEH HACKZOR!");

            byte[] signature = Convert.FromBase64String("sAx4uDJZFOKcbhj+a65RdCVUF0E/kvluG7FnwGYWRIWNay3r/A7xw5p46shtT0HJrYKApIel00pY7rCdI/OVBP2VvCNvMiTD9VtY6LzMwOXcNKgBDAiSp/cu/ZvqQO7dCALmlBffj+5uKMtThbAgLN+i74wpI7Zt+2kwvQKbbR4=");

            bool valid = CryptographyHelpers.ValidateData(testData, signature);

            Assert.IsFalse(valid);
        }
Exemple #4
0
        private IDictionary <string, string> GetMetadata(SigningCredentials credentials)
        {
            var rsaParameters = CryptographyHelpers.GetRSAParameters(credentials);

            return(new Dictionary <string, string>
            {
                [JsonWebKeyParameterNames.E] = Base64UrlEncoder.Encode(rsaParameters.Exponent),
                [JsonWebKeyParameterNames.N] = Base64UrlEncoder.Encode(rsaParameters.Modulus),
            });
        }
Exemple #5
0
 private IEnumerable <SigningCredentialsDescriptor> GetDescriptors(IdentityServiceOptions options)
 {
     return(options.SigningKeys.Select(sk =>
     {
         var validity = GetValidity(sk);
         return new SigningCredentialsDescriptor(
             sk,
             CryptographyHelpers.GetAlgorithm(sk),
             validity.NotBefore,
             validity.Expires,
             GetMetadata(sk));
     }));
 }
Exemple #6
0
        public void Encryption_Should_Encrypt_String()
        {
            // arrange
            var key  = Guid.NewGuid().ToString();
            var salt = Guid.NewGuid().ToString();
            var text = "lorem ipsum dom dolor sit amet";

            // act
            var target = CryptographyHelpers.Encrypt(key, salt, text);

            // assert
            target.Should().NotBeNullOrEmpty();
            target.Should().NotBe(text);
        }
Exemple #7
0
        private void LoadAzureCredentials()
        {
            cRndRandom = new Random(System.Environment.TickCount);
            String  pStrCreds = File.ReadAllText("../../../../azure/creds.json");
            JObject pJOtCreds = JObject.Parse(pStrCreds);

            cStrTableStorageRootURL = pJOtCreds["TableStorageRootURL"].Value <String>();
            cStrConnectionString    = pJOtCreds["ConnectionString"].Value <String>();
            EnvironmentHelpers.SetEnvironmentVariable("HOME", @"C:\Temp", EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("TableStorageRootURL", cStrTableStorageRootURL, EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("AzureWebJobsStorage", cStrConnectionString, EnvironmentVariableTarget.Process);

            cLisUsers = new List <CreateUserArgs>();
            for (Int32 curUserIndex = 1; curUserIndex <= NOOFUSERS; curUserIndex++)
            {
                String pStrEmail = String.Format("{0}@{1}.com",
                                                 CryptographyHelpers.RandomString(12),
                                                 CryptographyHelpers.RandomString(12));
                String pStrUserName       = CryptographyHelpers.RandomString(12);
                String pStrActivationCode = CryptographyHelpers.RandomString(6);
                cLisUsers.Add(new CreateUserArgs()
                {
                    Email          = pStrEmail,
                    UserName       = pStrUserName,
                    ActivationCode = pStrActivationCode
                });
            }

            for (Int32 curUserIndex = 1; curUserIndex <= NOOFUSERS; curUserIndex++)
            {
                CreateUserArgs pCUAUser = cLisUsers[curUserIndex - 1];
                pCUAUser.Friends = new List <CreateUserArgs>();
                List <Int32> pLisIndexes = new List <Int32>();
                for (Int32 curFriendIndex = 1; curFriendIndex <= NOOFRIENDSPERUSER; curFriendIndex++)
                {
                    List <CreateUserArgs> pLisFriends = new List <CreateUserArgs>();

                    //Get a random user that isn't us
                    Int32 pIntUserIndex = cRndRandom.Next(0, NOOFUSERS);
                    while (pIntUserIndex == curFriendIndex - 1 ||
                           pLisIndexes.Contains(pIntUserIndex))
                    {
                        pIntUserIndex = cRndRandom.Next(0, NOOFUSERS);
                    }

                    pLisIndexes.Add(pIntUserIndex);
                    pCUAUser.Friends.Add(cLisUsers[pIntUserIndex]);
                }
            }
        }
Exemple #8
0
        public void Decrypt_Should_Decode_An_Encrypted_String_With_Special_Characters()
        {
            // arrange
            var key             = Guid.NewGuid().ToString("N");
            var salt            = Guid.NewGuid().ToString("N");
            var original_value  = "Søm€ unicode s-tring+";
            var encrypted_value = CryptographyHelpers.Encrypt(key, salt, original_value);

            // act
            var target = CryptographyHelpers.Decrypt(key, salt, encrypted_value);

            // assert
            target.Should().NotBeNullOrEmpty();
            target.Should().Be(original_value);
        }
Exemple #9
0
        public void Decrypt_Should_Decode_An_Encrypted_String()
        {
            // arrange
            var key             = Guid.NewGuid().ToString();
            var salt            = Guid.NewGuid().ToString();
            var original_value  = "lorem ipsum dom dolor sit amet";
            var encrypted_value = CryptographyHelpers.Encrypt(key, salt, original_value);

            // act
            var target = CryptographyHelpers.Decrypt(key, salt, encrypted_value);

            // assert
            target.Should().NotBeNullOrEmpty();
            target.Should().Be(original_value);
        }
        /// <summary>
        /// Gets a strong typed object from the LocalStorage.
        /// </summary>
        /// <param name="key">Unique key, as used when the object was stored.</param>
        public T Get <T>(string key)
        {
            var succeeded = Storage.TryGetValue(key, out string raw);

            if (!succeeded)
            {
                throw new ArgumentNullException($"Could not find key '{key}' in the LocalStorage.");
            }

            if (_config.EnableEncryption)
            {
                raw = CryptographyHelpers.Decrypt(_encryptionKey, _config.EncryptionSalt, raw);
            }

            return(JsonConvert.DeserializeObject <T>(raw));
        }
        private void LoadAzureCredentials()
        {
            String  pStrCreds = File.ReadAllText("../../../../azure/creds.json");
            JObject pJOtCreds = JObject.Parse(pStrCreds);

            cStrTableStorageRootURL = pJOtCreds["TableStorageRootURL"].Value <String>();
            cStrConnectionString    = pJOtCreds["ConnectionString"].Value <String>();
            EnvironmentHelpers.SetEnvironmentVariable("HOME", @"C:\Temp", EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("TableStorageRootURL", cStrTableStorageRootURL, EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("AzureWebJobsStorage", cStrConnectionString, EnvironmentVariableTarget.Process);
            cStrEmail = String.Format("{0}@{1}.com",
                                      CryptographyHelpers.RandomString(12),
                                      CryptographyHelpers.RandomString(12));
            cStrUserName       = CryptographyHelpers.RandomString(12);
            cStrActivationCode = CryptographyHelpers.RandomString(6);
        }
Exemple #12
0
        private void LoadAzureCredentials()
        {
            String  pStrCreds = File.ReadAllText("../../../../azure/creds.json");
            JObject pJOtCreds = JObject.Parse(pStrCreds);

            cStrTableStorageRootURL = pJOtCreds["TableStorageRootURL"].Value <String>();
            cStrConnectionString    = pJOtCreds["ConnectionString"].Value <String>();
            EnvironmentHelpers.SetEnvironmentVariable("HOME", @"C:\Temp", EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("TableStorageRootURL", cStrTableStorageRootURL, EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("AzureWebJobsStorage", cStrConnectionString, EnvironmentVariableTarget.Process);
            cStrSource = CryptographyHelpers.RandomString(8);

            //Init storage
            cStoStorage = new Storage("TableStorageRootURL",
                                      "AzureWebJobsStorage",
                                      "Test");
        }
Exemple #13
0
        public async Task <IEnumerable <SigningCredentialsDescriptor> > GetCredentials()
        {
            var options = _options.Value;
            var client  = new KeyVaultClient(KeyVaultCallBack, options.ClientHandler);

            var certificateBundle = await client.GetCertificateAsync(options.VaultUri, options.CertificateName);

            var secret = await client.GetSecretAsync(certificateBundle.SecretIdentifier.Identifier);

            var certificate        = new X509Certificate2(Base64UrlEncoder.DecodeBytes(secret.Value), string.Empty);
            var signingCredentials = new SigningCredentials(new X509SecurityKey(certificate), CryptographyHelpers.FindAlgorithm(certificate));
            var descriptor         = new SigningCredentialsDescriptor(
                signingCredentials,
                CryptographyHelpers.GetAlgorithm(signingCredentials),
                certificateBundle.Attributes.NotBefore.Value.ToUniversalTime(),
                certificateBundle.Attributes.Expires.Value.ToUniversalTime(),
                GetMetadata(signingCredentials));

            return(new List <SigningCredentialsDescriptor>()
            {
                descriptor
            });

            IDictionary <string, string> GetMetadata(SigningCredentials credentials)
            {
                var rsaParameters = CryptographyHelpers.GetRSAParameters(credentials);

                return(new Dictionary <string, string>
                {
                    [JsonWebKeyParameterNames.E] = Base64UrlEncoder.Encode(rsaParameters.Exponent),
                    [JsonWebKeyParameterNames.N] = Base64UrlEncoder.Encode(rsaParameters.Modulus),
                });
            }

            async Task <string> KeyVaultCallBack(string authority, string resource, string scope)
            {
                var adCredential          = new ClientCredential(options.ClientId, options.ClientSecret);
                var authenticationContext = new AuthenticationContext(authority, null);
                var tokenResponse         = await authenticationContext.AcquireTokenAsync(resource, adCredential);

                return(tokenResponse.AccessToken);
            }
        }
        /// <summary>
        /// Stores an object into the LocalStorage.
        /// </summary>
        /// <param name="key">Unique key, can be any string, used for retrieving it later.</param>
        /// <param name="instance"></param>
        public void Store <T>(string key, T instance, bool preserveInstReferences = false)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            string value = string.Empty;

            if (preserveInstReferences)
            {
                value = JsonConvert.SerializeObject(instance, new JsonSerializerSettings()
                {
                    //PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
            }
            else
            {
                value = JsonConvert.SerializeObject(instance);
            }

            if (value != string.Empty)
            {
                if (Storage.Keys.Contains(key))
                {
                    Storage.Remove(key);
                }

                if (_config.EnableEncryption)
                {
                    value = CryptographyHelpers.Encrypt(_encryptionKey, _config.EncryptionSalt, value);
                }

                Storage.Add(key, value);
            }
        }
Exemple #15
0
        private bool savePic(string picstr, picType picType, string identity, businessType btype)
        {
            try
            {
                var fpath = Path.Combine(_picpath, identity, btype.ToString());
                if (!Directory.Exists(fpath))
                {
                    Directory.CreateDirectory(fpath);
                }
                var fname = Path.Combine(fpath, picType + ".jpg");

                var index = picstr.IndexOf("base64,");
                //   System.IO.File.WriteAllBytes(fname, Convert.FromBase64String(CryptographyHelpers.StudyEncrypt(picstr.Substring(index + 7))));
                System.IO.File.WriteAllText(fname, CryptographyHelpers.StudyEncrypt(picstr.Substring(index + 7)));
            }
            catch (Exception ex)
            {
                _log.LogInformation("savePic error: {0}", ex);
                return(false);
            }
            return(true);
        }
Exemple #16
0
        public commonresponse downloadpic(picType picType)
        {
            var accinfo = highlevel.GetInfoByToken(Request.Headers);

            if (accinfo.status != responseStatus.ok)
            {
                return(accinfo);
            }

            try
            {
                var fname = Path.Combine(_picpath, accinfo.photofile, accinfo.businessType.ToString(), picType + ".jpg");
                //  highlevel.infolog(_log, "downloadpic", fname);
                var bbytes = CryptographyHelpers.StudyFileDecryptStr(fname);
                var retstr = "data:image/jpeg;base64," + bbytes;
                try
                {
                    var he = Request.Host.ToString();
                    foreach (var a in Request.Headers)
                    {
                        he += "--" + a.Key + "=" + a.Value;
                    }
                    Task.Run(() => highlevel.LogRequest(he + accinfo.photofile + picType + accinfo.Identity,
                                                        "downloadpic", Request.HttpContext.Connection.RemoteIpAddress.ToString(), (short)accinfo.businessType));
                }
                catch (Exception ex) { _log.LogError("dblog error:", ex); }
                return(new downloadresponse {
                    status = responseStatus.ok, picture = retstr
                });
            }
            catch (Exception ex)
            {
                _log.LogError("{0}-{1}-{2}", DateTime.Now, "downloadpic", ex.Message);
                return(new commonresponse {
                    status = responseStatus.processerror, content = ex.Message
                });
            }
        }
Exemple #17
0
        public void UpdatetUserProfile()
        {
            String pStrNewFullName = CryptographyHelpers.RandomString(12);

            devoctomy.funk.core.Membership.Profile pProProfile = cUsrUser.GetProfile(cStoStorage);
            List <String> pLisKeys = pProProfile.GetAllKeys();
            Dictionary <String, String> pDicNewValues = new Dictionary <String, String>();

            foreach (String curKey in pLisKeys)
            {
                String pStrRandom = CryptographyHelpers.RandomString(8);
                pProProfile[curKey] = pStrRandom;
                pDicNewValues.Add(curKey, pStrRandom);
            }
            Assert.IsTrue(cUsrUser.ReplaceProfile(cStoStorage,
                                                  pProProfile));
            pProProfile = cUsrUser.GetProfile(cStoStorage);
            foreach (String curKey in pLisKeys)
            {
                String pStrValue     = pProProfile[curKey];
                String pStrExpecting = pDicNewValues[curKey];
                Assert.IsTrue(pStrValue.Equals(pStrExpecting));
            }
        }
Exemple #18
0
        public void Init()
        {
            String  pStrCreds = File.ReadAllText("../../../../azure/creds.json");
            JObject pJOtCreds = JObject.Parse(pStrCreds);

            cStrTableStorageRootURL = pJOtCreds["TableStorageRootURL"].Value <String>();
            cStrConnectionString    = pJOtCreds["ConnectionString"].Value <String>();
            EnvironmentHelpers.SetEnvironmentVariable("HOME", @"C:\Temp", EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("TableStorageRootURL", cStrTableStorageRootURL, EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("AzureWebJobsStorage", cStrConnectionString, EnvironmentVariableTarget.Process);
            cStrDefaultProfile = File.ReadAllText(@"Assets\ProfileDefaults.json");
            cStrEmail          = String.Format("{0}@{1}.com",
                                               CryptographyHelpers.RandomString(12),
                                               CryptographyHelpers.RandomString(12));
            cStrActivationCode = CryptographyHelpers.RandomString(6);

            //Create the user
            cStoStorage = new Storage("TableStorageRootURL",
                                      "AzureWebJobsStorage",
                                      "Test");
            cUsrUser = new User(GetTestUserPrincipal(), 6);
            cUsrUser.ActivationCode = cStrActivationCode;
            Assert.IsTrue(cUsrUser.Insert(cStoStorage));
        }
Exemple #19
0
        public async Task <SignatureQueryResponse> SignatureQuery([FromBody] SignatureQueryRequest inputRequest)
        {
            try
            {
                var input = JsonConvert.SerializeObject(inputRequest);
                await Task.Run(() =>
                               LogRequest(input, "SignatureQuery", Request.HttpContext.Connection.RemoteIpAddress.ToString()));

                if (inputRequest == null)
                {
                    Log.Error("SignatureQuery,{0}", Global.Status[responseCode.studyRequestError].Description);
                    return(new SignatureQueryResponse
                    {
                        StatusCode = Global.Status[responseCode.studyRequestError].StatusCode,
                        Description = Global.Status[responseCode.studyRequestError].Description
                    });
                }
                Log.Information("SignatureQuery,input={0},from {1}",
                                input, Request.HttpContext.Connection.RemoteIpAddress);
                var allstatus = string.Empty;
                var completed = true;
                var signed    = true;

                var found    = false;
                var identity = string.Empty;
                foreach (var a in tokens)
                {
                    if (a.Token == inputRequest.Token)
                    {
                        identity = a.Identity;
                        found    = true;
                        break;
                    }
                }
                if (!found)
                {
                    Log.Error("SignatureQuery,{0}", Global.Status[responseCode.studyTokenError].Description);
                    return(new SignatureQueryResponse
                    {
                        StatusCode = Global.Status[responseCode.studyTokenError].StatusCode,
                        Description = Global.Status[responseCode.studyTokenError].Description
                    });
                }


                var cryptographicid = CryptographyHelpers.StudyEncrypt(identity);
                var theuser         = _db1.User.FirstOrDefault(async => async.Identity == identity || async.Identity == cryptographicid);
                if (theuser == null)
                {
                    var his = _db1.History.Where(async => async.Identity == identity || async.Identity == cryptographicid)
                              .OrderBy(q => q.Finishdate).LastOrDefault();
                    //;
                    if (his == null)
                    {
                        Log.Error("LoginAndQuery,{0}", Global.Status[responseCode.studyNotNecessary].Description + identity);
                        return(new SignatureQueryResponse
                        {
                            StatusCode = Global.Status[responseCode.studyNotNecessary].StatusCode,
                            Description = Global.Status[responseCode.studyNotNecessary].Description + identity
                        });
                    }

                    completed = his.Completed == "1" ? true : false;
                    signed    = his.Signed == "1" ? true : false;
                    allstatus = his.Studylog;
                }
                else
                {
                    completed = theuser.Completed == "1" ? true : false;
                    signed    = theuser.Signed == "1" ? true : false;

                    allstatus = theuser.Studylog;
                }


                return(new SignatureQueryResponse
                {
                    StatusCode = Global.Status[responseCode.studyOk].StatusCode,
                    Description = Global.Status[responseCode.studyOk].Description,

                    Completed = completed,
                    Signed = signed,

                    AllStatus = allstatus
                });
            }
            catch (Exception ex)
            {
                Log.Error("LoginAndQuery,{0}", ex);
                return(new SignatureQueryResponse
                {
                    StatusCode = Global.Status[responseCode.studyProgramError].StatusCode,
                    Description = Global.Status[responseCode.studyProgramError].Description
                });
            }
        }
Exemple #20
0
        public async Task <CommonResponse> LogSignature([FromBody] LogSignatureRequest inputRequest)
        {
            try
            {
                var input = JsonConvert.SerializeObject(inputRequest);
                await Task.Run(() =>
                               LogRequest(input, "LogSignature", Request.HttpContext.Connection.RemoteIpAddress.ToString()));

                if (inputRequest == null)
                {
                    Log.Error("LogSignature,{0}", Global.Status[responseCode.studyRequestError].Description);
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.studyRequestError].StatusCode,
                        Description = Global.Status[responseCode.studyRequestError].Description
                    });
                }
                Log.Information("LogSignature,input={0},from {1}",
                                input, Request.HttpContext.Connection.RemoteIpAddress);
                var found    = false;
                var identity = string.Empty;
                foreach (var a in tokens)
                {
                    if (a.Token == inputRequest.Token)
                    {
                        identity = a.Identity;
                        found    = true;
                        break;
                    }
                }
                if (!found)
                {
                    Log.Error("LogSignature,{0}", Global.Status[responseCode.studyTokenError].Description);
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.studyTokenError].StatusCode,
                        Description = Global.Status[responseCode.studyTokenError].Description
                    });
                }
                var cryptographicid = CryptographyHelpers.StudyEncrypt(identity);
                var theuser         = _db1.User.FirstOrDefault(async => async.Identity == identity || async.Identity == cryptographicid);
                if (theuser == null)
                {
                    return(new CommonResponse {
                        StatusCode = "100004", Description = "error identity"
                    });
                }
                var date = DateTime.Today;
                //    var dir = string.Format("{0}{1}{2}", date.Year, date.Month, date.Day);
                var fpath = Global.SignaturePath;//Path.Combine(Global.SignaturePath, dir);
                if (!Directory.Exists(fpath))
                {
                    Directory.CreateDirectory(fpath);
                }
                var subfpath = identity;
                if (!string.IsNullOrEmpty(theuser.Photofile))
                {
                    subfpath = theuser.Photofile;
                }
                var fname = Path.Combine(fpath, subfpath + inputRequest.SignatureType);
                var index = inputRequest.SignatureFile.IndexOf("base64,");
                //  Log.Information("LogSignature,{0}", inputRequest.SignatureFile.Substring(index + 7));
                System.IO.File.WriteAllBytes(fname, Convert.FromBase64String(inputRequest.SignatureFile.Substring(index + 7)));

                switch (inputRequest.SignatureType)
                {
                case SignatureType.PhysicalCondition:
                    theuser.Firstsigned = "1";
                    // if (!string.IsNullOrEmpty(inputRequest.PostalAddress))
                    // {
                    //     theuser.Postaladdress = inputRequest.PostalAddress;
                    // }
                    break;

                case SignatureType.EducationalRecord:
                    theuser.Signed = "1";
                    break;

                default:
                    break;
                }
                if (inputRequest.SignatureType == SignatureType.EducationalRecord)
                {
                    _db1.History.Add(new History
                    {
                        Identity       = cryptographicid,
                        Drivinglicense = theuser.Drivinglicense,
                        Deductedmarks  = theuser.Deductedmarks,
                        Name           = theuser.Name,
                        Syncphone      = theuser.Syncphone,
                        Phone          = theuser.Phone,
                        Syncdate       = theuser.Syncdate,
                        Startdate      = theuser.Startdate,
                        Completed      = theuser.Completed,
                        Finishdate     = DateTime.Now,
                        Stoplicense    = theuser.Stoplicense,
                        Noticedate     = theuser.Noticedate,
                        Wechat         = theuser.Wechat,
                        Studylog       = theuser.Studylog,
                        Postaladdress  = theuser.Postaladdress,
                        Drugrelated    = theuser.Drugrelated,
                        Fullmark       = theuser.Fullmark,
                        Inspect        = theuser.Inspect,
                        Completelog    = theuser.Completelog,
                        Signed         = theuser.Signed,
                        Photostatus    = theuser.Photostatus,
                        Firstsigned    = theuser.Firstsigned,
                        Photofile      = theuser.Photofile,
                        Status         = theuser.Status,
                        Token          = theuser.Token,
                        Lasttoken      = theuser.Lasttoken,
                        Licensetype    = theuser.Licensetype
                    });
                    _db1.User.Remove(theuser);
                }
                _db1.SaveChanges();
                return(new CommonResponse
                {
                    StatusCode = Global.Status[responseCode.studyOk].StatusCode,
                    Description = Global.Status[responseCode.studyOk].Description,
                });
            }
            catch (Exception ex)
            {
                Log.Error("LogSignature,{0}", ex);
                return(new CommonResponse
                {
                    StatusCode = Global.Status[responseCode.studyProgramError].StatusCode,
                    Description = Global.Status[responseCode.studyProgramError].Description
                });
            }
        }
Exemple #21
0
        public async Task <LoginAndQueryResponse> LoginAndQuery([FromBody] LoginAndQueryRequest inputRequest)
        {
            try
            {
                var input = JsonConvert.SerializeObject(inputRequest);
                await Task.Run(() =>
                               LogRequest(input, "LoginAndQuery", Request.HttpContext.Connection.RemoteIpAddress.ToString()));

                if (inputRequest == null)
                {
                    Log.Error("LoginAndQuery,{0}", Global.Status[responseCode.studyRequestError].Description);
                    return(new LoginAndQueryResponse
                    {
                        StatusCode = Global.Status[responseCode.studyRequestError].StatusCode,
                        Description = Global.Status[responseCode.studyRequestError].Description
                    });
                }
                Log.Information("LoginAndQuery,input={0},from {1}", input, Request.HttpContext.Connection.RemoteIpAddress);
                var allstatus       = string.Empty;
                var allow           = true;
                var completed       = true;
                var signed          = true;
                var firstsigned     = true;
                var drivinglicense  = string.Empty;
                var deductedmarks   = 0;
                var identity        = inputRequest.Identity;
                var fname           = identity + ".jpg";
                var cryptographicid = CryptographyHelpers.StudyEncrypt(identity);
                var pic             = new byte[8];


                //token process
                var toke1n    = GetToken();
                var found     = false;
                var lasttoken = string.Empty;
                foreach (var a in tokens)
                {
                    if (a.Identity == identity)
                    {
                        //  lasttoken = a.Token;
                        a.Token = toke1n;
                        found   = true;
                        break;
                    }
                }
                if (!found)
                {
                    tokens.Add(new Ptoken {
                        Identity = identity, Token = toke1n
                    });
                }

                var theuser = _db1.User.FirstOrDefault(async => (async.Identity == identity || async.Identity == cryptographicid) &&
                                                       async.Inspect == "1"
                                                       );
                if (theuser == null)
                {
                    var his = _db1.History.Where(async => async.Identity == identity || async.Identity == cryptographicid)
                              .OrderBy(al => al.Finishdate).LastOrDefault();
                    if (his == null)
                    {
                        Log.Error("LoginAndQuery,{0}", Global.Status[responseCode.studyNotNecessary].Description + identity);
                        return(new LoginAndQueryResponse
                        {
                            StatusCode = Global.Status[responseCode.studyNotNecessary].StatusCode,
                            Description = Global.Status[responseCode.studyNotNecessary].Description + identity
                        });
                    }
                    allow = his.Drugrelated != "1" ? true : false;
                    if (!string.IsNullOrEmpty(his.Status) && (his.Status.Contains("H") || his.Status.Contains("M")))
                    {
                        allow = false;
                    }
                    completed   = his.Completed == "1" ? true : false;
                    signed      = his.Signed == "1" ? true : false;
                    firstsigned = his.Firstsigned == "1" ? true : false;
                    if (!string.IsNullOrEmpty(his.Licensetype))
                    {
                        drivinglicense = his.Licensetype;
                    }
                    if (his.Deductedmarks != null)
                    {
                        deductedmarks = (int)his?.Deductedmarks;
                    }
                    try
                    {
                        if (!string.IsNullOrEmpty(his.Photofile))
                        {
                            fname = his.Photofile;
                            pic   = CryptographyHelpers.StudyFileDecrypt(Path.Combine(Global.PhotoPath, fname));
                        }
                        else
                        {
                            var filename = Path.Combine(Global.PhotoPath, fname);
                            pic = System.IO.File.ReadAllBytes(filename);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("loginandquery,{0},={1}", identity, ex.Message);
                    }
                    if (allow)
                    {
                        allstatus = his.Studylog;
                    }
                    else
                    {
                        allstatus = "您不能参加网络学习,可以参加现场学习";
                    }
                }
                else
                {
                    //drugrelated judge
                    allow = theuser.Drugrelated != "1" ? true : false;
                    if (!string.IsNullOrEmpty(theuser.Status) && (theuser.Status.Contains("H") || theuser.Status.Contains("M")))
                    {
                        allow = false;
                    }
                    completed   = theuser.Completed == "1" ? true : false;
                    signed      = theuser.Signed == "1" ? true : false;
                    firstsigned = theuser.Firstsigned == "1" ? true : false;
                    if (!string.IsNullOrEmpty(theuser.Licensetype))
                    {
                        drivinglicense = theuser.Licensetype;
                    }
                    if (theuser.Deductedmarks != null)
                    {
                        deductedmarks = (int)theuser?.Deductedmarks;
                    }
                    if (allow)
                    {
                        allstatus = theuser.Studylog;
                        //need update?
                        if (!string.IsNullOrEmpty(inputRequest.Name))
                        {
                            theuser.Name = inputRequest.Name;
                        }
                        //  theuser.Licensetype = ((int)inputRequest.DrivingLicenseType).ToString();//elements?
                        if (!string.IsNullOrEmpty(inputRequest.Phone))
                        {
                            theuser.Phone = inputRequest.Phone;
                        }
                        // theuser.Wechat = inputRequest.Wechat;
                        if (theuser.Startdate == null)
                        {
                            theuser.Startdate = DateTime.Now;
                        }
                        if (!string.IsNullOrEmpty(theuser.Token))
                        {
                            lasttoken = theuser.Token;
                        }
                        _db1.SaveChanges();
                    }
                    else
                    {
                        allstatus = "您不能参加网络学习,可以参加现场学习";
                    }
                    try
                    {
                        if (!string.IsNullOrEmpty(theuser.Photofile))
                        {
                            fname = theuser.Photofile;
                            pic   = CryptographyHelpers.StudyFileDecrypt(Path.Combine(Global.PhotoPath, fname));
                        }
                        else
                        {
                            var filename = Path.Combine(Global.PhotoPath, fname);
                            pic = System.IO.File.ReadAllBytes(filename);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("loginandquery,{0},={1}", identity, ex.Message);
                    }
                }



                return(new LoginAndQueryResponse
                {
                    Token = toke1n,
                    LastToken = lasttoken,
                    StatusCode = Global.Status[responseCode.studyOk].StatusCode,
                    Description = Global.Status[responseCode.studyOk].Description,
                    AllowedToStudy = allow,
                    Completed = completed,
                    Signed = signed,
                    FirstSigned = firstsigned,
                    DrivingLicense = drivinglicense,
                    DeductedMarks = deductedmarks,
                    Photo = pic,
                    AllStatus = allstatus
                });
            }
            catch (Exception ex)
            {
                Log.Error("LoginAndQuery,{0}", ex);
                return(new LoginAndQueryResponse
                {
                    StatusCode = Global.Status[responseCode.studyProgramError].StatusCode,
                    Description = Global.Status[responseCode.studyProgramError].Description
                });
            }
        }
Exemple #22
0
 public commonresponse getScrapDoneList(string startdate = "2000-1-1", string enddate = "2222-2-2",
                                        CarType carType  = CarType.unknown,
                                        int startnum     = 1, int endnum = -1)
 {
     try
     {
         var token      = Request.Headers["Token"].First();
         var found      = false;
         var scrapplace = ScrapPlace.unknown;
         foreach (var a in tokens)
         {
             if (a.Token == token)
             {
                 scrapplace = a.scrapPlace;
                 found      = true;
                 break;
             }
         }
         _log.LogInformation("DeleteScrap,{0},,", 111);
         if (!found)
         {
             _log.LogInformation("DeleteScrap,{0}", responseStatus.tokenerror);
             return(new commonresponse
             {
                 status = responseStatus.tokenerror
             });
         }
         var start = DateTime.Now;
         if (string.IsNullOrEmpty(startdate) || !DateTime.TryParse(startdate, out start))
         {
             return(new commonresponse {
                 status = responseStatus.startdateerror, content = responseStatus.startdateerror.ToString()
             });
         }
         var end = DateTime.Now;
         if (string.IsNullOrEmpty(enddate) || !DateTime.TryParse(enddate, out end))
         {
             return(new commonresponse {
                 status = responseStatus.enddateerror, content = responseStatus.enddateerror.ToString()
             });
         }
         var scraps = new List <Scrap>();
         var count  = 0;
         using (var db = new carsContext())
         {
             var ss = db.Carbusinesshis.Where(a => a.Businesstype == (short)businessType.scrap &&
                                              a.Time.CompareTo(start) >= 0 &&
                                              a.Time.CompareTo(end) <= 0 &&
                                              a.Scrapplace == (short)scrapplace
                                              // && a.Cartype==(short)carType
                                              );
             if (carType != CarType.unknown)
             {
                 ss = ss.Where(c => c.Cartype == (short)carType);
             }
             count = ss.Count();
             if (endnum != -1)
             {
                 ss = ss.Take(endnum);
             }
             ss = ss.Skip(startnum - 1);
             //  var index = 1;
             foreach (var s in ss)
             {
                 //  if (index++ < startnum) continue;
                 var user = db.Caruser.FirstOrDefault(a => a.Identity == s.Identity);
                 if (user == null)
                 {
                     continue;
                 }
                 scraps.Add(new Scrap
                 {
                     id      = CryptographyHelpers.StudyDecrypt(s.Identity),
                     name    = user.Name,
                     phone   = user.Phone,
                     address = s.Postaddr,
                     cartype = (CarType)s.Cartype,
                     time    = s.Time,
                 });
             }
         }
         Task.Run(() => highlevel.LogRequest("getScrapDoneList",
                                             "getScrapDoneList", Request.HttpContext.Connection.RemoteIpAddress.ToString(), 0));
         return(new ScrapListRes {
             status = responseStatus.ok, scraps = scraps, count = count
         });
     }
     catch (Exception ex)
     {
         _log.LogError("{0}-{1}-{2}", DateTime.Now, "getScrapDoneList", ex.Message);
         return(new commonresponse {
             status = responseStatus.processerror, content = ex.Message
         });
     }
 }
Exemple #23
0
        public async Task <CommonResponse> InspectCompleteCourses([FromBody] CompleteCoursesRequest inputRequest)
        {
            try
            {
                var input = JsonConvert.SerializeObject(inputRequest);
                await Task.Run(() =>
                               LogRequest(input, "InspectCompleteCourses", Request.HttpContext.Connection.RemoteIpAddress.ToString()));

                if (inputRequest == null)
                {
                    Log.Error("InspectCompleteCourses,{0}", Global.Status[responseCode.RequestError].Description);
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.RequestError].StatusCode,
                        Description = Global.Status[responseCode.RequestError].Description
                    });
                }
                Log.Information("InspectCompleteCourses,input={0},from {1}",
                                input, Request.HttpContext.Connection.RemoteIpAddress);
                var found    = false;
                var identity = string.Empty;
                foreach (var a in tokens)
                {
                    if (a.Token == inputRequest.Token)
                    {
                        identity = a.Identity;
                        found    = true;
                        break;
                    }
                }
                if (!found)
                {
                    Log.Error("InspectCompleteCourses,{0},token={1}",
                              Global.Status[responseCode.TokenError].Description, inputRequest.Token);
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.TokenError].StatusCode,
                        Description = Global.Status[responseCode.TokenError].Description
                    });
                }
                var cryptographicid = CryptographyHelpers.StudyEncrypt(identity);
                var theuser         = _db1.User.FirstOrDefault(async => async.Identity == identity || async.Identity == cryptographicid);
                //  var theuser = _db1.User.FirstOrDefault(async => async.Identity == identity);
                if (theuser == null)
                {
                    Log.Error("InspectCompleteCourses,{0},identity={1}",
                              Global.Status[responseCode.InvalidIdentiy].Description, identity);
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.InvalidIdentiy].StatusCode,
                        Description = Global.Status[responseCode.InvalidIdentiy].Description
                    });
                }
                if (theuser.Completed == "1")
                {
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.ok].StatusCode,
                        Description = Global.Status[responseCode.ok].Description,
                    });
                }
                // theuser. = DateTime.Now;
                var clog = inputRequest.AllStatus.Length < 80 ? inputRequest.AllStatus : inputRequest.AllStatus.Substring(0, 78);
                theuser.Completelog = clog;
                theuser.Completed   = "1";
                //   theuser.Syncdate=DateTime.Now;
                _db1.SaveChanges();

                if (inputRequest.AllRecords != null)
                {
                    var date = DateTime.Today;
                    // var dir = string.Format("{0}{1}{2}", date.Year, date.Month, date.Day);
                    var subfpath = identity;
                    if (!string.IsNullOrEmpty(theuser.Photofile))
                    {
                        subfpath = theuser.Photofile;
                    }
                    var fpath = Path.Combine(Global.LogPhotoPath, subfpath);
                    if (!Directory.Exists(fpath))
                    {
                        Directory.CreateDirectory(fpath);
                    }

                    var fname = Path.Combine(fpath, "exam_result.txt");
                    Log.Information("filename is: {0}", fname);
                    System.IO.File.WriteAllBytes(fname, inputRequest.AllRecords);
                }

                return(new CommonResponse
                {
                    StatusCode = Global.Status[responseCode.ok].StatusCode,
                    Description = Global.Status[responseCode.ok].Description,
                });
            }
            catch (Exception ex)
            {
                Log.Error("InspectCompleteCourses,{0},exception={1}",
                          Global.Status[responseCode.ProgramError].Description, ex);
                return(new CommonResponse
                {
                    StatusCode = Global.Status[responseCode.ProgramError].StatusCode,
                    Description = Global.Status[responseCode.ProgramError].Description
                });
            }
        }
Exemple #24
0
        public async Task <GetLearnerInfoResponse> InspectGetLearnerInfo(string token)
        {
            try
            {
                await Task.Run(() =>
                               LogRequest(token, "InspectGetLearnerInfo", Request.HttpContext.Connection.RemoteIpAddress.ToString()));

                if (string.IsNullOrEmpty(token))
                {
                    Log.Error("InspectGetLearnerInfo,{0},token={1}, from {2}",
                              Global.Status[responseCode.TokenError].Description, "invalid", Request.HttpContext.Connection.RemoteIpAddress);
                    return(new GetLearnerInfoResponse
                    {
                        StatusCode = Global.Status[responseCode.TokenError].StatusCode,
                        Description = Global.Status[responseCode.TokenError].Description
                    });
                }
                Log.Information("InspectGetLearnerInfo,input={0},from {1}",
                                token, Request.HttpContext.Connection.RemoteIpAddress);
                var found    = false;
                var identity = string.Empty;
                foreach (var a in tokens)
                {
                    if (a.Token == token)
                    {
                        identity = a.Identity;
                        found    = true;
                        break;
                    }
                }
                if (!found)
                {
                    Log.Error("InspectGetLearnerInfo,{0},token={1},no corresponding identity",
                              Global.Status[responseCode.TokenError].Description, token);
                    return(new GetLearnerInfoResponse
                    {
                        StatusCode = Global.Status[responseCode.TokenError].StatusCode,
                        Description = Global.Status[responseCode.TokenError].Description + token
                    });
                }
                var cryptographicid = CryptographyHelpers.StudyEncrypt(identity);
                var theuser         = _db1.User.FirstOrDefault(async => async.Identity == identity || async.Identity == cryptographicid);
                // var theuser = _db1.User.FirstOrDefault(async => async.Identity == identity);
                if (theuser == null)
                {
                    Log.Error("InspectGetLearnerInfo,{0},identity={1}",
                              Global.Status[responseCode.InvalidIdentiy].Description, identity);
                    return(new GetLearnerInfoResponse
                    {
                        StatusCode = Global.Status[responseCode.InvalidIdentiy].StatusCode,
                        Description = Global.Status[responseCode.InvalidIdentiy].Description
                    });
                }
                var pic     = new byte[1];
                var photook = true;
                try
                {
                    Log.Information("InspectGetLearnerInfo,{0},={1}", Global.PhotoPath, Global.PhotoPath);
                    var ff = identity + ".jpg";
                    if (!string.IsNullOrEmpty(theuser.Photofile))
                    {
                        ff = theuser.Photofile;
                        var filename = Path.Combine(Global.PhotoPath, ff);
                        pic = CryptographyHelpers.StudyFileDecrypt(filename);
                    }
                    else
                    {
                        var filename = Path.Combine(Global.PhotoPath, ff);
                        pic = System.IO.File.ReadAllBytes(filename);
                    }
                }
                catch (Exception ex)
                {
                    photook = false;
                    Log.Error("InspectGetLearnerInfo,{0},={1}", identity, ex.Message);
                }
                theuser.Token    = token;
                theuser.Syncdate = DateTime.Now;
                _db1.SaveChanges();
                return(new GetLearnerInfoResponse
                {
                    StatusCode = Global.Status[responseCode.ok].StatusCode,
                    Description = Global.Status[responseCode.ok].Description,
                    DrivingLicenseType = string.IsNullOrEmpty(theuser.Licensetype) ? DrivingLicenseType.Unknown : (DrivingLicenseType)int.Parse(theuser.Licensetype),

                    //   Identity = theuser.Identity,
                    Name = theuser.Name,
                    PhotoOk = photook,
                    Photo = pic
                });
            }
            catch (Exception ex)
            {
                Log.Error("InspectGetLearnerInfo,{0},{2},exception={1}",
                          Global.Status[responseCode.ProgramError].Description, ex, Global.PhotoPath);
                return(new GetLearnerInfoResponse
                {
                    StatusCode = Global.Status[responseCode.ProgramError].StatusCode,
                    Description = Global.Status[responseCode.ProgramError].Description
                });
            }
        }
Exemple #25
0
        public async Task <CommonResponse> InspectPostStudyStatus([FromBody] StudyStatusRequest inputRequest)
        {
            try
            {
                var input = JsonConvert.SerializeObject(inputRequest);
                await Task.Run(() => LogRequest(input, "InspectPostStudyStatus", Request.HttpContext.Connection.RemoteIpAddress.ToString()));

                if (inputRequest == null)
                {
                    Log.Error("InspectPostStudyStatus,{0}", Global.Status[responseCode.RequestError].Description);
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.RequestError].StatusCode,
                        Description = Global.Status[responseCode.RequestError].Description
                    });
                }
                Log.Information("InspectPostStudyStatus,input ={0},from ip={1}",
                                input, Request.HttpContext.Connection.RemoteIpAddress);
                var found    = false;
                var identity = string.Empty;
                foreach (var a in tokens)
                {
                    if (a.Token == inputRequest.Token)
                    {
                        identity = a.Identity;
                        found    = true;
                        break;
                    }
                }
                if (!found)
                {
                    Log.Error("InspectPostStudyStatus,{0},token={1}",
                              Global.Status[responseCode.TokenError].Description, inputRequest.Token);
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.TokenError].StatusCode,
                        Description = Global.Status[responseCode.TokenError].Description
                    });
                }
                var cryptographicid = CryptographyHelpers.StudyEncrypt(identity);
                var theuser         = _db1.User.FirstOrDefault(async => async.Identity == identity || async.Identity == cryptographicid);
                //  var theuser = _db1.User.FirstOrDefault(async => async.Identity == identity);
                if (theuser == null)
                {
                    Log.Error("InspectPostStudyStatus,{0},identity={1}",
                              Global.Status[responseCode.InvalidIdentiy].Description, identity);
                    return(new CommonResponse
                    {
                        StatusCode = Global.Status[responseCode.InvalidIdentiy].StatusCode,
                        Description = Global.Status[responseCode.InvalidIdentiy].Description
                    });
                }

                var studylog = string.Format("{0},{1},{2}", inputRequest.CourseTitle, inputRequest.StartTime, inputRequest.EndTime);

                if (theuser.Startdate == null)
                {
                    theuser.Startdate = DateTime.Now;
                    theuser.Studylog  = studylog;
                    Log.Information("InspectPostStudyStatus,Startdate ={0},from ip={1}",
                                    "uninitiated", Request.HttpContext.Connection.RemoteIpAddress);
                    //  theuser.Studylog = string.Format("{0},{1},{2}", inputRequest.CourseTitle, inputRequest.StartTime, inputRequest.EndTime);
                }
                else
                {
                    //  var slog=string.Format("-{0}", studylog);
                    if (!string.IsNullOrEmpty(theuser.Studylog))
                    {
                        if (!theuser.Studylog.Contains(studylog))
                        {
                            theuser.Studylog += string.Format("-{0}", studylog);
                        }
                        else
                        {
                            Log.Information("InspectPostStudyStatus,duplicate submit, discarded ={0},from ip={1}",
                                            "", Request.HttpContext.Connection.RemoteIpAddress);
                        }
                    }
                    else
                    {
                        theuser.Studylog = studylog;
                    }
                }

                if (theuser.Studylog.Length < 500)
                {
                    theuser.Syncdate = DateTime.Now;
                    _db1.SaveChanges();
                }
                if (!string.IsNullOrEmpty(inputRequest.CourseTitle))
                {
                    if (inputRequest.Pictures != null)
                    {
                        var date = DateTime.Today;
                        //   var dir = string.Format("{0}{1}{2}", date.Year, date.Month, date.Day);
                        var subfpath = identity;
                        if (!string.IsNullOrEmpty(theuser.Photofile))
                        {
                            subfpath = theuser.Photofile;
                        }
                        var fpath = Path.Combine(Global.LogPhotoPath, subfpath);
                        if (!Directory.Exists(fpath))
                        {
                            Directory.CreateDirectory(fpath);
                        }

                        var fname = Path.Combine(fpath, inputRequest.StartTime.ToString() + inputRequest.EndTime.ToString() + ".zip");
                        //     Log.Information("filename is: {0}", fname);
                        System.IO.File.WriteAllBytes(fname, inputRequest.Pictures);
                    }
                }

                return(new CommonResponse
                {
                    StatusCode = Global.Status[responseCode.ok].StatusCode,
                    Description = Global.Status[responseCode.ok].Description,
                });
            }
            catch (Exception ex)
            {
                Log.Error("InspectPostStudyStatus,{0},exception={1}",
                          Global.Status[responseCode.ProgramError].Description, ex);
                return(new CommonResponse
                {
                    StatusCode = Global.Status[responseCode.ProgramError].StatusCode,
                    Description = Global.Status[responseCode.ProgramError].Description
                });
            }
        }
Exemple #26
0
 public void Init()
 {
     CryptographyHelpers.CreateRSAKeyPair(out cStrPrivateKey,
         out cStrPublicKey,
         true);
 }
Exemple #27
0
        public void Generate(Stream outputStream)
        {
            // Implementation borrows heavily from UnusualInputTests.

            const string cpixPrefix    = "aa";
            const string pskcPrefix    = "bb";
            const string xmlencPrefix  = "cc";
            const string xmldsigPrefix = "dd";
            const string xsiPrefix     = "ee";
            const string xsdPrefix     = "ff";

            // We create a blank document that predefines the unusual namespaces prefixes.
            var xmlDocument = new XmlDocument();

            xmlDocument.AppendChild(xmlDocument.CreateElement(cpixPrefix, "CPIX", Constants.CpixNamespace));

            // We delcare a default namespace that will not be used for anything.
            var attribute = xmlDocument.CreateAttribute(null, "xmlns", Constants.XmlnsNamespace);

            attribute.Value = "⚽";
            xmlDocument.DocumentElement.Attributes.Append(attribute);

            XmlHelpers.DeclareNamespace(xmlDocument.DocumentElement, xmldsigPrefix, Constants.XmlDigitalSignatureNamespace);
            XmlHelpers.DeclareNamespace(xmlDocument.DocumentElement, xmlencPrefix, Constants.XmlEncryptionNamespace);
            XmlHelpers.DeclareNamespace(xmlDocument.DocumentElement, pskcPrefix, Constants.PskcNamespace);
            XmlHelpers.DeclareNamespace(xmlDocument.DocumentElement, xsiPrefix, "http://www.w3.org/2001/XMLSchema-instance");
            XmlHelpers.DeclareNamespace(xmlDocument.DocumentElement, xsdPrefix, "http://www.w3.org/2001/XMLSchema");

            var buffer = new MemoryStream();

            xmlDocument.Save(buffer);

            buffer.Position = 0;
            // Loading the blank document means we will now use the above prefixes.
            var document = CpixDocument.Load(buffer);

            const string complexLabel = "滆 柦柋牬 趉軨鄇 鶊鵱, 緳廞徲 鋑鋡髬 溮煡煟 綡蒚";

            document.ContentKeys.Add(new ContentKey
            {
                Id         = new Guid("152ae2e0-f455-486e-81d1-6df5fc5d7179"),
                Value      = Convert.FromBase64String("B+DoDP4r/j1NEr7b2aKXlw=="),
                ExplicitIv = Convert.FromBase64String("7qFwxoV85KBUNVXw8rgY3w==")
            });
            document.ContentKeys.Add(new ContentKey
            {
                Id         = new Guid("0cbe1c84-5c54-4ce8-8893-ff77f7d793e1"),
                Value      = Convert.FromBase64String("CedOXHsXc3xQ+HQuJOJZ+g=="),
                ExplicitIv = Convert.FromBase64String("zm4oYmRJWbLPrqXnhFS00w==")
            });
            document.ContentKeys.Add(new ContentKey
            {
                Id         = new Guid("486a8d08-29f7-42f5-9a9a-a1ab9b0685ad"),
                Value      = Convert.FromBase64String("ADq3douHS0QrY1omNB1njA=="),
                ExplicitIv = Convert.FromBase64String("wS4WCf4LgOe45BuG/qv5LA==")
            });
            document.ContentKeys.Add(new ContentKey
            {
                Id         = new Guid("84044421-a871-4999-8931-289aa6f4a607"),
                Value      = Convert.FromBase64String("JlZWL6tfkh6e8k9U1IOC8A=="),
                ExplicitIv = Convert.FromBase64String("9tlEFBcaX2S8/tfgQw9vAQ==")
            });

            DrmSignalingHelpers.AddDefaultSignalingForAllKeys(document);

            document.Recipients.Add(new Recipient(TestHelpers.Certificate1WithPublicKey));
            document.Recipients.Add(new Recipient(TestHelpers.Certificate2WithPublicKey));

            document.UsageRules.Add(new UsageRule
            {
                KeyId = document.ContentKeys.First().Id,

                AudioFilters = new[]
                {
                    new AudioFilter
                    {
                        MinChannels = 1,
                        MaxChannels = 2
                    },
                    new AudioFilter
                    {
                        MinChannels = 8,
                        MaxChannels = 10
                    }
                },
                BitrateFilters = new[]
                {
                    new BitrateFilter
                    {
                        MinBitrate = 1000,
                        MaxBitrate = 5 * 1000 * 1000
                    },
                    new BitrateFilter
                    {
                        MinBitrate = 10 * 1000 * 1000,
                        MaxBitrate = 32 * 1000 * 1000
                    }
                },
                LabelFilters = new[]
                {
                    new LabelFilter("EncryptedStream"),
                    new LabelFilter("CencStream"),
                    new LabelFilter(complexLabel),
                }
            });

            document.UsageRules.Add(new UsageRule
            {
                KeyId = document.ContentKeys.Last().Id,

                BitrateFilters = new[]
                {
                    new BitrateFilter
                    {
                        MinBitrate = 1000,
                        MaxBitrate = 5 * 1000 * 1000
                    },
                    new BitrateFilter
                    {
                        MinBitrate = 10 * 1000 * 1000,
                        MaxBitrate = 32 * 1000 * 1000
                    }
                },
                LabelFilters = new[]
                {
                    new LabelFilter("EncryptedStream"),
                    new LabelFilter("CencStream"),
                    new LabelFilter(complexLabel),
                },
                VideoFilters = new[]
                {
                    new VideoFilter
                    {
                        MinPixels          = 1000,
                        MaxPixels          = 1920 * 1080,
                        MinFramesPerSecond = 10,
                        MaxFramesPerSecond = 30,
                        WideColorGamut     = false,
                        HighDynamicRange   = true,
                    },
                    new VideoFilter
                    {
                        MinPixels          = 1000,
                        MaxPixels          = 4096 * 4096,
                        MinFramesPerSecond = 30,
                        MaxFramesPerSecond = 200,
                        WideColorGamut     = false,
                        HighDynamicRange   = false,
                    }
                }
            });

            // Save the XML, using funny prefixes and with complex data.
            buffer.SetLength(0);
            document.Save(buffer);

            // Now pretty-print the XML.
            var formattedStream = new MemoryStream();

            buffer.Position = 0;
            XmlHelpers.PrettyPrintXml(buffer, formattedStream);
            buffer = formattedStream;

            // Now modify the element IDs to be signed, sign the document, add comments and save as UTF-16.
            xmlDocument = new XmlDocument();
            xmlDocument.PreserveWhitespace = true;

            buffer.Position = 0;
            xmlDocument.Load(buffer);

            var namespaces = XmlHelpers.CreateCpixNamespaceManager(xmlDocument);

            const string recipientsId  = "id-for-recipients----";
            const string contentKeysId = "_id_for_content_keys";
            const string drmSystemsId  = "_id_for_drm_systems";
            const string usageRulesId  = "a.0a.0a.0a.0a.0a.a0.0a0.0404040......";

            UnusualInputTests.SetElementId(xmlDocument, namespaces, "/cpix:CPIX/cpix:DeliveryDataList", recipientsId);
            UnusualInputTests.SetElementId(xmlDocument, namespaces, "/cpix:CPIX/cpix:ContentKeyList", contentKeysId);
            UnusualInputTests.SetElementId(xmlDocument, namespaces, "/cpix:CPIX/cpix:DRMSystemList", drmSystemsId);
            UnusualInputTests.SetElementId(xmlDocument, namespaces, "/cpix:CPIX/cpix:ContentKeyUsageRuleList", usageRulesId);

            CryptographyHelpers.SignXmlElement(xmlDocument, recipientsId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(xmlDocument, contentKeysId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(xmlDocument, drmSystemsId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(xmlDocument, usageRulesId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(xmlDocument, usageRulesId, TestHelpers.Certificate2WithPrivateKey);
            CryptographyHelpers.SignXmlElement(xmlDocument, "", TestHelpers.Certificate1WithPrivateKey);

            // Add comments everywhere.
            namespaces = XmlHelpers.CreateCpixNamespaceManager(xmlDocument);

            UnusualInputTests.AddCommentAsChild(xmlDocument.DocumentElement);

            UnusualInputTests.AddCommentAsChild((XmlElement)xmlDocument.SelectSingleNode("/cpix:CPIX/cpix:DeliveryDataList", namespaces));
            UnusualInputTests.AddCommentAsChild((XmlElement)xmlDocument.SelectSingleNode("/cpix:CPIX/cpix:ContentKeyList", namespaces));
            UnusualInputTests.AddCommentAsChild((XmlElement)xmlDocument.SelectSingleNode("/cpix:CPIX/cpix:DRMSystemList", namespaces));
            UnusualInputTests.AddCommentAsChild((XmlElement)xmlDocument.SelectSingleNode("/cpix:CPIX/cpix:ContentKeyUsageRuleList", namespaces));

            UnusualInputTests.AddCommentAsChild((XmlElement)xmlDocument.SelectSingleNode("/cpix:CPIX/cpix:DeliveryDataList/cpix:DeliveryData", namespaces));
            UnusualInputTests.AddCommentAsChild((XmlElement)xmlDocument.SelectSingleNode("/cpix:CPIX/cpix:ContentKeyList/cpix:ContentKey", namespaces));
            UnusualInputTests.AddCommentAsChild((XmlElement)xmlDocument.SelectSingleNode("/cpix:CPIX/cpix:DRMSystemList/cpix:DRMSystem", namespaces));
            UnusualInputTests.AddCommentAsChild((XmlElement)xmlDocument.SelectSingleNode("/cpix:CPIX/cpix:ContentKeyUsageRuleList/cpix:ContentKeyUsageRule", namespaces));

            // Save the signed document as UTF-16.
            using (var writer = XmlWriter.Create(outputStream, new XmlWriterSettings
            {
                Encoding = Encoding.Unicode,
                CloseOutput = false
            }))
            {
                xmlDocument.Save(writer);
            }

            // Phew. That's enough for now.
        }
Exemple #28
0
 /// <summary>
 /// Randomises the activationm code, called on construction
 /// </summary>
 /// <param name="iLength">The length in characters of the newly generated activation code</param>
 public void RandomiseActivationCode(Int32 iLength)
 {
     ActivationCode = CryptographyHelpers.RandomString(iLength);
 }
Exemple #29
0
        public void SignAndLoadAndSave_DocumentWithWhitespaceAndIndentation_DoesNotBreakSignatures()
        {
            // Signatures are sensitive to even whitespace changes. While this library deliberately avoids generating
            // whitespace to keep it simple, we cannot assume that all input is without whitespace.
            // The library must be capable of preserving signed parts of existing documents that contain whitespace.

            var cpixStream = GenerateNontrivialCpixStream();

            // Now create a nicely formatted copy.
            var formattedCpixStream = new MemoryStream();

            XmlHelpers.PrettyPrintXml(cpixStream, formattedCpixStream);

            // Now sign it!
            var document = new XmlDocument();

            document.PreserveWhitespace = true;

            formattedCpixStream.Position = 0;
            document.Load(formattedCpixStream);

            // Note that the collections are not given IDs as they were not signed on save.
            // We need to manually give them IDs. That's fine - we can also verify that we have no ID format dependencies!
            var namespaces = XmlHelpers.CreateCpixNamespaceManager(document);

            const string recipientsId  = "id-for-recipients----";
            const string contentKeysId = "_id_for_content_keys";
            const string usageRulesId  = "a.0a.0a.0a.0a.0a.a0.0a0.0404040......";

            SetElementId(document, namespaces, "/cpix:CPIX/cpix:DeliveryDataList", recipientsId);
            SetElementId(document, namespaces, "/cpix:CPIX/cpix:ContentKeyList", contentKeysId);
            SetElementId(document, namespaces, "/cpix:CPIX/cpix:ContentKeyUsageRuleList", usageRulesId);

            CryptographyHelpers.SignXmlElement(document, recipientsId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(document, contentKeysId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(document, usageRulesId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(document, usageRulesId, TestHelpers.Certificate2WithPrivateKey);
            CryptographyHelpers.SignXmlElement(document, "", TestHelpers.Certificate1WithPrivateKey);

            // Okay, that's fine. Save!
            var signedCpixStream = new MemoryStream();

            using (var writer = XmlWriter.Create(signedCpixStream, new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                CloseOutput = false
            }))
            {
                document.Save(writer);
            }

            signedCpixStream.Position = 0;

            // Now it should be a nice valid and signed CPIX document.
            var cpix = CpixDocument.Load(signedCpixStream);

            Assert.NotNull(cpix.SignedBy);
            Assert.Single(cpix.Recipients.SignedBy);
            Assert.Single(cpix.ContentKeys.SignedBy);
            Assert.Equal(2, cpix.UsageRules.SignedBy.Count());

            // And save/load should preserve all the niceness.
            cpix = TestHelpers.Reload(cpix);

            Assert.NotNull(cpix.SignedBy);
            Assert.Single(cpix.Recipients.SignedBy);
            Assert.Single(cpix.ContentKeys.SignedBy);
            Assert.Equal(2, cpix.UsageRules.SignedBy.Count());

            // And, of course, the data should still be there.
            Assert.Equal(2, cpix.ContentKeys.Count);
            Assert.Equal(2, cpix.Recipients.Count);
            Assert.Equal(2, cpix.UsageRules.Count);

            // No exception? Success!
        }
Exemple #30
0
        public loginresponse login(string name, string identify, string phone, businessType businessType)
        {
            if (string.IsNullOrEmpty(identify) || identify == "undefined")
            {
                return(new loginresponse {
                    status = responseStatus.iderror
                });
            }
            if (string.IsNullOrEmpty(name) || name == "undefined")
            {
                return(new loginresponse {
                    status = responseStatus.nameerror
                });
            }
            if (string.IsNullOrEmpty(phone) || phone == "undefined")
            {
                return(new loginresponse {
                    status = responseStatus.phoneerror
                });
            }
            if (businessType == businessType.unknown)
            {
                return(new loginresponse {
                    status = responseStatus.businesstypeerror
                });
            }

            var btype = (short)businessType;
            //  var picsl = new List<short>();
            var token     = GetToken();
            var photofile = string.Empty;
            var response  = new loginresponse
            {
                status         = responseStatus.ok, blacklist = false,
                businessstatus = businessstatus.unknown,
                submitted      = false,
                content        = "unknown",
                token          = token,
                //   okpic = picsl.ToArray()
            };
            var encryptedIdentity = CryptographyHelpers.StudyEncrypt(identify);

            try
            {
                if (businessType == businessType.overage)
                {
                    var idl = identify.Length;
                    if (idl == 18)//
                    {
                        var year  = int.Parse(identify.Substring(6, 4));
                        var month = int.Parse(identify.Substring(10, 2));
                        var day   = int.Parse(identify.Substring(12, 2));
                        var birth = new DateTime(year, month, day);
                        if (birth.AddYears(60) > DateTime.Now)
                        {
                            return new loginresponse {
                                       status = responseStatus.forbidden
                            }
                        }
                        ;
                    }
                    else if (idl == 15)
                    {
                        var year  = int.Parse(identify.Substring(6, 2)) + 1900;
                        var month = int.Parse(identify.Substring(8, 2));
                        var day   = int.Parse(identify.Substring(10, 2));
                        var birth = new DateTime(year, month, day);
                        if (birth.AddYears(60) > DateTime.Now)
                        {
                            return new loginresponse {
                                       status = responseStatus.forbidden
                            }
                        }
                        ;
                    }
                }

                var theuser = _db1.Aouser.FirstOrDefault(i => i.Identity == encryptedIdentity);
                if (theuser == null)
                {
                    photofile = token;
                    _db1.Aouser.Add(new Aouser
                    {
                        Identity  = encryptedIdentity,
                        Blacklist = false,
                        Photofile = token,
                        Phone     = phone,
                        Name      = name
                    });
                    _db1.SaveChanges();
                }
                else
                {
                    photofile = theuser.Photofile;
                }

                var business = _db1.Business.FirstOrDefault(i => i.Identity == encryptedIdentity &&
                                                            i.Businesstype == (short)businessType);
                if (business == null)
                {
                    _db1.Business.Add(new Business
                    {
                        Identity     = encryptedIdentity,
                        Businesstype = (short)businessType,
                        Completed    = false,
                        Time         = DateTime.Now,
                    });
                    _db1.SaveChanges();
                }
                else
                {
                    var pics = _db1.Businesspic.Where(c => c.Businesstype == btype &&
                                                      c.Identity == encryptedIdentity &&
                                                      c.Uploaded == true);
                    response.businessstatus = (businessstatus)business.Status;
                    response.finish_time    = business.Finishtime;
                    response.wait_time      = business.Waittime;
                    response.process_time   = business.Processtime;
                    if (!string.IsNullOrEmpty(business.Reason))
                    {
                        response.content = business.Reason;
                    }
                    if (pics.Count() < global.businesscount[businessType] || response.businessstatus == businessstatus.failure)
                    {
                        //foreach (var a in pics)
                        //{
                        //    picsl.Add(a.Pictype);
                        //}
                        //response.okpic = picsl.ToArray();
                        if (response.businessstatus == businessstatus.failure)
                        {
                            response.submitted = true;
                        }
                    }
                    else
                    {
                        response.submitted = true;
                    }
                }
                if (theuser != null && theuser.Blacklist == true)
                {
                    response.blacklist = true;
                }
            }
            catch (Exception ex)
            {
                _log.LogError("login -- process error:{0}", ex.Message);
            }

            try
            {
                var redisdb = highlevel.redis.GetDatabase();
                redisdb.StringSet(token, JsonConvert.SerializeObject(new idinfo {
                    Identity = encryptedIdentity, photofile = photofile, businessType = businessType
                }));
                redisdb.KeyExpire(token, TimeSpan.FromDays(30));
            }
            catch (Exception ex)
            {
                _log.LogError("redis key process error:{0}", ex.Message);
            }

            var found = false;

            foreach (var a in global.tokens)
            {
                if (a.idinfo.Identity == encryptedIdentity && a.idinfo.businessType == businessType)
                {
                    a.Token = token;
                    found   = true;
                    break;
                }
            }
            if (!found)
            {
                global.tokens.Add(new Ptoken {
                    idinfo = new idinfo {
                        Identity = encryptedIdentity, photofile = photofile, businessType = businessType
                    }, Token = token
                });
            }
            try
            {
                var he = Request.Host.ToString();
                foreach (var a in Request.Headers)
                {
                    he += "--" + a.Key + "=" + a.Value;
                }
                Task.Run(() => highlevel.LogRequest(he + name + phone + encryptedIdentity + JsonConvert.SerializeObject(response),
                                                    "login", Request.HttpContext.Connection.RemoteIpAddress.ToString(), (short)businessType));
            }
            catch (Exception ex) { _log.LogError("dblog error:", ex); }
            return(response);
        }