public CryptoMirror(string root, char letter, string label)
 {
     this.root = root;
     this.mountPoint = letter + mountPointEnd;
     this.label = label;
     encryptor = new Encryptor(Encoding.Default.GetBytes(internalKey));
     Options = new DokanOptions();
     Options.DebugMode = false;
     Options.MountPoint = mountPoint;
     Options.ThreadCount = threadCount;
     Options.VolumeLabel = label;
 }
Beispiel #2
0
 public SecureBox()
 {
     appSettings = new XmlAppSettings(appDirectory);
     encryptor = new Encryptor(Encoding.Default.GetBytes(internalKey));
     threads = new Dictionary<char, Thread>();
     Initialize();
 }
Beispiel #3
0
 public ActionResult Create(User user)
 {
     if (ModelState.IsValid)
     {
         user.Creation = DateTime.Now;
         string source = user.Password;
         using (MD5 md5Hash = MD5.Create())
         {
             Encryptor enc = new Encryptor();
             string hash = enc.GetMd5Hash(md5Hash, source);
             if (enc.VerifyMd5Hash(md5Hash, source, hash))
             {
                 user.Password = hash;
                 db.Users.AddObject(user);
                 db.SaveChanges();
                 return RedirectToAction("Index");
             }
             else
             {
                 ViewBag.Status = new SelectList((new UserViewModel()).GetStatus(), "Value", "Text", user.Status);
                 return View(user);
             }
         }
     }
     ViewBag.Status = new SelectList((new UserViewModel()).GetStatus(), "Value", "Text", user.Status);
     return View(user);
 }
        public async Task incorrect_encrypted_string_format_should_throw()
        {
            const string textToEncrypt = "some text of mine";
            var encryptor = new Encryptor("my key");

            var decryptedText = encryptor.Decrypt("This is not the correct format");
        }
        /// <summary>
        /// Creates a new ProcessedPacket instance.
        /// </summary>
        /// <param name="ID">The ID of the packet.</param>
        /// <param name="Encrypted">Is this packet encrypted?</param>
        /// <param name="Length">The length of the packet.</param>
        /// <param name="EncKey">The encryptionkey, can be null if the packet isn't encrypted.</param>
        /// <param name="DataBuffer">The databuffer containing the packet.</param>
        public ProcessedPacket(byte ID, bool Encrypted, bool VariableLength, ushort Length, Encryptor Enc, byte[] DataBuffer)
            : base(ID, Length, DataBuffer)
        {
            byte Opcode = (byte)this.ReadByte();

            if (VariableLength)
                this.m_Length = (ushort)this.ReadUShort();
            else
                this.m_Length = Length;

            if(Encrypted)
            {
                this.DecryptedLength = (ushort)this.ReadUShort();

                //Length should be at least the length of the decrypted data.
                if ((m_Length - (int)PacketHeaders.ENCRYPTED) < this.DecryptedLength)
                {
                    //Something's gone haywire, throw an error...
                    throw new PacketProcessingException("DecryptedLength didn't match packet's length!\n" +
                    Convert.ToBase64String(this.m_BaseStream.ToArray()));
                }

                DecryptionArgsContainer Args = Enc.GetDecryptionArgsContainer();
                Args.UnencryptedLength = DecryptedLength;

                this.m_BaseStream = Enc.DecryptPacket(this, Args);
                this.m_BaseStream.Position = 0;
                this.m_Reader = new System.IO.BinaryReader(m_BaseStream);
            }
        }
        protected override void Context()
        {
            base.Context();

              TestType = new SaltedEncryptedString();
              Encryptor = new CryptographyFactory().CreateEncryptor();
        }
Beispiel #7
0
        private void encryptBtn_Click(object sender, EventArgs e)
        {
            Encryptor newEncryption = new Encryptor();
            string input = InputTextBox.Text;
            //checks there is something to encrypt
            if (input != "")
            {
                //if rot13
                if (rdbtnROT13.Checked)
                {
                    newEncryption.encryption = new ROT13Encryptor();
                    OutputTextBox.Text = newEncryption.EncryptInputText(input);

                }
                //if reverse string
                else if (rdbtnReverse.Checked)
                {
                    newEncryption.encryption = new ReverseString();
                    OutputTextBox.Text = newEncryption.EncryptInputText(input);
                }
                //if neither selected
                else
                {
                    MessageBox.Show("Please select an encryption type!");

                }
            }
            else
            {
                MessageBox.Show("Please enter text to encrypt!");
            }
        }
Beispiel #8
0
        /// <summary>
        /// プログラムのエントリーポイント。
        /// </summary>
        /// <param name="args">コマンドライン引数。</param>
        public static void Main(string[] args)
        {
            var password = "******";
            var serializer = new XmlSerializer(typeof(UserMan));
            UserMan userMan;

            // XML ファイルの内容をオブジェクトに読み込みます。
            using (var userManStream = new FileStream("UserMan.xml", FileMode.Open, FileAccess.Read))
            {
                userMan = serializer.Deserialize(userManStream) as UserMan;
                foreach (var user in userMan.UserList)
                {
                    Console.WriteLine("User ID: {0}", user.UserID);
                    Console.WriteLine("User Name: {0}", user.UserName);
                }
            }
            // オブジェクトを暗号化して保存します。
            using (var encryptor = new Encryptor("userMan.xml.enc", password))
            {
                serializer.Serialize(encryptor.EncryptStream, userMan);
            }
            // 暗号化したファイルを復号化して、オブジェクトに読み込みます。
            using (var decryptor = new Decryptor("UserMan.xml.enc", password))
            {
                UserMan decryptedUserMan = serializer.Deserialize(decryptor.DecryptStream) as UserMan;
                foreach (var user in decryptedUserMan.UserList)
                {
                    Console.WriteLine("User ID: {0}", user.UserID);
                    Console.WriteLine("User Name: {0}", user.UserName);
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Encrypts a string.
        /// </summary>
        /// <param name="Text">The string should be encrypted.</param>
        /// <param name="Key">The 8-bit string for encryption.</param>
        /// <returns>The encrypted string.</returns>
		public string Encrypt(string Text, string Key)
		{
			if(Key.Length != 8)
				throw new Exception("Key must be a 8-bit string!");

			byte[] IV = null;
			byte[] cipherText = null;
			byte[] key = null;

			try
			{
				Encryptor enc = new Encryptor(EncryptionAlgorithm.Des);
				byte[] plainText = Encoding.ASCII.GetBytes(Text);

				key = Encoding.ASCII.GetBytes(Key);
				IV = Encoding.ASCII.GetBytes("init vec");		// "init vec is big."

				enc.IV = IV;

				cipherText = enc.Encrypt(plainText, key);
				IV = enc.IV;
				key = enc.Key;

			}
			catch(Exception ex)
			{
				throw new Exception("Exception while encrypting. " + ex.Message);
			}

			return Convert.ToBase64String(cipherText);
		}
 public HttpResponseMessage EncriptarPassword(string password)
 {
     Encryptor encryptor = new Encryptor();
     byte[] cipherText = encryptor.encrypt(password);
     string contrasenaEncriptada = Convert.ToBase64String(cipherText);
     return Request.CreateResponse(HttpStatusCode.OK, contrasenaEncriptada);
 }
        public async Task incorrect_encrypted_value_should_throw()
        {
            const string textToEncrypt = "some text of mine";
            var encryptor = new Encryptor("my key");

            //correct format, but not cryptographically correct
            var decryptedText = encryptor.Decrypt("c29tZXRoaW5n:c29tZXRoaW5n");
        }
        public void Salt_Eight_Bytes_Long()
        {
            var encryptor = new Encryptor();

            var result = encryptor.GetSalt();

            Assert.AreEqual(8, result.Length);
        }
Beispiel #13
0
      public void TestDecryptWithWrongKey()
      {
         const string TEXT_TO_ENCRYPT = "TEXT_TO_ENCRYPT";
         const string KEY = "Secret";

         Encryptor encryptor = new Encryptor();
         byte[] encrypted = encryptor.Encrypt(Encoding.Unicode.GetBytes(TEXT_TO_ENCRYPT), KEY);

         byte[] decrypted = encryptor.Decrypt(encrypted, "WrongKey");
      }
Beispiel #14
0
        public static void Test1()
        {
            Encryptor encryptor = new Encryptor("foobar!");

            for (int i = 0; i < 256; i++)
            {
                Debug.Assert(encryptor.encryptTable[i] == target[0][i]);
                Debug.Assert(encryptor.decryptTable[i] == target[1][i]);
            }
        }
        public void Encrypt_Password()
        {
            var password = "******";
            var salt = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
            var encryptor = new Encryptor();

            var result = encryptor.GetPassword(salt, password);

            Assert.AreEqual(50, result.Length);
        }
Beispiel #16
0
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                bool changePasswordSucceeded = true;
                try
                {
                    if (ModelState.IsValid && model.OldPassword != null)
                    {
                        int id = ((Session)Session["Session"]).UserID;
                        User oldUser = db.Users.Single(u => u.UserID == id);

                        string source = model.OldPassword;
                        using (MD5 md5Hash = MD5.Create())
                        {
                            Encryptor enc = new Encryptor();
                            string hash = enc.GetMd5Hash(md5Hash, source);
                            if (enc.VerifyMd5Hash(md5Hash, source, hash))
                            {
                                if (hash == oldUser.Password)
                                {
                                    source = model.NewPassword;
                                    hash = enc.GetMd5Hash(md5Hash, source);
                                    if (enc.VerifyMd5Hash(md5Hash, source, hash))
                                    {
                                        oldUser.Password = hash;
                                        db.Users.Attach(oldUser);
                                        db.ObjectStateManager.ChangeObjectState(oldUser, EntityState.Modified);
                                        db.SaveChanges();
                                        changePasswordSucceeded = true;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public async Task encrypted_string_should_be_able_to_decrypt()
        {
            const string textToEncrypt = "some text of mine";
            var encryptor = new Encryptor("my key");

            var encryptedText = encryptor.Encrypt(textToEncrypt);
            Assert.AreNotEqual(textToEncrypt, encryptedText);

            var decryptedText = encryptor.Decrypt(encryptedText);
            Assert.AreEqual(textToEncrypt, decryptedText);
        }
        public async Task short_bytes_should_be_padded()
        {
            var data = new byte[] { 0xAA };
            var salt = new byte[]{0xAA};
            var encryptor = new Encryptor("my key");

            var encryptedBytes = encryptor.Encrypt(data, salt);
            var decryptedData = encryptor.Decrypt(encryptedBytes, salt);

            Assert.IsTrue(data.SequenceEqual(decryptedData));
        }
 private void MenuItem_Click(object sender, RoutedEventArgs e)
 {
     var encryptor = new Encryptor();
     if (encryptor.ShowDialog().Value)
     {
         EC2.Provider.AccessKey = AwsConfiguration.AccessKey;
         EC2.Provider.SecretKey = AwsConfiguration.SecretKey;
         SetStatus(null);
         menu1.Visibility = Visibility.Hidden;
         Title = AwsConfiguration.PCName;
     }
 }
        public static bool Login(string naam, string wachtwoord)
        {
            Gebruiker gebruiker = new Gebruiker{UserName=naam,Password=wachtwoord};

            Encryptor enc = new Encryptor(DarwinConfig.PrivateKey);
            MessageArgs msgArgs = new MessageArgs { username = gebruiker.UserName, password = gebruiker.Password };

            AanvraagMessage avMsg = new AanvraagMessage { method=DarwinConfig.Method,args=msgArgs};
            string strMsg = JsonConvert.SerializeObject(avMsg);
            string encryptedMsg = enc.Encrypt3DES(strMsg);

            Aanvraag deAanvraag = new Aanvraag {
                appId=DarwinConfig.AppId,
                message=encryptedMsg
            };
            string aanvraagText = JsonConvert.SerializeObject(deAanvraag);

            //vraag sturen
            var httpwebrequest = (HttpWebRequest)WebRequest.Create(DarwinConfig.DarwinURL);
            httpwebrequest.Method = "POST";
            //een stream maken om er in te kunnen schrijven
            Stream dataStream = httpwebrequest.GetRequestStream();
            TextWriter tw = new StreamWriter(dataStream);
            tw.WriteLine("contents=" + aanvraagText);
            tw.Flush();
            tw.Close();

            //antwoord van Darwin
            HttpWebResponse response = (HttpWebResponse)httpwebrequest.GetResponse();

            //inlezen in tekst
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string responseText = sr.ReadToEnd();

            //antwoord object uit die tekst maken
            Antwoord jsonAntwoord = JsonConvert.DeserializeObject<Antwoord>(responseText);

            //isRegisteredUser betekent dat gebruiker een "Darwin" gebruiker is
            bool isRegisteredUser = false;
            if (jsonAntwoord.status == "OK")
            {
                string plainText = enc.Decrypt3DES(jsonAntwoord.response);

                //andere manier om een json string om te zetten in een Json-object
                JObject o = JObject.Parse(plainText);
                if (o["exception"] == null && o["id"] != null)
                {
                    isRegisteredUser = true;
                }

            }
            return isRegisteredUser;
        }
 private void Closed_Click(object sender, RoutedEventArgs e)
 {
     Encryptor encryptor = new Encryptor(Password.Text);
     string str = encryptor.EncryptStr;
     Configuration currentConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     currentConfig.AppSettings.Settings["Token"].Value = Token.Text;
     currentConfig.AppSettings.Settings["User"].Value = User.Text;
     currentConfig.AppSettings.Settings["Password"].Value = str;
     currentConfig.AppSettings.Settings["Domian"].Value = Domian.Text;
     currentConfig.Save(ConfigurationSaveMode.Modified, true);
     ConfigurationManager.RefreshSection("appSettings");
     this.Close();
 }
Beispiel #22
0
      public void TestEncryptAndThenDecrypt()
      {
         const string TEXT_TO_ENCRYPT = "TEXT_TO_ENCRYPT";
         const string KEY = "Secret";
         
         Encryptor encryptor = new Encryptor();
         byte[] encrypted = encryptor.Encrypt(Encoding.Unicode.GetBytes(TEXT_TO_ENCRYPT), KEY);

         byte[] decrypted = encryptor.Decrypt(encrypted, KEY);

         String decryptedString = Encoding.Unicode.GetString(decrypted);

         Assert.AreEqual(TEXT_TO_ENCRYPT, decryptedString);
      }
Beispiel #23
0
    protected void NfteDetailsView_DataBound(object sender, EventArgs e)
    {
        Encryptor enc = new Encryptor();

        TextBox netpayTextBox = (TextBox)NfteDetailsView.Rows[14].Cells[1].Controls[0];
        netpayTextBox.Text = enc.Decrypt(netpayTextBox.Text);

        TextBox grosspayTextBox = (TextBox)NfteDetailsView.Rows[15].Cells[1].Controls[0];
        grosspayTextBox.Text = enc.Decrypt(grosspayTextBox.Text);

        TextBox ctcTextBox = (TextBox)NfteDetailsView.Rows[16].Cells[1].Controls[0];
        ctcTextBox.Text = enc.Decrypt(ctcTextBox.Text);

        TextBox ctcmTextBox = (TextBox)NfteDetailsView.Rows[17].Cells[1].Controls[0];
        ctcmTextBox.Text = enc.Decrypt(ctcmTextBox.Text);
    }
Beispiel #24
0
        public static ITwitter From(string filename)
        {
            try
            {
                if (File.Exists(filename))
                {
                    var doc = XDocument.Load(filename);
                    var settings = doc.Element("twitter-info");
                    var encryptor = new Encryptor(ConsumerKey);
                    string token = encryptor.Decrypt(settings.Element("token").Value);
                    string secretToken = encryptor.Decrypt(settings.Element("secret-token").Value);

                    return new TwitterProxy(token, secretToken);
                }
                return new TwitterProxy();
            }
            catch (Exception)
            {
                return new TwitterProxy();
            }
        }
 static void Main(string[] args)
 {
     Encryptor encryptor;
     for (int encryptType = 0; encryptType < 3; encryptType++)
     {
         switch(encryptType)
         {
             case 0:
                 encryptor = new Encryptor(new Hash());
                 break;
             case 1:
                 encryptor = new Encryptor(new Symmetric());
                 break;
             case 2:
             default:
                 encryptor = new Encryptor(new Asymmetric());
                 break;
         }
         var result = encryptor.Encrypt("pasSW@rd");
         Console.WriteLine(result);
     }
     Console.Read();
 }
Beispiel #26
0
 public void SetPassword(IUser target, string password, bool ignorepolicy = false, string salt = null) {
     if (null == target) {
         throw new ArgumentNullException("target");
     }
     if (string.IsNullOrWhiteSpace(target.Login)) {
         throw new Exception("not login");
     }
     if (string.IsNullOrWhiteSpace(password)) {
         throw new Exception("no password");
     }
     var policy = GetPolicy(password);
     if (!ignorepolicy && !policy.Ok) {
         throw new Exception("Invalid password policy " + policy);
     }
     if (!string.IsNullOrWhiteSpace(salt)) {
         target.Salt = salt;
     }
     else {
         var e = new Encryptor();
         target.Salt = e.Encrypt(Guid.NewGuid() + "::" + target.Login + "::" + password).GetMd5();
     }
     var hash = GetHash(target, password);
     target.Hash = hash;
 }
Beispiel #27
0
 public static void Decode()
 {
     Console.WriteLine("Specify key file? (Leave blank if key.txt exists and is correct)");
     var keyfilename = Console.ReadLine();
     if (keyfilename == "")
     {
         keyfilename = "key";
     }
     Console.WriteLine("Specify message file? (Leave blank if cypher.txt exists and is correct)");
     var cypherfilename = Console.ReadLine();
     if (cypherfilename == "")
     {
         cypherfilename = "cypher";
     }
     var cypherfile = new FileObject();
     cypherfile.ReadFile(cypherfilename);
     var keyfile = new FileObject();
     keyfile.ReadFile(keyfilename);
     var decryptor = new Encryptor
                         {
                             Key = keyfile.MessageText,
                             Message = cypherfile.MessageText,
                             SpaceFlag = cypherfile.SpaceFlag
                             };
     var result = decryptor.DeCypherIt();
     Console.WriteLine(result);
     var messagefile = new FileObject
                           {
                               Id = Guid.NewGuid(),
                               Name ="message",
                               MessageFigure = "",
                               MessageText = result,
                               SpaceFlag = cypherfile.SpaceFlag
                           };
     messagefile.WriteFile();
 }
Beispiel #28
0
 public bool ValidateHash(string value, string hash, string key)
 {
     return(Encryptor.Validate(value, key, hash));
 }
Beispiel #29
0
        public static void listernet()
        {
            IPAddress   ipAddress   = IPAddress.Parse("0.0.0.0");
            TcpListener tcpListener = new TcpListener(ipAddress, (int)Service1.objectPassword["port"]);

            tcpListener.Start();
            Byte[] bytes = new Byte[256];

            while (true)
            {
                Socket socket = tcpListener.AcceptSocket();
                int    result = socket.Receive(bytes);

                ASCIIEncoding asen = new ASCIIEncoding();

                string str = asen.GetString(bytes);
                eventLog1.WriteEntry("str: " + str);
                try
                {
                    string msg        = "ERROR";
                    var    parametros = str.Split('|');
                    eventLog1.WriteEntry(parametros[1].ToString());

                    //SEMPRE PASSAR MAIS 1 PIPE PARA NA ODAR ERROR
                    //POS EM SOCKET A ULTIMA STRING EH \n\0\0\0\0\0\0\0
                    // echo "<password>|<get-session kill-session>|param2|" | nc <ip> <port>
                    if (parametros.Length == 0)
                    {
                        msg = "Use | para passar a string de parametros";
                    }

                    if (!Service1.objectPassword["password"].ToString().Equals(Encryptor.MD5Hash(parametros[0])))
                    {
                        msg = "Adicione o password na msg";
                    }

                    if (parametros[1].Equals("get-session"))
                    {
                        eventLog1.WriteEntry("get-session!");
                        string param2 = null;
                        if (!parametros[2].Equals(""))
                        {
                            param2 = parametros[2];
                        }

                        string output = runCmd("qwinsta", param2);
                        msg = output;
                    }

                    if (parametros[1].Equals("kill-session"))
                    {
                        eventLog1.WriteEntry("kill-session!");
                        string param2 = null;
                        if (!parametros[2].Equals(""))
                        {
                            param2 = parametros[2];
                        }
                        string output = runCmd("rwinsta", param2);
                        msg = output;
                    }

                    socket.Send(Encoding.ASCII.GetBytes(msg));
                }
                catch (Exception e)
                {
                    eventLog1.WriteEntry(e.Message);
                }
                finally
                {
                    socket.Close();
                }
            }
        }
Beispiel #30
0
        public void StandardEncryption()
        {
            FileStream file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-solrcell.docx");
            String     pass = "******";

            NPOIFSFileSystem nfs = new NPOIFSFileSystem(file);

            // Check the encryption details
            EncryptionInfo infoExpected = new EncryptionInfo(nfs);
            Decryptor      d            = Decryptor.GetInstance(infoExpected);
            bool           passed       = d.VerifyPassword(pass);

            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            MemoryStream bos = new MemoryStream();
            Stream       is1 = d.GetDataStream(nfs);

            IOUtils.Copy(is1, bos);
            is1.Close();
            nfs.Close();
            byte[] payloadExpected = bos.ToArray();

            // check that same verifier/salt lead to same hashes
            byte[] verifierSaltExpected = infoExpected.Verifier.Salt;
            byte[] verifierExpected     = d.GetVerifier();
            byte[] keySpec = d.GetSecretKey().GetEncoded();
            byte[] keySalt = infoExpected.Header.KeySalt;


            EncryptionInfo infoActual = new EncryptionInfo(
                EncryptionMode.Standard
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            Encryptor e = Encryptor.GetInstance(infoActual);

            e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null);

            CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifier, infoActual.Verifier.EncryptedVerifier);
            CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifierHash, infoActual.Verifier.EncryptedVerifierHash);

            // now we use a newly generated salt/verifier and check
            // if the file content is still the same

            infoActual = new EncryptionInfo(
                EncryptionMode.Standard
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            e = Encryptor.GetInstance(infoActual);
            e.ConfirmPassword(pass);

            POIFSFileSystem fs = new POIFSFileSystem();
            Stream          os = e.GetDataStream(fs);

            IOUtils.Copy(new MemoryStream(payloadExpected), os);
            os.Close();

            bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
            fs.WriteFileSystem(bos);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.ToArray());

            // FileOutputStream fos = new FileOutputStream("encrypted.docx");
            // IOUtils.Copy(bis, fos);
            // fos.Close();
            // bis.Reset();

            nfs          = new NPOIFSFileSystem(bis);
            infoExpected = new EncryptionInfo(nfs);
            d            = Decryptor.GetInstance(infoExpected);
            passed       = d.VerifyPassword(pass);
            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
            is1 = d.GetDataStream(nfs);
            IOUtils.Copy(is1, bos);
            is1.Close();
            nfs.Close();
            byte[] payloadActual = bos.ToArray();

            CollectionAssert.AreEqual(payloadExpected, payloadActual);
            //assertArrayEquals(payloadExpected, payloadActual);
        }
        private void BUY_CASH(HttpContext context)
        {
            try
            {
                if (context.Session["BUY_CASH"] == null || (DateTime.Now - (DateTime)context.Session["BUY_CASH"]).TotalMilliseconds > Constants.TIME_REQUEST)
                {
                    string    json        = context.Request.Form["json"];
                    decimal[] rulerAmount = { 20000000, 50000000, 100000000, 200000000, 500000000, 1000000000 };
                    if (!string.IsNullOrEmpty(json))
                    {
                        var jsonData = JsonConvert.DeserializeObject <AddMoneyAgencyEntity>(json);
                        if (jsonData != null)
                        {
                            Logs.SaveLog(JsonConvert.SerializeObject(jsonData));
                            if (string.IsNullOrEmpty(jsonData.agencyID))
                            {
                                result.status = Constants.NUMBER_CODE.DATA_NULL;
                                result.msg    = "Mã đại lý không được trống!";
                            }
                            else if (!rulerAmount.Contains(jsonData.amount))
                            {
                                result.status = Constants.NUMBER_CODE.AMOUNT_WRONG;
                                result.msg    = "Số tiền không hợp lệ!";
                            }
                            else
                            {
                                jsonData.IP          = UtilClass.GetIPAddress();
                                jsonData.creatorID   = accountInfo.AccountId;
                                jsonData.creatorName = accountInfo.UserName;

                                PayloadApi p = new PayloadApi()
                                {
                                    clientIP = UtilClass.GetIPAddress(),
                                    data     = Encryptor.EncryptString(JsonConvert.SerializeObject(jsonData), Constants.API_SECRETKEY)
                                };
                                var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "api/v1/Agency/AddMoneyAgency");
                                context.Response.Write(responseData);
                                return;
                            }
                        }
                        else
                        {
                            result.status = Constants.NUMBER_CODE.DATA_NULL;
                            result.msg    = "Thông tin không được để trống";
                        }
                    }
                }
                else
                {
                    result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER;
                    result.msg    = "Thao tác quá nhanh! vui lòng thử lại";
                }
            }
            catch (Exception ex)
            {
                Logs.SaveError("ERROR BUY_CASH: " + ex);
                result.status = Constants.NUMBER_CODE.ERROR_EX;
                result.msg    = Constants.NUMBER_CODE.ERROR_EX.ToString();
            }
            finally
            {
                context.Session["BUY_CASH"] = DateTime.Now;
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
Beispiel #32
0
 public string HashString(string text, string key)
 {
     return(Encryptor.HashString(text, key));
 }
Beispiel #33
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var dao    = new AccountValidation();
                var result = dao.Login(model.UserName, Encryptor.ToMD5(model.Password));  // Encrypt Password
                switch (result)
                {
                case 1:
                {
                    var user        = dao.GetById(model.UserName);   // Get User with UserName
                    var userSession = new UserLogin();               // Create a object consists of Id and UserName to store into session
                    userSession.UserId   = user.Id;
                    userSession.UserName = user.UserName;
                    Session.Add(Common.Constants.USER_SESSION, userSession);
                    //Session.Add(Common.Constants.USER_ROLE, user.IdRole);
                    if (model.RememberMe == true)
                    {
                        HttpCookie ckUsername = new HttpCookie("UserName");
                        ckUsername.Expires = DateTime.Now.AddMonths(6);
                        ckUsername.Value   = model.UserName;
                        Response.Cookies.Add(ckUsername);
                        HttpCookie ckPassword = new HttpCookie("Password");
                        ckPassword.Expires = DateTime.Now.AddMonths(6);
                        ckPassword.Value   = Encryptor.ToMD5(model.Password);
                        Response.Cookies.Add(ckPassword);
                    }
                    if (user.IdRole == "1" || user.IdRole == "2")
                    {
                        return(RedirectToAction("Index", "AdminHome", new { area = "Admin" }));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }

                case 0:
                {
                    ModelState.AddModelError("", "Account is not exit !");
                    break;
                }

                case -1:
                {
                    ModelState.AddModelError("", "Account was blocked !");
                    break;
                }

                case -2:
                {
                    ModelState.AddModelError("", "Password is incorrect !");
                    break;
                }

                default:
                {
                    ModelState.AddModelError("", "An error occurred !");
                    break;
                }
                }
            }
            return(View());
        }
Beispiel #34
0
            public int Predict(double[] features, int power, bool useRelinearizeInplace, bool useReScale, Stopwatch timePredictSum)
            {
                EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);

                if (power < 60)
                {
                    ulong polyModulusDegree = 8192;
                    parms.PolyModulusDegree = polyModulusDegree;
                    parms.CoeffModulus      = CoeffModulus.Create(polyModulusDegree, new int[] { 60, 40, 40, 60 });
                }
                else
                {
                    ulong polyModulusDegree = 16384;
                    parms.PolyModulusDegree = polyModulusDegree;
                    parms.CoeffModulus      = CoeffModulus.Create(polyModulusDegree, new int[] { 60, 60, 60, 60, 60, 60 });
                }
                //

                double scale = Math.Pow(2.0, power);

                SEALContext context = new SEALContext(parms);

                Console.WriteLine();

                KeyGenerator keygen     = new KeyGenerator(context);
                PublicKey    publicKey  = keygen.PublicKey;
                SecretKey    secretKey  = keygen.SecretKey;
                RelinKeys    relinKeys  = keygen.RelinKeys();
                var          galoisKeys = keygen.GaloisKeys();
                Encryptor    encryptor  = new Encryptor(context, publicKey);
                Evaluator    evaluator  = new Evaluator(context);
                Decryptor    decryptor  = new Decryptor(context, secretKey);

                CKKSEncoder encoder = new CKKSEncoder(context);

                ulong slotCount = encoder.SlotCount;

                Console.WriteLine($"Number of slots: {slotCount}");

                timePredictSum.Start();
                var featuresLength = features.Length;

                var plaintexts          = new Plaintext();
                var featuresCiphertexts = new Ciphertext();

                //Encode and encrypt features

                encoder.Encode(features, scale, plaintexts);
                encryptor.Encrypt(plaintexts, featuresCiphertexts);
                SvcUtilities.PrintScale(plaintexts, "featurePlaintext");
                SvcUtilities.PrintScale(featuresCiphertexts, "featurefEncrypted");



                // Handle SV
                var numOfrows    = _vectors.Length;
                var numOfcolumns = _vectors[0].Length;

                int numOfRotations = (int)Math.Ceiling(Math.Log2(numOfcolumns));
                //Console.WriteLine("**********************************    : "+ numOfRotations);
                var svPlaintexts = new Plaintext[numOfrows];

                //Encode SV
                for (int i = 0; i < numOfrows; i++)
                {
                    //for (int j = 0; j < numOfcolumns; j++)
                    //{
                    svPlaintexts[i] = new Plaintext();
                    encoder.Encode(_vectors[i], scale, svPlaintexts[i]);
                    SvcUtilities.PrintScale(svPlaintexts[i], "supportVectorsPlaintext" + i);
                    //}
                }
                // Prepare sum of inner product
                var sums = new Ciphertext[numOfcolumns];

                for (int i = 0; i < numOfcolumns; i++)
                {
                    sums[i] = new Ciphertext();
                }

                var kernels      = new Ciphertext[numOfrows];
                var decisionsArr = new Ciphertext[numOfrows];
                var coefArr      = new Plaintext [numOfrows];

                for (int i = 0; i < numOfrows; i++)
                {
                    kernels[i]      = new Ciphertext();
                    decisionsArr[i] = new Ciphertext();
                    coefArr[i]      = new Plaintext();
                }


                // Level 1
                for (int i = 0; i < numOfrows; i++)
                {
                    var ciphertexts = new List <Ciphertext>();

                    evaluator.MultiplyPlain(featuresCiphertexts, svPlaintexts[i], sums[i]);

                    for (int k = 1; k <= numOfRotations + 1 /*(int)encoder.SlotCount*/ / 2; k <<= 1)
                    {
                        Ciphertext tempCt = new Ciphertext();
                        evaluator.RotateVector(sums[i], k, galoisKeys, tempCt);
                        evaluator.AddInplace(sums[i], tempCt);
                    }


                    kernels[i] = sums[i];


                    evaluator.NegateInplace(kernels[i]);

                    if (useRelinearizeInplace)
                    {
                        evaluator.RelinearizeInplace(kernels[i], relinKeys);
                    }

                    if (useReScale)
                    {
                        evaluator.RescaleToNextInplace(kernels[i]);
                    }

                    SvcUtilities.PrintScale(kernels[i], "kernel" + i);

                    SvcUtilities.PrintCyprherText(decryptor, kernels[i], encoder, "kernel" + i);
                }

                // Encode coefficients : ParmsId! , scale!
                double scale2 = Math.Pow(2.0, power);

                if (useReScale)
                {
                    scale2 = kernels[0].Scale;
                }

                for (int i = 0; i < numOfrows; i++)
                {
                    encoder.Encode(_coefficients[0][i], scale2, coefArr[i]);
                    SvcUtilities.PrintScale(coefArr[i], "coefPlainText+i");
                }



                if (useReScale)
                {
                    for (int i = 0; i < numOfrows; i++)
                    {
                        ParmsId lastParmsId = kernels[i].ParmsId;
                        evaluator.ModSwitchToInplace(coefArr[i], lastParmsId);
                    }
                }
                // Level 2
                // Calculate decisionArr
                for (int i = 0; i < numOfrows; i++)
                {
                    evaluator.MultiplyPlain(kernels[i], coefArr[i], decisionsArr[i]);
                    if (useRelinearizeInplace)
                    {
                        evaluator.RelinearizeInplace(decisionsArr[i], relinKeys);
                    }

                    if (useReScale)
                    {
                        evaluator.RescaleToNextInplace(decisionsArr[i]);
                    }
                    SvcUtilities.PrintScale(decisionsArr[i], "decision" + i);
                    SvcUtilities.PrintCyprherText(decryptor, decisionsArr[i], encoder, "decision" + i);
                }



                // Calculate decisionTotal
                Ciphertext decisionTotal = new Ciphertext();

                //=================================================================
                evaluator.AddMany(decisionsArr, decisionTotal);
                //=================================================================

                SvcUtilities.PrintScale(decisionTotal, "decisionTotal");
                SvcUtilities.PrintCyprherText(decryptor, decisionTotal, encoder, "decision total");


                // Encode intercepts : ParmsId! , scale!
                Plaintext interceptsPlainText = new Plaintext();

                double scale3 = Math.Pow(2.0, power * 3);

                if (useReScale)
                {
                    scale3 = decisionTotal.Scale;
                }
                encoder.Encode(_intercepts[0], scale3, interceptsPlainText);
                if (useReScale)
                {
                    ParmsId lastParmsId = decisionTotal.ParmsId;
                    evaluator.ModSwitchToInplace(interceptsPlainText, lastParmsId);
                }

                SvcUtilities.PrintScale(interceptsPlainText, "interceptsPlainText");
                SvcUtilities.PrintScale(decisionTotal, "decisionTotal");


                //// Calculate finalTotal
                Ciphertext finalTotal = new Ciphertext();

                //=================================================================
                evaluator.AddPlainInplace(decisionTotal, interceptsPlainText);
                //=================================================================
                timePredictSum.Stop();

                SvcUtilities.PrintScale(decisionTotal, "decisionTotal");  //Level 3
                List <double> result = SvcUtilities.PrintCyprherText(decryptor, decisionTotal, encoder, "finalTotal");

                using (System.IO.StreamWriter file =
                           new System.IO.StreamWriter(
                               $@"{OutputDir}IrisLinearBatch_IrisSecureSVC_total_{power}_{useRelinearizeInplace}_{useReScale}.txt", !_firstTime)
                       )
                {
                    _firstTime = false;
                    file.WriteLine($"{result[0]}");
                }

                if (result[0] > 0)
                {
                    return(0);
                }

                return(1);
            }
        private void ACCEPT_REQUEST_GET_MONEY_AGENCY(HttpContext context)
        {
            try
            {
                if (context.Session["ACCEPT_REQUEST_GET_MONEY_AGENCY"] == null || (DateTime.Now - (DateTime)context.Session["ACCEPT_REQUEST_GET_MONEY_AGENCY"]).TotalMilliseconds > Constants.TIME_REQUEST)
                {
                    string json = context.Request.Form["json"];
                    if (!string.IsNullOrEmpty(json))
                    {
                        AcceptGetMoneyAgency jsonData = null;
                        try
                        {
                            jsonData = JsonConvert.DeserializeObject <AcceptGetMoneyAgency>(json);
                        }
                        catch (Exception)
                        {
                            result.status = Constants.NUMBER_CODE.ERROR_EX;
                            result.msg    = "Sai thông tin nhập vào";
                            context.Response.Write(JsonConvert.SerializeObject(result));
                            return;
                        }

                        if (jsonData != null)
                        {
                            jsonData.Key         = Constants.KEY_SQL;
                            jsonData.CreatorID   = accountInfo.AccountId.ToString();
                            jsonData.CreatorName = accountInfo.UserName;
                            jsonData.IP          = UtilClass.GetIPAddress();
                            //jsonData.Reason = "Tài khoản mở khóa chat: " + accountInfo.UserName;

                            //Logs.SaveLog(JsonConvert.SerializeObject(jsonData));

                            PayloadApi p = new PayloadApi()
                            {
                                clientIP = UtilClass.GetIPAddress(),
                                data     = Encryptor.EncryptString(JsonConvert.SerializeObject(jsonData), Constants.API_SECRETKEY)
                            };
                            var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "api/v1/Agency/AcceptGetMoneyAgency");
                            context.Response.Write(responseData);
                            return;
                        }
                    }
                }
                else
                {
                    result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER;
                    result.msg    = "Thao tác quá nhanh! vui lòng thử lại";
                }
            }
            catch (Exception ex)
            {
                Logs.SaveError("ERROR ACCEPT_REQUEST_GET_MONEY_AGENCY: " + ex);
                result.status = Constants.NUMBER_CODE.ERROR_EX;
                result.msg    = Constants.NUMBER_CODE.ERROR_EX.ToString();
            }
            finally
            {
                context.Session["ACCEPT_REQUEST_GET_MONEY_AGENCY"] = DateTime.Now;
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
Beispiel #36
0
        private string GetTeacherNameById(int id)
        {
            string userName = _context.User.Where(u => u.Userid == id).Select(u => u.Nick).FirstOrDefault();

            return(Encryptor.Decrypt(userName));
        }
        private void AddApoteker_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            _mDaftarBaru = new MApoteker(" ", " ", " ", " ", " ");

            if (checkTextBoxValue())
            {
                var id   = txtidDokter.Text.ToUpper();
                var nama = txtNamaDokter.Text;
                this.id = id;
                var alamat        = TextAlamat.Text;
                var no_telp       = txtTelpDokter.Text;
                var jenis_kelamin = cbJenisKelamin.Text;
                var password      = txtPassword.Text.ToUpper();

                if (cmd.CheckApotekerExsist(id) == 1)
                {
                    MessageBox.Show("Id sudah terdaftar.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    if (!Regex.IsMatch(no_telp, "^[A-Za-z]+$") && Regex.IsMatch(nama, "^[A-Za-z]+$"))
                    {
                        if (cmd.InsertDataApoteker(id, nama, no_telp, alamat, jenis_kelamin, password))
                        {
                            var isPrinted = false;

                            if (chkCetakKartu.IsChecked == true)
                            {
                                while (!isPrinted)
                                {
                                    try
                                    {
                                        if (!string.IsNullOrEmpty(id))
                                        {
                                            if (sp.WriteBlock(Msb, BlockId, Util.ToArrayByte16(id)))
                                            {
                                            }
                                            else
                                            {
                                                MessageBox.Show("Id gagal ditulis.");
                                            }
                                        }

                                        if (nama.Length > 48)
                                        {
                                            nama = nama.Substring(0, 47);
                                        }

                                        if (!string.IsNullOrEmpty(nama))
                                        {
                                            if (sp.WriteBlockRange(Msb, BlockNamaFrom, BlockNamaTo,
                                                                   Util.ToArrayByte48(nama)))
                                            {
                                            }
                                            else
                                            {
                                                MessageBox.Show("Nama gagal ditulis.");
                                            }
                                        }

                                        if (!string.IsNullOrEmpty(no_telp))
                                        {
                                            if (sp.WriteBlock(Msb, BlockTelp, Util.ToArrayByte16(no_telp)))
                                            {
                                            }
                                            else
                                            {
                                                MessageBox.Show("telp gagal ditulis.");
                                            }
                                        }

                                        if (alamat.Length > 64)
                                        {
                                            alamat = alamat.Substring(0, 67);
                                        }

                                        if (!string.IsNullOrEmpty(alamat))
                                        {
                                            if (sp.WriteBlockRange(Msb, BlockAlamatFrom, BlockAlamatTo,
                                                                   Util.ToArrayByte64(alamat)))
                                            {
                                            }
                                            else
                                            {
                                                MessageBox.Show("alamat gagal ditulis.");
                                            }
                                        }

                                        if (!string.IsNullOrEmpty(jenis_kelamin))
                                        {
                                            if (sp.WriteBlock(Msb, BlockJenisKelamin,
                                                              Util.ToArrayByte16(jenis_kelamin)))
                                            {
                                            }
                                            else
                                            {
                                                MessageBox.Show("Jenis kelamin gagal ditulis.");
                                            }
                                        }

                                        if (!string.IsNullOrEmpty(id))
                                        {
                                            if (sp.WriteBlockRange(Msb, BlockPasswordFrom, BlockPasswordTo,
                                                                   Util.ToArrayByte32(Encryptor.MD5Hash(id))))
                                            {
                                            }
                                            else
                                            {
                                                MessageBox.Show("Password gagal ditulis.");
                                            }
                                        }

                                        isPrinted = true;
                                        if (isPrinted)
                                        {
                                            break;
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        var ans = MessageBox.Show(
                                            "Penulisan kartu gagal, pastikan kartu sudah berada pada jangkauan reader.\nApakah anda ingin menulis kartu lain kali?",
                                            "Error",
                                            MessageBoxButton.YesNo, MessageBoxImage.Error);

                                        if (ans == MessageBoxResult.Yes)
                                        {
                                            break;
                                        }

                                        sp.isoReaderInit();
                                    }
                                }
                            }

                            MessageBox.Show("Data apoteker berhasil disimpan.", "Informasi", MessageBoxButton.OK,
                                            MessageBoxImage.Information);
                            da.displayDataApoteker();
                            Close();
                        }
                        else
                        {
                            MessageBox.Show("Data apoteker gagal disimpan.", "Error", MessageBoxButton.OK,
                                            MessageBoxImage.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Periksa kembali data yang akan di inputkan.", "Peringatan",
                                        MessageBoxButton.OK,
                                        MessageBoxImage.Warning);
                    }
                }
            }
            else
            {
                MessageBox.Show("Periksa kembali data yang akan di inputkan.", "Perhatian", MessageBoxButton.OK,
                                MessageBoxImage.Warning);
            }

            e.Handled = true;
        }
        /*
         * In `1_BFV_Basics.cs' we showed how to perform a very simple computation using the
         * BFV scheme. The computation was performed modulo the PlainModulus parameter, and
         * utilized only one coefficient from a BFV plaintext polynomial. This approach has
         * two notable problems:
         *
         *  (1) Practical applications typically use integer or real number arithmetic,
         *      not modular arithmetic;
         *  (2) We used only one coefficient of the plaintext polynomial. This is really
         *      wasteful, as the plaintext polynomial is large and will in any case be
         *      encrypted in its entirety.
         *
         * For (1), one may ask why not just increase the PlainModulus parameter until no
         * overflow occurs, and the computations behave as in integer arithmetic. The problem
         * is that increasing PlainModulus increases noise budget consumption, and decreases
         * the initial noise budget too.
         *
         * In these examples we will discuss other ways of laying out data into plaintext
         * elements (encoding) that allow more computations without data type overflow, and
         * can allow the full plaintext polynomial to be utilized.
         */
        private static void ExampleIntegerEncoder()
        {
            Utilities.PrintExampleBanner("Example: Encoders / Integer Encoder");

            /*
             * [IntegerEncoder] (For BFV scheme only)
             *
             * The IntegerEncoder encodes integers to BFV plaintext polynomials as follows.
             * First, a binary expansion of the integer is computed. Next, a polynomial is
             * created with the bits as coefficients. For example, the integer
             *
             *  26 = 2^4 + 2^3 + 2^1
             *
             * is encoded as the polynomial 1x^4 + 1x^3 + 1x^1. Conversely, plaintext
             * polynomials are decoded by evaluating them at x=2. For negative numbers the
             * IntegerEncoder simply stores all coefficients as either 0 or -1, where -1 is
             * represented by the unsigned integer PlainModulus - 1 in memory.
             *
             * Since encrypted computations operate on the polynomials rather than on the
             * encoded integers themselves, the polynomial coefficients will grow in the
             * course of such computations. For example, computing the sum of the encrypted
             * encoded integer 26 with itself will result in an encrypted polynomial with
             * larger coefficients: 2x^4 + 2x^3 + 2x^1. Squaring the encrypted encoded
             * integer 26 results also in increased coefficients due to cross-terms, namely,
             *
             *  (1x^4 + 1x^3 + 1x^1)^2 = 1x^8 + 2x^7 + 1x^6 + 2x^5 + 2x^4 + 1x^2;
             *
             * further computations will quickly increase the coefficients much more.
             * Decoding will still work correctly in this case (evaluating the polynomial
             * at x=2), but since the coefficients of plaintext polynomials are really
             * integers modulo plain_modulus, implicit reduction modulo plain_modulus may
             * yield unexpected results. For example, adding 1x^4 + 1x^3 + 1x^1 to itself
             * plain_modulus many times will result in the constant polynomial 0, which is
             * clearly not equal to 26 * plain_modulus. It can be difficult to predict when
             * such overflow will take place especially when computing several sequential
             * multiplications.
             *
             * The IntegerEncoder is easy to understand and use for simple computations,
             * and can be a good tool to experiment with for users new to Microsoft SEAL.
             * However, advanced users will probably prefer more efficient approaches,
             * such as the BatchEncoder or the CKKSEncoder.
             */
            EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree    = 4096;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.BFVDefault(polyModulusDegree);

            /*
             * There is no hidden logic behind our choice of the plain_modulus. The only
             * thing that matters is that the plaintext polynomial coefficients will not
             * exceed this value at any point during our computation; otherwise the result
             * will be incorrect.
             */
            parms.PlainModulus = new SmallModulus(512);
            SEALContext context = new SEALContext(parms);

            Utilities.PrintParameters(context);
            Console.WriteLine();

            KeyGenerator keygen    = new KeyGenerator(context);
            PublicKey    publicKey = keygen.PublicKey;
            SecretKey    secretKey = keygen.SecretKey;
            Encryptor    encryptor = new Encryptor(context, publicKey);
            Evaluator    evaluator = new Evaluator(context);
            Decryptor    decryptor = new Decryptor(context, secretKey);

            /*
             * We create an IntegerEncoder.
             */
            IntegerEncoder encoder = new IntegerEncoder(context);

            /*
             * First, we encode two integers as plaintext polynomials. Note that encoding
             * is not encryption: at this point nothing is encrypted.
             */
            int       value1 = 5;
            Plaintext plain1 = encoder.Encode(value1);

            Utilities.PrintLine();
            Console.WriteLine($"Encode {value1} as polynomial {plain1} (plain1),");

            int       value2 = -7;
            Plaintext plain2 = encoder.Encode(value2);

            Console.WriteLine(new string(' ', 13)
                              + $"Encode {value2} as polynomial {plain2} (plain2),");

            /*
             * Now we can encrypt the plaintext polynomials.
             */
            Ciphertext encrypted1 = new Ciphertext();
            Ciphertext encrypted2 = new Ciphertext();

            Utilities.PrintLine();
            Console.WriteLine("Encrypt plain1 to encrypted1 and plain2 to encrypted2.");
            encryptor.Encrypt(plain1, encrypted1);
            encryptor.Encrypt(plain2, encrypted2);
            Console.WriteLine("    + Noise budget in encrypted1: {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted1));
            Console.WriteLine("    + Noise budget in encrypted2: {0} bits",
                              decryptor.InvariantNoiseBudget(encrypted2));

            /*
             * As a simple example, we compute (-encrypted1 + encrypted2) * encrypted2.
             */
            encryptor.Encrypt(plain2, encrypted2);
            Ciphertext encryptedResult = new Ciphertext();

            Utilities.PrintLine();
            Console.WriteLine("Compute encrypted_result = (-encrypted1 + encrypted2) * encrypted2.");
            evaluator.Negate(encrypted1, encryptedResult);
            evaluator.AddInplace(encryptedResult, encrypted2);
            evaluator.MultiplyInplace(encryptedResult, encrypted2);
            Console.WriteLine("    + Noise budget in encryptedResult: {0} bits",
                              decryptor.InvariantNoiseBudget(encryptedResult));

            Plaintext plainResult = new Plaintext();

            Utilities.PrintLine();
            Console.WriteLine("Decrypt encrypted_result to plain_result.");
            decryptor.Decrypt(encryptedResult, plainResult);

            /*
             * Print the result plaintext polynomial. The coefficients are not even close
             * to exceeding our plainModulus, 512.
             */
            Console.WriteLine($"    + Plaintext polynomial: {plainResult}");

            /*
             * Decode to obtain an integer result.
             */
            Utilities.PrintLine();
            Console.WriteLine("Decode plain_result.");
            Console.WriteLine("    + Decoded integer: {0} ...... Correct.",
                              encoder.DecodeInt32(plainResult));
        }
Beispiel #39
0
        /*
         * In this example we show how serialization works in Microsoft SEAL. Specifically,
         * we present important concepts that enable the user to optimize the data size when
         * communicating ciphertexts and keys for outsourced computation. Unlike the previous
         * examples, we organize this one in a client-server style for maximal clarity. The
         * server selects encryption parameters, the client generates keys, the server does
         * the encrypted computation, and the client decrypts.
         */
        private static void ExampleSerialization()
        {
            Utilities.PrintExampleBanner("Example: Serialization");

            /*
             * We require ZLIB or Zstandard support for this example to be available.
             */
            if (!Serialization.IsSupportedComprMode(ComprModeType.ZLIB) &&
                !Serialization.IsSupportedComprMode(ComprModeType.ZSTD))
            {
                Console.WriteLine("Neither ZLIB nor Zstandard support is enabled; this example is not available.");
                Console.WriteLine();
                return;
            }

            /*
             * We start by briefly discussing the Serializable<T> generic class. This is
             * a wrapper class that can wrap any serializable class, which include:
             *
             *  - EncryptionParameters
             *  - Modulus
             *  - Plaintext and Ciphertext
             *  - SecretKey, PublicKey, RelinKeys, and GaloisKeys
             *
             * Serializable<T> provides minimal functionality needed to serialize the wrapped
             * object by simply forwarding the calls to corresponding functions of the wrapped
             * object of type T. The need for Serializable<T> comes from the fact that many
             * Microsoft SEAL objects consist of two parts, one of which is pseudorandom data
             * independent of the other part. Until the object is actually being used, the
             * pseudorandom part can be instead stored as a seed. We will call objects with
             * property `seedable'.
             *
             * For example, GaloisKeys can often be very large in size, but in reality half
             * of the data is pseudorandom and can be stored as a seed. Since GaloisKeys are
             * never used by the party that generates them, so it makes sense to expand the
             * seed at the point deserialization. On the other hand, we cannot allow the user
             * to accidentally try to use an unexpanded GaloisKeys object, which is prevented
             * at by ensuring it is always wrapped in a Serializable<GaloisKeys> and can only
             * be serialized.
             *
             * Only some Microsoft SEAL objects are seedable. Specifically, they are:
             *
             *  - PublicKey, RelinKeys, and GaloisKeys
             *  - Ciphertext in secret-key mode (from Encryptor.EncryptSymmetric or
             *    Encryptor.EncryptZeroSymmetric)
             *
             * Importantly, ciphertexts in public-key mode are not seedable. Thus, it may
             * be beneficial to use Microsoft SEAL in secret-key mode whenever the public
             * key is not truly needed.
             *
             * There are a handful of functions that output Serializable<T> objects:
             *
             *  - Encryptor.Encrypt (and variants) output Serializable<Ciphertext>
             *  - KeyGenerator.Create... output Serializable<T> for different key types
             *
             * Note that Encryptor.Encrypt is included in the above list, yet it produces
             * ciphertexts in public-key mode that are not seedable. This is for the sake of
             * consistency in the API for public-key and secret-key encryption. Functions
             * that output Serializable<T> objects also have overloads that take a normal
             * object of type T as a destination parameter, overwriting it. These overloads
             * can be convenient for local testing where no serialization is needed and the
             * object needs to be used at the point of construction. Such an object can no
             * longer be transformed back to a seeded state.
             */

            /*
             * To simulate client-server interaction, we set up a shared C# stream. In real
             * use-cases this can be a network stream, a filestream, or any shared resource.
             *
             * It is critical to note that all data serialized by Microsoft SEAL is in binary
             * form, so it is not meaningful to print the data as ASCII characters. Encodings
             * such as Base64 would increase the data size, which is already a bottleneck in
             * homomorphic encryption. Hence, serialization into text is not supported or
             * recommended.
             *
             * In this example we use a couple of shared MemoryStreams.
             */
            MemoryStream parmsStream = new MemoryStream();
            MemoryStream dataStream  = new MemoryStream();
            MemoryStream skStream    = new MemoryStream();

            /*
             * The server first determines the computation and sets encryption parameters
             * accordingly.
             */
            {
                ulong polyModulusDegree = 8192;
                using EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);
                parms.PolyModulusDegree          = polyModulusDegree;
                parms.CoeffModulus = CoeffModulus.Create(
                    polyModulusDegree, new int[] { 50, 20, 50 });

                /*
                 * Serialization of the encryption parameters to our shared stream is very
                 * simple with the EncryptionParameters.Save function.
                 */
                long size = parms.Save(parmsStream);

                /*
                 * Seek the parmsStream head back to beginning of the stream.
                 */
                parmsStream.Seek(0, SeekOrigin.Begin);

                /*
                 * The return value of this function is the actual byte count of data written
                 * to the stream.
                 */
                Utilities.PrintLine();
                Console.WriteLine($"EncryptionParameters: wrote {size} bytes");

                /*
                 * Before moving on, we will take some time to discuss further options in
                 * serialization. These will become particularly important when the user
                 * needs to optimize communication and storage sizes.
                 *
                 * It is possible to enable or disable compression for serialization by
                 * providing EncryptionParameters.Save with the desired compression mode as
                 * in the following examples:
                 *
                 *  long size = parms.Save(sharedStream, ComprModeType.None);
                 *  long size = parms.Save(sharedStream, ComprModeType.ZLIB);
                 *  long size = parms.Save(sharedStream, ComprModeType.ZSTD);
                 *
                 * If Microsoft SEAL is compiled with Zstandard or ZLIB support, the default
                 * is to use one of them. If available, Zstandard is preferred over ZLIB due
                 * to its speed.
                 *
                 * Compression can have a substantial impact on the serialized data size,
                 * because ciphertext and key data consists of many uniformly random integers
                 * modulo the CoeffModulus primes. Especially when using CKKS, the primes in
                 * CoeffModulus can be relatively small compared to the 64-bit words used to
                 * store the ciphertext and key data internally. Serialization writes full
                 * 64-bit words to the destination buffer or stream, possibly leaving in many
                 * zero bytes corresponding to the high-order bytes of the 64-bit words. One
                 * convenient way to get rid of these zeros is to apply a general-purpose
                 * compression algorithm on the encrypted data. The compression rate can be
                 * significant (up to 50-60%) when using CKKS with small primes.
                 */

                /*
                 * In many cases, when working with fixed size memory, it is necessary to know
                 * ahead of time an upper bound on the serialized data size to allocate enough
                 * memory. This information is returned by the EncryptionParameters.SaveSize
                 * function. This function accepts the desired compression mode, or uses the
                 * default option otherwise.
                 *
                 * In more detail, the output of EncryptionParameters.SaveSize is as follows:
                 *
                 *  - Exact buffer size required for ComprModeType.None;
                 *  - Upper bound on the size required for ComprModeType.ZLIB or
                 *    ComprModeType.ZSTD.
                 *
                 * As we can see from the print-out, the sizes returned by these functions
                 * are significantly larger than the compressed size written into the shared
                 * stream in the beginning. This is normal: compression yielded a significant
                 * improvement in the data size, however, it is impossible to know ahead of
                 * time the exact size of the compressed data. If compression is not used,
                 * then the size is exactly determined by the encryption parameters.
                 */
                Utilities.PrintLine();
                Console.Write("EncryptionParameters: data size upper bound (ComprModeType.None): ");
                Console.WriteLine(parms.SaveSize(ComprModeType.None));
                Console.Write("             ");
                Console.Write("EncryptionParameters: data size upper bound (compression): ");
                Console.WriteLine(parms.SaveSize(/* Serialization.ComprModeDefault */));

                /*
                 * As an example, we now serialize the encryption parameters to a fixed
                 * size buffer.
                 */
                MemoryStream buffer = new MemoryStream(new byte[parms.SaveSize()]);
                parms.Save(buffer);

                /*
                 * To illustrate deserialization, we load back the encryption parameters
                 * from our buffer into another instance of EncryptionParameters. First
                 * we need to seek our stream back to the beginning.
                 */
                buffer.Seek(0, SeekOrigin.Begin);
                using EncryptionParameters parms2 = new EncryptionParameters();
                parms2.Load(buffer);

                /*
                 * We can check that the saved and loaded encryption parameters indeed match.
                 */
                Utilities.PrintLine();
                Console.WriteLine($"EncryptionParameters: parms == parms2: {parms.Equals(parms2)}");
            }

            /*
             * Client starts by loading the encryption parameters, sets up the SEALContext,
             * and creates the required keys.
             */
            {
                using EncryptionParameters parms = new EncryptionParameters();
                parms.Load(parmsStream);

                /*
                 * Seek the parmsStream head back to beginning of the stream because we
                 * will use the same stream to read the parameters repeatedly.
                 */
                parmsStream.Seek(0, SeekOrigin.Begin);

                using SEALContext context = new SEALContext(parms);

                using KeyGenerator keygen = new KeyGenerator(context);
                using SecretKey sk        = keygen.SecretKey;
                keygen.CreatePublicKey(out PublicKey pk);

                /*
                 * We need to save the secret key so we can decrypt later.
                 */
                sk.Save(skStream);
                skStream.Seek(0, SeekOrigin.Begin);

                /*
                 * As in previous examples, in this example we will encrypt in public-key
                 * mode. If we want to send a public key over the network, we should instead
                 * have created it as a seeded object as follows:
                 *
                 *  Serializable<PublicKey> pk = keygen.CreatePublicKey();
                 *
                 * In this example we will also use relinearization keys. These we will
                 * absolutely want to create as seeded objects to minimize communication
                 * cost, unlike in prior examples.
                 */
                using Serializable <RelinKeys> rlk = keygen.CreateRelinKeys();

                /*
                 * To demonstrate the significant space saving from this method, we will
                 * create another set of relinearization keys, this time fully expanded.
                 */
                keygen.CreateRelinKeys(out RelinKeys rlkBig);

                /*
                 * We serialize both relinearization keys to demonstrate the concrete size
                 * difference. If compressed serialization is used, the compression rate
                 * will be the same in both cases. We omit specifying the compression mode
                 * to use the default, as determined by the Microsoft SEAL build system.
                 */
                long sizeRlk    = rlk.Save(dataStream);
                long sizeRlkBig = rlkBig.Save(dataStream);

                Utilities.PrintLine();
                Console.WriteLine($"Serializable<RelinKeys>: wrote {sizeRlk} bytes");
                Console.Write("             ");
                Console.WriteLine($"RelinKeys: wrote {sizeRlkBig} bytes");

                /*
                 * Seek back in dataStream to where rlk data ended, i.e., sizeRlkBig bytes
                 * backwards from current position.
                 */
                dataStream.Seek(-sizeRlkBig, SeekOrigin.Current);

                /*
                 * Next set up the CKKSEncoder and Encryptor, and encrypt some numbers.
                 */
                double      scale   = Math.Pow(2.0, 20);
                CKKSEncoder encoder = new CKKSEncoder(context);
                using Plaintext plain1 = new Plaintext(),
                      plain2           = new Plaintext();
                encoder.Encode(2.3, scale, plain1);
                encoder.Encode(4.5, scale, plain2);

                using Encryptor encryptor = new Encryptor(context, pk);

                /*
                 * The client will not compute on ciphertexts that it creates, so it can
                 * just as well create Serializable<Ciphertext> objects. In fact, we do
                 * not even need to name those objects and instead immediately call
                 * Serializable<Ciphertext>.Save.
                 */
                long sizeEncrypted1 = encryptor.Encrypt(plain1).Save(dataStream);

                /*
                 * As we discussed in the beginning of this example, ciphertexts can
                 * be created in a seeded state in secret-key mode, providing a huge
                 * reduction in the data size upon serialization. To do this, we need
                 * to provide the Encryptor with the secret key in its constructor, or
                 * at a later point with the Encryptor.SetSecretKey function, and use
                 * the Encryptor.EncryptSymmetric function to encrypt.
                 */
                encryptor.SetSecretKey(sk);
                long sizeSymEncrypted2 = encryptor.EncryptSymmetric(plain2).Save(dataStream);

                /*
                 * The size reduction is substantial.
                 */
                Utilities.PrintLine();
                Console.WriteLine($"Serializable<Ciphertext> (public-key): wrote {sizeEncrypted1} bytes");
                Console.Write("             ");
                Console.Write($"Serializable<Ciphertext> (seeded secret-key): ");
                Console.WriteLine($"wrote {sizeSymEncrypted2} bytes");

                /*
                 * Seek to the beginning of dataStream.
                 */
                dataStream.Seek(0, SeekOrigin.Begin);

                /*
                 * We have seen how creating seeded objects can result in huge space
                 * savings compared to creating unseeded objects. This is particularly
                 * important when creating Galois keys, which can be very large. We have
                 * seen how secret-key encryption can be used to achieve much smaller
                 * ciphertext sizes when the public-key functionality is not needed.
                 *
                 * We would also like to draw attention to the fact there we could easily
                 * serialize multiple Microsoft SEAL objects sequentially in a stream. Each
                 * object writes its own size into the stream, so deserialization knows
                 * exactly how many bytes to read. We will see this working below.
                 */
            }

            /*
             * The server can now compute on the encrypted data. We will recreate the
             * SEALContext and set up an Evaluator here.
             */
            {
                using EncryptionParameters parms = new EncryptionParameters();
                parms.Load(parmsStream);
                parmsStream.Seek(0, SeekOrigin.Begin);
                using SEALContext context = new SEALContext(parms);

                using Evaluator evaluator = new Evaluator(context);

                /*
                 * Next we need to load relinearization keys and the ciphertexts from our
                 * dataStream.
                 */
                using RelinKeys rlk         = new RelinKeys();
                using Ciphertext encrypted1 = new Ciphertext(),
                      encrypted2            = new Ciphertext();

                /*
                 * Deserialization is as easy as serialization.
                 */
                rlk.Load(context, dataStream);
                encrypted1.Load(context, dataStream);
                encrypted2.Load(context, dataStream);

                /*
                 * Compute the product, rescale, and relinearize.
                 */
                using Ciphertext encryptedProd = new Ciphertext();
                evaluator.Multiply(encrypted1, encrypted2, encryptedProd);
                evaluator.RelinearizeInplace(encryptedProd, rlk);
                evaluator.RescaleToNextInplace(encryptedProd);

                /*
                 * We use dataStream to communicate encryptedProd back to the client.
                 * There is no way to save the encryptedProd as a seeded object: only
                 * freshly encrypted secret-key ciphertexts can be seeded. Note how the
                 * size of the result ciphertext is smaller than the size of a fresh
                 * ciphertext because it is at a lower level due to the rescale operation.
                 */
                dataStream.Seek(0, SeekOrigin.Begin);
                long sizeEncryptedProd = encryptedProd.Save(dataStream);
                dataStream.Seek(0, SeekOrigin.Begin);

                Utilities.PrintLine();
                Console.Write($"Ciphertext (secret-key): ");
                Console.WriteLine($"wrote {sizeEncryptedProd} bytes");
            }

            /*
             * In the final step the client decrypts the result.
             */
            {
                using EncryptionParameters parms = new EncryptionParameters();
                parms.Load(parmsStream);
                parmsStream.Seek(0, SeekOrigin.Begin);
                using SEALContext context = new SEALContext(parms);

                /*
                 * Load back the secret key from skStream.
                 */
                using SecretKey sk = new SecretKey();
                sk.Load(context, skStream);
                using Decryptor decryptor = new Decryptor(context, sk);
                using CKKSEncoder encoder = new CKKSEncoder(context);

                using Ciphertext encryptedResult = new Ciphertext();
                encryptedResult.Load(context, dataStream);

                using Plaintext plainResult = new Plaintext();
                decryptor.Decrypt(encryptedResult, plainResult);
                List <double> result = new List <double>();
                encoder.Decode(plainResult, result);

                Utilities.PrintLine();
                Console.WriteLine("Result: ");
                Utilities.PrintVector(result, 3, 7);
            }

            /*
             * Finally, we give a little bit more explanation of the structure of data
             * serialized by Microsoft SEAL. Serialized data always starts with a 16-byte
             * SEALHeader struct, as defined in dotnet/src/Serialization.cs, and is
             * followed by the possibly compressed data for the object.
             *
             * A SEALHeader contains the following data:
             *
             *  [offset 0] 2-byte magic number 0xA15E (Serialization.SEALMagic)
             *  [offset 2] 1-byte indicating the header size in bytes (always 16)
             *  [offset 3] 1-byte indicating the Microsoft SEAL major version number
             *  [offset 4] 1-byte indicating the Microsoft SEAL minor version number
             *  [offset 5] 1-byte indicating the compression mode type
             *  [offset 6] 2-byte reserved field (unused)
             *  [offset 8] 8-byte size in bytes of the serialized data, including the header
             *
             * Currently Microsoft SEAL supports only little-endian systems.
             *
             * As an example, we demonstrate the SEALHeader created by saving a plaintext.
             * Note that the SEALHeader is never compressed, so there is no need to specify
             * the compression mode.
             */
            using Plaintext pt = new Plaintext("1x^2 + 3");
            MemoryStream stream   = new MemoryStream();
            long         dataSize = pt.Save(stream);

            /*
             * Seek the stream head back to beginning of the stream.
             */
            stream.Seek(0, SeekOrigin.Begin);

            /*
             * We can now load just the SEALHeader back from the stream as follows.
             */
            Serialization.SEALHeader header = new Serialization.SEALHeader();
            Serialization.LoadHeader(stream, header);

            /*
             * Now confirm that the size of data written to stream matches with what is
             * indicated by the SEALHeader.
             */
            Utilities.PrintLine();
            Console.WriteLine($"Size written to stream: {dataSize} bytes");
            Console.Write("             ");
            Console.WriteLine($"Size indicated in SEALHeader: {header.Size} bytes");
            Console.WriteLine();
        }
        /// <summary>
        /// Tạo đại lý cấp 1 mới
        /// </summary>
        /// <param name="context"></param>
        private void CREATE_AGENCY(HttpContext context)
        {
            short debug = 0;

            try
            {
                if (context.Session["CREATE_AGENCY"] == null || (DateTime.Now - (DateTime)context.Session["CREATE_AGENCY"]).TotalMilliseconds > Constants.TIME_REQUEST)
                {
                    debug = 1;
                    string json = context.Request.Form["json"];
                    if (!string.IsNullOrEmpty(json))
                    {
                        debug = 2;
                        try
                        {
                            JsonConvert.DeserializeObject <AgencyEntity>(json);
                        }
                        catch (Exception)
                        {
                            result.status = Constants.NUMBER_CODE.ERROR_EX;
                            result.msg    = "Sai thông tin nhập vào";
                            context.Response.Write(JsonConvert.SerializeObject(result));
                            return;
                        }
                        var jsonData = JsonConvert.DeserializeObject <AgencyEntity>(json);
                        if (jsonData != null)
                        {
                            debug = 3;
                            if (string.IsNullOrEmpty(jsonData.agencyCode))
                            {
                                debug         = 301;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Mã đại lý không được bỏ trống!";
                            }
                            else if (jsonData.agencyCode.Length < 6 || jsonData.agencyCode.Length > 10)
                            {
                                debug         = 302;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Mã đại lý phải từ 6-10 ký tự";
                            }
                            else if (string.IsNullOrEmpty(jsonData.password))
                            {
                                debug         = 303;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Password không được để trống";
                            }
                            else if (jsonData.password.Length < 6 && jsonData.password.Length > 20)
                            {
                                debug         = 304;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Password phải từ 6-20 ký tự";
                            }
                            else if (jsonData.email.Length > 80)
                            {
                                debug         = 3051;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Email không được dài hơn 80 ký tự";
                            }
                            else if (string.IsNullOrEmpty(jsonData.phone))
                            {
                                debug         = 306;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Số điện thoại không được để trống";
                            }
                            else if (jsonData.phone.Length != 10)
                            {
                                debug         = 307;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Số điện thoại phải là 10 chữ số";
                            }
                            else if (string.IsNullOrEmpty(jsonData.displayName))
                            {
                                debug         = 308;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Tên hiển thị không được để trống";
                            }
                            else if (jsonData.displayName.Length < 6)
                            {
                                debug         = 3091;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Tên hiển thị phải nhiều hơn 5 ký tự";
                            }
                            else if (jsonData.infomation.Length >= 250)
                            {
                                debug         = 3092;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Thông tin đại lý phải ít hơn 250 ký tự";
                            }
                            else if (jsonData.FB.Length >= 250)
                            {
                                debug         = 3093;
                                result.status = Constants.NUMBER_CODE.INFO_CREATE_AGENCY_VALI;
                                result.msg    = "Đường link facebook phải ít hơn 250 ký tự";
                            }

                            else
                            {
                                debug = 310;

                                jsonData.IP                    = UtilClass.GetIPAddress();
                                jsonData.creatorID             = accountInfo.AccountId;
                                jsonData.creatorName           = accountInfo.UserName;
                                jsonData.limitTransaction      = Constants.limitTransaction;
                                jsonData.limitTransactionDaily = Constants.limitTransactionDaily;

                                PayloadApi p = new PayloadApi()
                                {
                                    clientIP = UtilClass.GetIPAddress(),
                                    data     = Encryptor.EncryptString(JsonConvert.SerializeObject(jsonData), Constants.API_SECRETKEY)
                                };
                                var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Agency/CreateAgency");
                                context.Response.Write(responseData);
                                return;
                            }
                        }
                        else
                        {
                            debug         = 4;
                            result.status = Constants.NUMBER_CODE.DATA_NULL;
                            result.msg    = Constants.NUMBER_CODE.DATA_NULL.ToString();
                        }
                    }
                    else
                    {
                        debug         = 5;
                        result.status = Constants.NUMBER_CODE.DATA_NULL;
                        result.msg    = Constants.NUMBER_CODE.DATA_NULL.ToString();
                    }
                }
                else
                {
                    debug         = 6;
                    result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER;
                    result.msg    = "Thao tác quá nhanh! vui lòng thử lại";
                }
            }
            catch (Exception ex)
            {
                Logs.SaveError("ERROR CREATE_AGENCY: [debug]:" + debug + "\n,\n" + ex);
                result.status = Constants.NUMBER_CODE.ERROR_EX;
                result.msg    = Constants.NUMBER_CODE.ERROR_EX.ToString();
            }
            finally
            {
                Logs.SaveError("[debug]:" + debug);
                context.Session["CREATE_AGENCY"] = DateTime.Now;
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
        public void FVEncryptDecryptNET()
        {
            var parms         = new EncryptionParameters();
            var plain_modulus = new SmallModulus(1 << 6);

            parms.NoiseStandardDeviation = 3.19;
            parms.PlainModulus           = plain_modulus;
            {
                parms.PolyModulus  = "1x^64 + 1";
                parms.CoeffModulus = new List <SmallModulus> {
                    DefaultParams.SmallMods60Bit(0)
                };
                var context = new SEALContext(parms);

                var keygen  = new KeyGenerator(context);
                var encoder = new BalancedEncoder(plain_modulus);

                var encryptor = new Encryptor(context, keygen.PublicKey);
                var decryptor = new Decryptor(context, keygen.SecretKey);

                var encrypted = new Ciphertext();
                var plain     = new Plaintext();
                encryptor.Encrypt(encoder.Encode(0x12345678), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x12345678UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(1), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(1UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(2), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(2UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFD), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFDUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFE), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFEUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFF), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFFUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(314159265), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(314159265UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);
            }
            {
                parms.PolyModulus  = "1x^128 + 1";
                parms.CoeffModulus = new List <SmallModulus> {
                    DefaultParams.SmallMods40Bit(0), DefaultParams.SmallMods40Bit(1)
                };
                var context = new SEALContext(parms);
                var keygen  = new KeyGenerator(context);

                var encoder = new BalancedEncoder(plain_modulus);

                var encryptor = new Encryptor(context, keygen.PublicKey);
                var decryptor = new Decryptor(context, keygen.SecretKey);

                var encrypted = new Ciphertext();
                var plain     = new Plaintext();
                encryptor.Encrypt(encoder.Encode(0x12345678), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x12345678UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(1), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(1UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(2), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(2UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFD), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFDUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFE), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFEUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFF), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFFUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(314159265), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(314159265UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);
            }

            {
                parms.PolyModulus  = "1x^256 + 1";
                parms.CoeffModulus = new List <SmallModulus> {
                    DefaultParams.SmallMods40Bit(0), DefaultParams.SmallMods40Bit(1), DefaultParams.SmallMods40Bit(2)
                };
                var context = new SEALContext(parms);
                var keygen  = new KeyGenerator(context);

                var encoder = new BalancedEncoder(plain_modulus);

                var encryptor = new Encryptor(context, keygen.PublicKey);
                var decryptor = new Decryptor(context, keygen.SecretKey);

                var encrypted = new Ciphertext();
                var plain     = new Plaintext();
                encryptor.Encrypt(encoder.Encode(0x12345678), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x12345678UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(1), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(1UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(2), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(2UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFD), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFDUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFE), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFEUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(0x7FFFFFFFFFFFFFFF), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(0x7FFFFFFFFFFFFFFFUL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);

                encryptor.Encrypt(encoder.Encode(314159265), encrypted);
                decryptor.Decrypt(encrypted, plain);
                Assert.AreEqual(314159265UL, encoder.DecodeUInt64(plain));
                Assert.AreEqual(encrypted.HashBlock, parms.HashBlock);
            }
        }
 /// <summary>
 /// Constructs the step with the given encryptor
 /// </summary>
 public DecryptMessagesIncomingStep(Encryptor encryptor)
 {
     _encryptor = encryptor;
 }
Beispiel #43
0
        /// <summary>
        /// To get a request without sending a push notification call this method.
        ///
        /// This method will throw an ArgumentException if there is an issue with the input.
        /// </summary>
        /// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
        /// <param name="payload">The payload you wish to send to the user</param>
        /// <param name="options">Options for the GCM API key and vapid keys can be passed in if they are unique for each notification.</param>
        /// <returns>A HttpRequestMessage object that can be sent.</returns>
        public HttpRequestMessage GenerateRequestDetails(PushSubscription subscription, string payload, Dictionary <string, object> options = null)
        {
            if (!Uri.IsWellFormedUriString(subscription.Endpoint, UriKind.Absolute))
            {
                throw new ArgumentException(@"You must pass in a subscription with at least a valid endpoint");
            }

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, subscription.Endpoint);

            if (!String.IsNullOrEmpty(payload) && (String.IsNullOrEmpty(subscription.Auth) || String.IsNullOrEmpty(subscription.P256DH)))
            {
                throw new ArgumentException(@"To send a message with a payload, the subscription must have 'auth' and 'p256dh' keys.");
            }

            string       currentGCMAPiKey            = _gcmAPIKey;
            VapidDetails currentVapidDetails         = _vapidDetails;
            int          timeToLive                  = DefaultTtl;
            Dictionary <string, object> extraHeaders = new Dictionary <string, object>();

            if (options != null)
            {
                List <string> validOptionsKeys = new List <string> {
                    "headers", "gcmAPIKey", "vapidDetails", "TTL"
                };
                foreach (string key in options.Keys)
                {
                    if (!validOptionsKeys.Contains(key))
                    {
                        throw new ArgumentException(key + " is an invalid options. The valid options are" + String.Join(",", validOptionsKeys));
                    }
                }


                if (options.ContainsKey("headers"))
                {
                    Dictionary <string, object> headers = options["headers"] as Dictionary <string, object>;
                    if (headers == null)
                    {
                        throw new ArgumentException("options.headers must be of type Dictionary<string,object>");
                    }

                    extraHeaders = headers;
                }

                if (options.ContainsKey("gcmAPIKey"))
                {
                    string gcmAPIKey = options["gcmAPIKey"] as string;
                    if (gcmAPIKey == null)
                    {
                        throw new ArgumentException("options.gcmAPIKey must be of type string");
                    }

                    currentGCMAPiKey = gcmAPIKey;
                }

                if (options.ContainsKey("vapidDetails"))
                {
                    VapidDetails vapidDetails = options["vapidDetails"] as VapidDetails;
                    if (vapidDetails == null)
                    {
                        throw new ArgumentException("options.vapidDetails must be of type VapidDetails");
                    }

                    currentVapidDetails = vapidDetails;
                }

                if (options.ContainsKey("TTL"))
                {
                    int?ttl = options["TTL"] as int?;
                    if (ttl == null)
                    {
                        throw new ArgumentException("options.TTL must be of type int");
                    }

                    //at this stage ttl cannot be null.
                    timeToLive = (int)ttl;
                }
            }

            string cryptoKeyHeader = null;

            request.Headers.Add("TTL", timeToLive.ToString());

            foreach (KeyValuePair <string, object> header in extraHeaders)
            {
                request.Headers.Add(header.Key, header.Value.ToString());
            }

            if (!String.IsNullOrEmpty(payload))
            {
                if (String.IsNullOrEmpty(subscription.P256DH) || String.IsNullOrEmpty(subscription.Auth))
                {
                    throw new ArgumentException(@"Unable to send a message with payload to this subscription since it doesn't have the required encryption key");
                }

                EncryptionResult encryptedPayload = Encryptor.Encrypt(subscription.P256DH, subscription.Auth, payload);

                request.Content = new ByteArrayContent(encryptedPayload.Payload);
                request.Content.Headers.ContentType   = new MediaTypeHeaderValue("application/octet-stream");
                request.Content.Headers.ContentLength = encryptedPayload.Payload.Length;
                request.Content.Headers.ContentEncoding.Add("aesgcm");
                request.Headers.Add("Encryption", "salt=" + encryptedPayload.Base64EncodeSalt());
                cryptoKeyHeader = @"dh=" + encryptedPayload.Base64EncodePublicKey();
            }
            else
            {
                request.Content = new ByteArrayContent(new byte[0]);
                request.Content.Headers.ContentLength = 0;
            }

            bool isGCM = subscription.Endpoint.StartsWith(@"https://android.googleapis.com/gcm/send");

            if (isGCM)
            {
                if (!String.IsNullOrEmpty(currentGCMAPiKey))
                {
                    request.Headers.TryAddWithoutValidation("Authorization", "key=" + currentGCMAPiKey);
                }
            }
            else if (currentVapidDetails != null)
            {
                Uri    uri      = new Uri(subscription.Endpoint);
                string audience = uri.Scheme + Uri.SchemeDelimiter + uri.Host;

                Dictionary <string, string> vapidHeaders = VapidHelper.GetVapidHeaders(audience, currentVapidDetails.Subject, currentVapidDetails.PublicKey, currentVapidDetails.PrivateKey);
                request.Headers.Add(@"Authorization", vapidHeaders["Authorization"]);
                if (String.IsNullOrEmpty(cryptoKeyHeader))
                {
                    cryptoKeyHeader = vapidHeaders["Crypto-Key"];
                }
                else
                {
                    cryptoKeyHeader += @";" + vapidHeaders["Crypto-Key"];
                }
            }

            request.Headers.Add("Crypto-Key", cryptoKeyHeader);
            return(request);
        }
Beispiel #44
0
        public void AgileEncryption()
        {
            int maxKeyLen = Cipher.GetMaxAllowedKeyLength("AES");

            Assume.That(maxKeyLen == 2147483647, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256");

            FileStream       file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-pass.docx");
            String           pass = "******";
            NPOIFSFileSystem nfs  = new NPOIFSFileSystem(file);

            // Check the encryption details
            EncryptionInfo infoExpected = new EncryptionInfo(nfs);
            Decryptor      decExpected  = Decryptor.GetInstance(infoExpected);
            bool           passed       = decExpected.VerifyPassword(pass);

            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            Stream is1 = decExpected.GetDataStream(nfs);

            byte[] payloadExpected = IOUtils.ToByteArray(is1);
            is1.Close();

            long decPackLenExpected = decExpected.GetLength();

            Assert.AreEqual(decPackLenExpected, payloadExpected.Length);

            is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY);
            ///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block
            ///throw new NotImplementedException(BoundedInputStream);
            byte[] encPackExpected = IOUtils.ToByteArray(is1);
            is1.Close();

            // listDir(nfs.Root, "orig", "");

            nfs.Close();

            // check that same verifier/salt lead to same hashes
            byte[] verifierSaltExpected = infoExpected.Verifier.Salt;
            byte[] verifierExpected     = decExpected.GetVerifier();
            byte[] keySalt       = infoExpected.Header.KeySalt;
            byte[] keySpec       = decExpected.GetSecretKey().GetEncoded();
            byte[] integritySalt = decExpected.GetIntegrityHmacKey();
            // the hmacs of the file always differ, as we use PKCS5-pAdding to pad the bytes
            // whereas office just uses random bytes
            // byte integrityHash[] = d.IntegrityHmacValue;

            POIFSFileSystem fs         = new POIFSFileSystem();
            EncryptionInfo  infoActual = new EncryptionInfo(
                EncryptionMode.Agile
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            Encryptor e = Encryptor.GetInstance(infoActual);

            e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt);

            Stream os = e.GetDataStream(fs);

            IOUtils.Copy(new MemoryStream(payloadExpected), os);
            os.Close();

            MemoryStream bos = new MemoryStream();

            fs.WriteFileSystem(bos);

            nfs        = new NPOIFSFileSystem(new MemoryStream(bos.ToArray()));
            infoActual = new EncryptionInfo(nfs.Root);
            Decryptor decActual = Decryptor.GetInstance(infoActual);

            passed = decActual.VerifyPassword(pass);
            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            is1 = decActual.GetDataStream(nfs);
            byte[] payloadActual = IOUtils.ToByteArray(is1);
            is1.Close();

            long decPackLenActual = decActual.GetLength();

            is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY);
            ///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block
            ///throw new NotImplementedException(BoundedInputStream);
            byte[] encPackActual = IOUtils.ToByteArray(is1);
            is1.Close();

            // listDir(nfs.Root, "copy", "");

            nfs.Close();

            AgileEncryptionHeader aehExpected = (AgileEncryptionHeader)infoExpected.Header;
            AgileEncryptionHeader aehActual   = (AgileEncryptionHeader)infoActual.Header;

            CollectionAssert.AreEqual(aehExpected.GetEncryptedHmacKey(), aehActual.GetEncryptedHmacKey());
            Assert.AreEqual(decPackLenExpected, decPackLenActual);
            CollectionAssert.AreEqual(payloadExpected, payloadActual);
            CollectionAssert.AreEqual(encPackExpected, encPackActual);
        }
Beispiel #45
0
        protected override ServiceOutcome DoWork()
        {
            // FTP configuration
            string fileConflictBehavior = this.Configuration.Parameters.Get <string>("FileConflictBehavior", emptyIsError: false, defaultValue: "Abort");
            string FtpServer            = this.Configuration.Parameters.Get <string>("FtpServer");

            string[] AllowedExtensions = this.Configuration.Parameters.Get <string>("AllowedExtensions").Split('|');
            bool     UsePassive        = this.Configuration.Parameters.Get <bool>("UsePassive");
            bool     UseBinary         = this.Configuration.Parameters.Get <bool>("UseBinary");
            string   UserId            = this.Configuration.Parameters.Get <string>("UserID");
            string   Password          = Encryptor.Dec(this.Configuration.Parameters.Get <string>("Password"));

            FtpWebRequest request;
            int           filesCounter = 0;

            try
            {
                request             = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpServer + "/"));
                request.UseBinary   = UseBinary;
                request.UsePassive  = UsePassive;
                request.Credentials = new NetworkCredential(UserId, Password);
                request.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;

                var    response         = (FtpWebResponse)request.GetResponse();
                var    reader           = new StreamReader(response.GetResponseStream());
                string fileInfoAsString = reader.ReadLine();

                while (fileInfoAsString != null)
                {
                    //Checking AllowedExtensions
                    Dictionary <string, string> fileInfo = GetFileInfo(fileInfoAsString);

                    if (fileConflictBehavior == "Ignore" || !CheckFileConflict(fileInfo))
                    {
                        //Get files with allowed extensions only.

                        if (AllowedExtensions.Contains(Path.GetExtension(fileInfo["Name"]), StringComparer.OrdinalIgnoreCase))
                        {
                            string sourceUrl = FtpServer + "/" + fileInfo["Name"];

                            var config = new PipelineServiceConfiguration();
                            config.Parameters[Const.DeliveryServiceConfigurationOptions.SourceUrl] = sourceUrl;
                            config.Parameters["FileSize"]         = fileInfo["Size"];
                            config.Parameters["DeliveryFileName"] = fileInfo["Name"];
                            config.Parameters["FileModifyDate"]   = fileInfo["ModifyDate"];

                            // TODO shriat add to scheduler
                            //Environment.ScheduleServiceByName(this.Configuration.Parameters.Get<string>("FtpService"),Configuration.Profile.ProfileID,config);
                            var serviceInstance = Environment.NewServiceInstance(Configuration);
                            Environment.AddToSchedule(serviceInstance);
                        }
                    }

                    fileInfoAsString = reader.ReadLine();
                    filesCounter++;
                }
                reader.Close();
                response.Close();

                if (filesCounter == 0)
                {
                    Log("No files in FTP directory for account id " + Configuration.Profile.Parameters["AccountID"], LogMessageType.Information);
                }
            }
            catch (Exception e)
            {
                Log(string.Format("Cannot connect FTP server for account ID:{0}  Exception: {1}", Configuration.Profile.Parameters["AccountID"], e.Message), LogMessageType.Information);
                return(ServiceOutcome.Failure);
            }

            return(ServiceOutcome.Success);
        }
Beispiel #46
0
 private User ValidateUser(string userName, string password)
 {
     User user = null;
     string source = password;
     using (MD5 md5Hash = MD5.Create())
     {
         Encryptor enc = new Encryptor();
         string hash = enc.GetMd5Hash(md5Hash, source);
         if (enc.VerifyMd5Hash(md5Hash, source, hash))
         {
             IQueryable<User> users = db.Users.Where(u => u.Name == userName && u.Password == hash && u.Status == 1);
             if (users.Count() == 1)
                 user = users.Single();
         }
     }
     return user;
 }
 private async Task SendNoticeToClientsAsync(IEnumerable <ClientConnection> clients, Notice notice)
 {
     try
     {
         if (clients.IsNullOrEmpty())
         {
             return;
         }
         foreach (var client in clients)
         {
             try
             {
                 if (client.IsProxiedClientConnection && client.ClientSocket == null && client.ProxyNodeWebSocket != null)
                 {
                     NodeConnection nodeConnection = connectionsService.GetNodeConnections().FirstOrDefault(opt => opt.NodeWebSocket == client.ProxyNodeWebSocket);
                     byte[]         noticeData     = ObjectSerializer.CommunicationObjectToBytes(notice);
                     if (client.IsEncryptedConnection)
                     {
                         noticeData = Encryptor.SymmetricDataEncrypt(
                             noticeData,
                             NodeData.Instance.NodeKeys.SignPrivateKey,
                             client.SymmetricKey,
                             MessageDataType.Notice,
                             NodeData.Instance.NodeKeys.Password);
                     }
                     nodeNoticeService.SendProxyUsersNotificationsNodeNoticeAsync(
                         noticeData,
                         client.UserId.GetValueOrDefault(),
                         client.PublicKey,
                         nodeConnection);
                 }
                 else if (client.ClientSocket != null)
                 {
                     byte[] noticeData = ObjectSerializer.NoticeToBytes(notice);
                     if (client.IsEncryptedConnection)
                     {
                         noticeData = Encryptor.SymmetricDataEncrypt(
                             noticeData,
                             NodeData.Instance.NodeKeys.SignPrivateKey,
                             client.SymmetricKey,
                             MessageDataType.Binary,
                             NodeData.Instance.NodeKeys.Password);
                     }
                     await client.ClientSocket.SendAsync(
                         noticeData,
                         WebSocketMessageType.Binary,
                         true,
                         CancellationToken.None)
                     .ConfigureAwait(false);
                 }
             }
             catch (WebSocketException)
             {
                 continue;
             }
         }
     }
     catch (Exception ex)
     {
         Logger.WriteLog(ex, notice.ToString());
     }
 }
Beispiel #48
0
 private void FORGOT_PASSWORD(HttpContext context)
 {
     try
     {
         string email = context.Request.Form["email"];
         if (!string.IsNullOrEmpty(email))
         {
             email = email.Trim();
             int code = manage.AccountModel.CheckResetPassword(email, (byte)Constants.LOGIN_TYPE.SINGLEID);
             if (code == 0)
             {
                 string token = email.ToLower() + "|" + UtilClass.UnixTime(DateTime.Now) + "|" + UtilClass.GetIPAddress() + "|" + ((int)Constants.LOGIN_TYPE.SINGLEID);
                 string link  = UtilClass.GetWebAppRoot() + "/VetifyResetPassword.aspx?token=" + Encryptor.Base64Encode(Encryptor.EncryptString(token, Constants.KEY_SERVER));
                 bool   s     = SendMailUser("Yêu cầu xác nhận thiết lập lại mật khẩu", "Hệ thống nhận yêu cầu thiết lập lại mật khẩu của Bạn. Vui lòng nhấn link bên dưới để thiết lập lại mật khẩu: <br/><br/><a href='" + link + "'>" + link + "</a>", email);
                 if (s)
                 {
                     result.status = Constants.NUMBER_CODE.SUCCESS;
                     result.msg    = "Vui lòng kiểm tra Email để xác nhận lấy lại mật khẩu mới";
                 }
                 else
                 {
                     result.status = Constants.NUMBER_CODE.SEND_MAIL_FAILD;
                     result.msg    = "Lỗi hệ thống vui lòng thử lại!";
                 }
             }
             else
             {
                 result.status = (Constants.NUMBER_CODE)code;
                 result.msg    = result.status.ToString();
             }
         }
         else
         {
             result.status = Constants.NUMBER_CODE.DATA_NULL;
             result.msg    = "Email không được để trống!";
         }
     }
     catch (Exception ex)
     {
         Logs.SaveError("ERROR CREATE_ACCOUNT: " + ex);
         result.status = Constants.NUMBER_CODE.ERROR_EX;
         result.msg    = Constants.NUMBER_CODE.ERROR_EX.ToString();
     }
     context.Response.Write(JsonConvert.SerializeObject(result));
 }
Beispiel #49
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                string pass = Encryptor.MD5Hash(model.PassWord);
                using (ELearningDB db = new ELearningDB())
                {
                    var res = db.TaiKhoans.Where(x => x.Username == model.UserName && x.Password == pass).FirstOrDefault();
                    if (res != null)
                    {
                        if (res.TrangThai != false)
                        {
                            var userSession = new TaiKhoanLogin();
                            userSession.ID       = res.ID;
                            userSession.loai     = res.Role;
                            userSession.UserName = res.Username;
                            Session.Add(CommonConstants.USER_SESSION, userSession);

                            Session.Add("User", res);

                            if (res.Role == 2)
                            {
                                GiangVien gv = db.GiangViens.Find(res.ID);
                                if (gv.HoVaTen == null)
                                {
                                    return(RedirectToAction("FirstLogin", "User", new { area = "GV", id = gv.ID }));
                                }
                                Session.Add("Hoten", res.GiangVien.HoVaTen);
                                return(RedirectToAction("TrangChu", "HomeGV", new { area = "GV" }));
                            }
                            else
                            {
                                if (res.Role == 3)
                                {
                                    HocVien hv = db.HocViens.Find(res.ID);
                                    if (hv.HoVaTen == null)
                                    {
                                        return(RedirectToAction("FirstLogin", "User", new { id = hv.ID }));
                                    }

                                    Session.Add("Hoten", res.HocVien.HoVaTen);
                                    return(RedirectToAction("TrangChu", "Home"));
                                }
                                else
                                {
                                    if (res.Role == 1)
                                    {
                                        return(RedirectToAction("Index", "Home", new { area = "Admin" }));
                                    }
                                    else
                                    {
                                        if (res.Role == 4)
                                        {
                                            NguoiDung user = db.NguoiDungs.Find(res.ID);
                                            Session.Add("Hoten", res.NguoiDung.HoVaTen);
                                            return(RedirectToAction("GuessHomePage", "Home"));
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "Tài khoản này hiện đang bị khóa");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Tên tài khoản hoặc mật khẩu không đúng");
                    }
                }
            }
            return(View("Index"));
        }
        private void CHANGE_DISPLAY_AGENCY(HttpContext context)
        {
            try
            {
                if (context.Session["CHANGE_DISPLAY_AGENCY"] == null || (DateTime.Now - (DateTime)context.Session["CHANGE_DISPLAY_AGENCY"]).TotalMilliseconds > Constants.TIME_REQUEST)
                {
                    UpdateDisplayAgencyEntity jsonData = new UpdateDisplayAgencyEntity();
                    bool display = true;
                    if (string.IsNullOrEmpty(context.Request.Form["display"]))
                    {
                        result.status = Constants.NUMBER_CODE.DATA_NULL;
                        result.msg    = "Giá trị chọn không tồn tại!";
                    }
                    else if (!bool.TryParse(context.Request.Form["display"], out display))
                    {
                        result.status = Constants.NUMBER_CODE.TRYPARSE_ERROR;
                        result.msg    = "Dữ liệu truyền vào không đúng!";
                    }
                    else if (string.IsNullOrEmpty(context.Request.Form["agencyID"]))
                    {
                        result.status = Constants.NUMBER_CODE.DATA_NULL;
                        result.msg    = "Tài khoản không tồn tại!";
                    }

                    else
                    {
                        display              = bool.Parse(context.Request.Form["display"]);
                        jsonData.agencyID    = context.Request.Form["agencyID"];
                        jsonData.display     = display;
                        jsonData.creatorID   = accountInfo.AccountId;
                        jsonData.creatorName = accountInfo.UserName;
                        jsonData.ip          = UtilClass.GetIPAddress();
                        //Logs.SaveLog("jsonData TRANFER_MONEY_TO_AGENCY_USER" + JsonConvert.SerializeObject(jsonData));
                        PayloadApi p = new PayloadApi()
                        {
                            clientIP = UtilClass.GetIPAddress(),
                            data     = Encryptor.EncryptString(JsonConvert.SerializeObject(jsonData), Constants.API_SECRETKEY)
                        };
                        var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "api/v1/Agency/UpdateDisplay_Agency");
                        context.Response.Write(responseData);
                        return;
                    }
                }
                else
                {
                    result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER;
                    result.msg    = "Thao tác quá nhanh! vui lòng thử lại";
                }
            }
            catch (Exception ex)
            {
                Logs.SaveError("ERROR CHANGE_DISPLAY_AGENCY: " + ex);
                result.status = Constants.NUMBER_CODE.ERROR_EX;
                result.msg    = ex.ToString();
            }
            finally
            {
                context.Session["CHANGE_DISPLAY_AGENCY"] = DateTime.Now;
            }
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
        public void Setup()
        {
            var settings = new EncryptionSettings(new HmacSHA256KeyGenerator(HashAlgorithmNames.Sha256));

            Encryptor.init(settings);
        }
Beispiel #52
0
        static private void ExampleCKKSEncoder()
        {
            Utilities.PrintExampleBanner("Example: Encoders / CKKS Encoder");

            /*
             * [CKKSEncoder] (For CKKS scheme only)
             *
             * In this example we demonstrate the Cheon-Kim-Kim-Song (CKKS) scheme for
             * computing on encrypted real or complex numbers. We start by creating
             * encryption parameters for the CKKS scheme. There are two important
             * differences compared to the BFV scheme:
             *
             *  (1) CKKS does not use the PlainModulus encryption parameter;
             *  (2) Selecting the CoeffModulus in a specific way can be very important
             *      when using the CKKS scheme. We will explain this further in the file
             *      `CKKS_Basics.cs'. In this example we use CoeffModulus.Create to
             *      generate 5 40-bit prime numbers.
             */
            using EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);

            ulong polyModulusDegree = 8192;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.Create(
                polyModulusDegree, new int[] { 40, 40, 40, 40, 40 });

            /*
             * We create the SEALContext as usual and print the parameters.
             */
            using SEALContext context = new SEALContext(parms);
            Utilities.PrintParameters(context);
            Console.WriteLine();

            /*
             * Keys are created the same way as for the BFV scheme.
             */
            using KeyGenerator keygen = new KeyGenerator(context);
            using SecretKey secretKey = keygen.SecretKey;
            keygen.CreatePublicKey(out PublicKey publicKey);
            keygen.CreateRelinKeys(out RelinKeys relinKeys);

            /*
             * We also set up an Encryptor, Evaluator, and Decryptor as usual.
             */
            using Encryptor encryptor = new Encryptor(context, publicKey);
            using Evaluator evaluator = new Evaluator(context);
            using Decryptor decryptor = new Decryptor(context, secretKey);

            /*
             * To create CKKS plaintexts we need a special encoder: there is no other way
             * to create them. The BatchEncoder cannot be used with the
             * CKKS scheme. The CKKSEncoder encodes vectors of real or complex numbers into
             * Plaintext objects, which can subsequently be encrypted. At a high level this
             * looks a lot like what BatchEncoder does for the BFV scheme, but the theory
             * behind it is completely different.
             */
            using CKKSEncoder encoder = new CKKSEncoder(context);

            /*
             * In CKKS the number of slots is PolyModulusDegree / 2 and each slot encodes
             * one real or complex number. This should be contrasted with BatchEncoder in
             * the BFV scheme, where the number of slots is equal to PolyModulusDegree
             * and they are arranged into a matrix with two rows.
             */
            ulong slotCount = encoder.SlotCount;

            Console.WriteLine($"Number of slots: {slotCount}");

            /*
             * We create a small vector to encode; the CKKSEncoder will implicitly pad it
             * with zeros to full size (PolyModulusDegree / 2) when encoding.
             */
            double[] input = new double[] { 0.0, 1.1, 2.2, 3.3 };
            Console.WriteLine("Input vector: ");
            Utilities.PrintVector(input);

            /*
             * Now we encode it with CKKSEncoder. The floating-point coefficients of `input'
             * will be scaled up by the parameter `scale'. This is necessary since even in
             * the CKKS scheme the plaintext elements are fundamentally polynomials with
             * integer coefficients. It is instructive to think of the scale as determining
             * the bit-precision of the encoding; naturally it will affect the precision of
             * the result.
             *
             * In CKKS the message is stored modulo CoeffModulus (in BFV it is stored modulo
             * PlainModulus), so the scaled message must not get too close to the total size
             * of CoeffModulus. In this case our CoeffModulus is quite large (200 bits) so
             * we have little to worry about in this regard. For this simple example a 30-bit
             * scale is more than enough.
             */
            using Plaintext plain = new Plaintext();
            double scale = Math.Pow(2.0, 30);

            Utilities.PrintLine();
            Console.WriteLine("Encode input vector.");
            encoder.Encode(input, scale, plain);

            /*
             * We can instantly decode to check the correctness of encoding.
             */
            List <double> output = new List <double>();

            Console.WriteLine("    + Decode input vector ...... Correct.");
            encoder.Decode(plain, output);
            Utilities.PrintVector(output);

            /*
             * The vector is encrypted the same was as in BFV.
             */
            using Ciphertext encrypted = new Ciphertext();
            Utilities.PrintLine();
            Console.WriteLine("Encrypt input vector, square, and relinearize.");
            encryptor.Encrypt(plain, encrypted);

            /*
             * Basic operations on the ciphertexts are still easy to do. Here we square
             * the ciphertext, decrypt, decode, and print the result. We note also that
             * decoding returns a vector of full size (PolyModulusDegree / 2); this is
             * because of the implicit zero-padding mentioned above.
             */
            evaluator.SquareInplace(encrypted);
            evaluator.RelinearizeInplace(encrypted, relinKeys);

            /*
             * We notice that the scale in the result has increased. In fact, it is now
             * the square of the original scale: 2^60.
             */
            Console.WriteLine("    + Scale in squared input: {0} ({1} bits)",
                              encrypted.Scale,
                              (int)Math.Ceiling(Math.Log(encrypted.Scale, newBase: 2)));
            Utilities.PrintLine();
            Console.WriteLine("Decrypt and decode.");
            decryptor.Decrypt(encrypted, plain);
            encoder.Decode(plain, output);
            Console.WriteLine("    + Result vector ...... Correct.");
            Utilities.PrintVector(output);

            /*
             * The CKKS scheme allows the scale to be reduced between encrypted computations.
             * This is a fundamental and critical feature that makes CKKS very powerful and
             * flexible. We will discuss it in great detail in `3_Levels.cs' and later in
             * `4_CKKS_Basics.cs'.
             */
        }
Beispiel #53
0
        /*
         * In `1_BFV_Basics.cs' we showed how to perform a very simple computation using the
         * BFV scheme. The computation was performed modulo the PlainModulus parameter, and
         * utilized only one coefficient from a BFV plaintext polynomial. This approach has
         * two notable problems:
         *
         *  (1) Practical applications typically use integer or real number arithmetic,
         *      not modular arithmetic;
         *  (2) We used only one coefficient of the plaintext polynomial. This is really
         *      wasteful, as the plaintext polynomial is large and will in any case be
         *      encrypted in its entirety.
         *
         * For (1), one may ask why not just increase the PlainModulus parameter until no
         * overflow occurs, and the computations behave as in integer arithmetic. The problem
         * is that increasing PlainModulus increases noise budget consumption, and decreases
         * the initial noise budget too.
         *
         * In these examples we will discuss other ways of laying out data into plaintext
         * elements (encoding) that allow more computations without data type overflow, and
         * can allow the full plaintext polynomial to be utilized.
         */
        private static void ExampleBatchEncoder()
        {
            Utilities.PrintExampleBanner("Example: Encoders / Batch Encoder");

            /*
             * [BatchEncoder] (For BFV or BGV scheme)
             *
             * Let N denote the PolyModulusDegree and T denote the PlainModulus. Batching
             * allows the BFV plaintext polynomials to be viewed as 2-by-(N/2) matrices, with
             * each element an integer modulo T. In the matrix view, encrypted operations act
             * element-wise on encrypted matrices, allowing the user to obtain speeds-ups of
             * several orders of magnitude in fully vectorizable computations. Thus, in all
             * but the simplest computations, batching should be the preferred method to use
             * with BFV, and when used properly will result in implementations outperforming
             * anything done without batching.
             *
             * In a later example, we will demonstrate how to use the BGV scheme. Batching
             * works similarly for the BGV scheme to this example for the BFV scheme. For
             * example, simply changing `SchemeType.BFV` into `SchemeType.BGV` can make
             * this example work for the BGV scheme.
             */
            using EncryptionParameters parms = new EncryptionParameters(SchemeType.BFV);
            ulong polyModulusDegree = 8192;

            parms.PolyModulusDegree = polyModulusDegree;
            parms.CoeffModulus      = CoeffModulus.BFVDefault(polyModulusDegree);

            /*
             * To enable batching, we need to set the plain_modulus to be a prime number
             * congruent to 1 modulo 2*PolyModulusDegree. Microsoft SEAL provides a helper
             * method for finding such a prime. In this example we create a 20-bit prime
             * that supports batching.
             */
            parms.PlainModulus = PlainModulus.Batching(polyModulusDegree, 20);

            using SEALContext context = new SEALContext(parms);
            Utilities.PrintParameters(context);
            Console.WriteLine();

            /*
             * We can verify that batching is indeed enabled by looking at the encryption
             * parameter qualifiers created by SEALContext.
             */
            using var qualifiers = context.FirstContextData.Qualifiers;
            Console.WriteLine($"Batching enabled: {qualifiers.UsingBatching}");

            using KeyGenerator keygen = new KeyGenerator(context);
            using SecretKey secretKey = keygen.SecretKey;
            keygen.CreatePublicKey(out PublicKey publicKey);
            keygen.CreateRelinKeys(out RelinKeys relinKeys);
            using Encryptor encryptor = new Encryptor(context, publicKey);
            using Evaluator evaluator = new Evaluator(context);
            using Decryptor decryptor = new Decryptor(context, secretKey);

            /*
             * Batching is done through an instance of the BatchEncoder class.
             */
            using BatchEncoder batchEncoder = new BatchEncoder(context);

            /*
             * The total number of batching `slots' equals the PolyModulusDegree, N, and
             * these slots are organized into 2-by-(N/2) matrices that can be encrypted and
             * computed on. Each slot contains an integer modulo PlainModulus.
             */
            ulong slotCount = batchEncoder.SlotCount;
            ulong rowSize   = slotCount / 2;

            Console.WriteLine($"Plaintext matrix row size: {rowSize}");

            /*
             * The matrix plaintext is simply given to BatchEncoder as a flattened vector
             * of numbers. The first `rowSize' many numbers form the first row, and the
             * rest form the second row. Here we create the following matrix:
             *
             *  [ 0,  1,  2,  3,  0,  0, ...,  0 ]
             *  [ 4,  5,  6,  7,  0,  0, ...,  0 ]
             */
            ulong[] podMatrix = new ulong[slotCount];
            podMatrix[0]           = 0;
            podMatrix[1]           = 1;
            podMatrix[2]           = 2;
            podMatrix[3]           = 3;
            podMatrix[rowSize]     = 4;
            podMatrix[rowSize + 1] = 5;
            podMatrix[rowSize + 2] = 6;
            podMatrix[rowSize + 3] = 7;

            Console.WriteLine("Input plaintext matrix:");
            Utilities.PrintMatrix(podMatrix, (int)rowSize);

            /*
             * First we use BatchEncoder to encode the matrix into a plaintext polynomial.
             */
            using Plaintext plainMatrix = new Plaintext();
            Utilities.PrintLine();
            Console.WriteLine("Encode plaintext matrix:");
            batchEncoder.Encode(podMatrix, plainMatrix);

            /*
             * We can instantly decode to verify correctness of the encoding. Note that no
             * encryption or decryption has yet taken place.
             */
            List <ulong> podResult = new List <ulong>();

            Console.WriteLine("    + Decode plaintext matrix ...... Correct.");
            batchEncoder.Decode(plainMatrix, podResult);
            Utilities.PrintMatrix(podResult, (int)rowSize);

            /*
             * Next we encrypt the encoded plaintext.
             */
            using Ciphertext encryptedMatrix = new Ciphertext();
            Utilities.PrintLine();
            Console.WriteLine("Encrypt plainMatrix to encryptedMatrix.");
            encryptor.Encrypt(plainMatrix, encryptedMatrix);
            Console.WriteLine("    + Noise budget in encryptedMatrix: {0} bits",
                              decryptor.InvariantNoiseBudget(encryptedMatrix));

            /*
             * Operating on the ciphertext results in homomorphic operations being performed
             * simultaneously in all 8192 slots (matrix elements). To illustrate this, we
             * form another plaintext matrix
             *
             *  [ 1,  2,  1,  2,  1,  2, ..., 2 ]
             *  [ 1,  2,  1,  2,  1,  2, ..., 2 ]
             *
             * and encode it into a plaintext.
             */
            ulong[] podMatrix2 = new ulong[slotCount];
            for (ulong i = 0; i < slotCount; i++)
            {
                podMatrix2[i] = (i & 1) + 1;
            }
            using Plaintext plainMatrix2 = new Plaintext();
            batchEncoder.Encode(podMatrix2, plainMatrix2);
            Console.WriteLine();
            Console.WriteLine("Second input plaintext matrix:");
            Utilities.PrintMatrix(podMatrix2, (int)rowSize);

            /*
             * We now add the second (plaintext) matrix to the encrypted matrix, and square
             * the sum.
             */
            Utilities.PrintLine();
            Console.WriteLine("Sum, square, and relinearize.");
            evaluator.AddPlainInplace(encryptedMatrix, plainMatrix2);
            evaluator.SquareInplace(encryptedMatrix);
            evaluator.RelinearizeInplace(encryptedMatrix, relinKeys);

            /*
             * How much noise budget do we have left?
             */
            Console.WriteLine("    + Noise budget in result: {0} bits",
                              decryptor.InvariantNoiseBudget(encryptedMatrix));

            /*
             * We decrypt and decompose the plaintext to recover the result as a matrix.
             */
            using Plaintext plainResult = new Plaintext();
            Utilities.PrintLine();
            Console.WriteLine("Decrypt and decode result.");
            decryptor.Decrypt(encryptedMatrix, plainResult);
            batchEncoder.Decode(plainResult, podResult);
            Console.WriteLine("    + Result plaintext matrix ...... Correct.");
            Utilities.PrintMatrix(podResult, (int)rowSize);

            /*
             * Batching allows us to efficiently use the full plaintext polynomial when the
             * desired encrypted computation is highly parallelizable. However, it has not
             * solved the other problem mentioned in the beginning of this file: each slot
             * holds only an integer modulo plain_modulus, and unless plain_modulus is very
             * large, we can quickly encounter data type overflow and get unexpected results
             * when integer computations are desired. Note that overflow cannot be detected
             * in encrypted form. The CKKS scheme (and the CKKSEncoder) addresses the data
             * type overflow issue, but at the cost of yielding only approximate results.
             */
        }
Beispiel #54
0
        public void IsCorrect_ShouldCheckIfDataIsCorrect()
        {
            bool actual = new LoginValidator().IsCorrect(Encryptor.Encrypt("teacher1"), Encryptor.Encrypt("teacher1"), "teacher");

            Assert.True(actual);
        }
Beispiel #55
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="file"></param>
        /// <param name="hash"></param>
        /// <param name="data"></param>
        /// <returns>fileId</returns>
        private async Task <(byte[] encryptedHash, string fileId)> StoreFileAsync(string file, byte[] hash, byte[] data, bool preventEncryption = false)
        {
            async Task <GetUploadUrlResponse> GetUploadUrl(int attempts = 0)
            {
                if (AuthResp == null)
                {
                    AuthResp = await AuthorizeAccount();
                }
                Delay();
                try
                {
                    var urlresp = await AuthResp.apiUrl
                                  .AppendPathSegment("/b2api/v1/b2_get_upload_url")
                                  .WithHeaders(new { Authorization = AuthResp.authorizationToken })
                                  .PostJsonAsync(new { bucketId = BucketId })
                                  .ReceiveJson <GetUploadUrlResponse>().ConfigureAwait(false);

                    SuccessfulTransmission();
                    return(urlresp);
                }
                catch (FlurlHttpException ex)
                {
                    if (ex.Call.HttpStatus != null && ex.Call.HttpStatus == System.Net.HttpStatusCode.Unauthorized)
                    {
                        AuthResp = null;
                    }
                    else
                    {
                        // Other classes of errors may be congestion related so we increase the delay
                        FailedTransmission();
                    }
                    if (attempts < Retries)
                    {
                        return(await GetUploadUrl(attempts + 1).ConfigureAwait(false));
                    }
                    throw;
                }
            }

            var hashFileId = await UploadData();

            async Task <(byte[] encryptedHash, string fileId)> UploadData(int attempts = 0)
            {
                if (UploadUrlResp == null)
                {
                    UploadUrlResp = await GetUploadUrl();
                }
                Delay();
                try
                {
                    if (Encryptor != null && !preventEncryption)
                    {
                        data = Encryptor.EncryptBytes(data);
                        hash = HashTools.GetSHA1Hasher().ComputeHash(data);
                    }

                    var filecontent = new ByteArrayContent(data);
                    filecontent.Headers.Add("Content-Type", "application/octet-stream");
                    var uploadresp = await UploadUrlResp.uploadUrl
                                     .WithHeaders(new
                    {
                        Authorization     = UploadUrlResp.authorizationToken,
                        X_Bz_File_Name    = file,
                        Content_Length    = data.Length,
                        X_Bz_Content_Sha1 = HashTools.ByteArrayToHexViaLookup32(hash)
                    })
                                     .PostAsync(filecontent)
                                     .ReceiveJson <UploadResponse>().ConfigureAwait(false);

                    SuccessfulTransmission();
                    return(hash, uploadresp.fileId);
                }
                catch (FlurlHttpException ex)
                {
                    if (ex.Call.HttpStatus != null && ex.Call.HttpStatus == System.Net.HttpStatusCode.Unauthorized)
                    {
                        UploadUrlResp = null;
                    }
                    else
                    {
                        // Other classes of errors may be congestion related so we increase the delay
                        FailedTransmission();
                    }

                    if (attempts < Retries)
                    {
                        return(await UploadData(attempts + 1).ConfigureAwait(false));
                    }
                    throw;
                }
            }

            return(hashFileId);
        }
Beispiel #56
0
        public User FindByPhoneNumber(string phoneNumber)
        {
            var user = dao.Find.ByUniqueID("Phone", Encryptor.EncryptSHA256(phoneNumber));

            return(user);
        }
Beispiel #57
0
 private MembershipCreateStatus CreateUser(RegisterModel model)
 {
     if (!db.Users.Where(u => u.Name == model.UserName).Any())
     {
         if (!db.Users.Where(u => u.Email == model.Email).Any())
         {
             User user = new User();
             user.Creation = DateTime.Now;
             string source = model.Password;
             using (MD5 md5Hash = MD5.Create())
             {
                 Encryptor enc = new Encryptor();
                 string hash = enc.GetMd5Hash(md5Hash, source);
                 if (enc.VerifyMd5Hash(md5Hash, source, hash))
                 {
                     user.Name = model.UserName;
                     user.Email = model.Email;
                     user.Password = hash;
                     user.Status = 1;
                     db.Users.AddObject(user);
                     db.SaveChanges();
                     return MembershipCreateStatus.Success;
                 }
                 else
                 {
                     return MembershipCreateStatus.ProviderError;
                 }
             }
         }
         else
         {
             return MembershipCreateStatus.DuplicateEmail;
         }
     }
     else
     {
         return MembershipCreateStatus.DuplicateUserName;
     }
 }
        public static void DoIt()
        {
            Console.WriteLine(DateTime.Now + " Generate key pair...");
            PgpKeyPairGenerator pgpKeyPairGenerator = new PgpKeyPairGenerator(identity, passphrase.ToCharArray(), pgpAsymAlgo, pgpAsymKeyLength);
            PgpKeyPairHolder    pgpKeyPairHolder    = pgpKeyPairGenerator.Generate();

            List <PgpPublicKey> encKeys = new List <PgpPublicKey>();

            encKeys.Add(PgpPublicKeyGetter.ReadPublicKey(pgpKeyPairHolder.PublicKeyRing));

            Encryptor encryptor = new Encryptor(true, false);

            List <String> encryptedvalues = new List <string>();

            const int cpt = 200;

            Console.WriteLine(DateTime.Now + " Text encryption... In loop " + cpt + " times:");

            for (int i = 0; i < cpt; i++)
            {
                string clearValue     = "This_is_a_full_plain_subject_for_an_email_text_" + i;
                string encryptedValue = encryptor.Encrypt(encKeys, clearValue);
                encryptedvalues.Add(encryptedValue);
            }
            Console.WriteLine(DateTime.Now + " Text encryption done!");
            Console.WriteLine();

            Decryptor decryptor = new Decryptor(pgpKeyPairHolder.PrivateKeyRing, passphrase.ToCharArray());

            Console.WriteLine(DateTime.Now + " Starting decryption... In loop " + cpt + " times:");

            DateTime dtBegin = DateTime.Now;

            List <String> decryptedValues = new List <string>();

            for (int i = 0; i < cpt; i++)
            {
                string decryptedValue = decryptor.Decrypt(encryptedvalues[i]);
                decryptedValues.Add(decryptedValue);
            }

            DateTime dtEnd = DateTime.Now;
            TimeSpan span  = dtEnd - dtBegin;
            int      ms    = (int)span.TotalMilliseconds;

            Console.WriteLine(DateTime.Now + " Text decryption done!");
            Console.WriteLine(DateTime.Now + " Decryption Elasped in Milliseconds: " + ms);

            Console.WriteLine("Press enter to continue....");
            Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine("Display decrypted values: ");

            for (int i = 0; i < cpt; i++)
            {
                Console.WriteLine(decryptedValues[i]);
            }

            Console.WriteLine();
            Console.WriteLine("Done!");
            Console.WriteLine("Press enter to close....");
            Console.ReadLine();
        }
        public override async Task <Student> Add(Student newModel)
        {
            newModel.Password = Encryptor.Encrypt(newModel.Password);

            return(await base.Add(newModel));
        }
        public RegistrationCode FindByPhoneNumber(string phoneNumber)
        {
            var value = dao.Find.ByUniqueID("Phone", Encryptor.EncryptSHA256(phoneNumber));

            return(value);
        }