Ejemplo n.º 1
0
        public async Task <String> RetrieveDHSessionKey(String PublickKey)
        {
            String DecryptedServerNumber;
            String readString = await ActivitySocket.read();

            ReadObj = JsonParse.ReadObject(readString);
            if (FingerPrint.Verification(ReadObj.getServerPrimeNumber(), PublickKey, ReadObj.getFingerPrint()))
            {
                if (MacAlgProvider.VerifyHMAC(ReadObj.getServerPrimeNumber(), SymmetricKey.StrKeyBase64,
                                              ReadObj.getHmacHash()))
                {
                    DecryptedServerNumber = AesEncryption.AES_Decrypt(ReadObj.getServerPrimeNumber(),
                                                                      SymmetricKey.StrKeyBase64);
                }
                else
                {
                    throw new Exception("Integrity of SymmetricKey canot verified");
                }
            }

            else
            {
                throw new Exception("Integrity of RSA canot verified");
            }

            return(GeneratoreMachine.SessionDHGenerator(DecryptedServerNumber));
        }
Ejemplo n.º 2
0
        //retrieval of email
        private bool checkEmail()
        {
            AesEncryption aes   = new AesEncryption();
            bool          exist = false;

            using (MySqlConnection con = new MySqlConnection("server = 35.240.129.112; user id = asguarduser; database = da_schema"))
            {
                con.Open();
                String       query   = "SELECT * FROM Userinfo";
                MySqlCommand command = new MySqlCommand(query, con);

                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (Email.Text == aes.Decryptstring(reader.GetString(reader.GetOrdinal("email")), reader.GetString(reader.GetOrdinal("userid"))))
                        {
                            exist = true;
                        }
                    }

                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
            return(exist);
        }
        public static byte[] GetStatistics(byte[] key, byte[] iv, int carwashId)
        {
            AesEncryption aes        = new AesEncryption();
            Statistics    statistics = new Statistics();
            Carwash       carwash    = CarwashRepository.GetCarwash(carwashId);

            statistics.TotalWashes = carwash.Washes.Count;

            foreach (Wash wash in carwash.Washes)
            {
                if (wash is BasicWash)
                {
                    statistics.BasicWashes++;
                }
                if (wash is SilverWash)
                {
                    statistics.SilverWashes++;
                }
                if (wash is GoldWash)
                {
                    statistics.GoldWashes++;
                }
            }

            string json = JsonHelper.SerializeJson <Statistics>(statistics);

            return(aes.Encrypt(json, key, iv));
        }
Ejemplo n.º 4
0
        //retrieve account based on  filter
        private void userdataRetrieval2(string listvalue, ArrayList searchfield)
        {
            AesEncryption aes = new AesEncryption();

            for (int i = 0; i < searchfield.Count; i++)
            {
                using (MySqlConnection con = new MySqlConnection("server = 35.240.129.112; user id = asguarduser; database = da_schema"))
                {
                    con.Open();
                    String       query   = "SELECT * FROM Userinfo where userid = @searchfield";
                    MySqlCommand command = new MySqlCommand(query, con);
                    command.Parameters.AddWithValue("@searchfield", searchfield[i].ToString());
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            ArrayList row = new ArrayList();
                            row.Add(reader.GetInt32(reader.GetOrdinal("userid")));
                            row.Add(aes.Decryptstring(reader.GetString(reader.GetOrdinal("username")), reader.GetString(reader.GetOrdinal("userid"))));
                            row.Add(aes.Decryptstring(reader.GetString(reader.GetOrdinal("email")), reader.GetString(reader.GetOrdinal("userid"))));
                            row.Add(reader.GetString(reader.GetOrdinal("firstname")) + " " + reader.GetString(reader.GetOrdinal("lastname")));
                            row.Add(aes.Decryptstring(reader.GetString(reader.GetOrdinal("contact")), reader.GetString(reader.GetOrdinal("userid"))));
                            row.Add(reader.GetString(reader.GetOrdinal("verificationflag")));
                            dataAccountGrid.Rows.Add(row.ToArray());
                        }

                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
            }
        }
Ejemplo n.º 5
0
        //retrieve account
        private void userdataRetrieval()
        {
            AesEncryption aes   = new AesEncryption();
            int           count = 0;

            using (MySqlConnection con = new MySqlConnection("server = 35.240.129.112; user id = asguarduser; database = da_schema"))
            {
                con.Open();
                String       query   = "SELECT * FROM Userinfo";
                MySqlCommand command = new MySqlCommand(query, con);

                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        ArrayList row = new ArrayList();
                        row.Add(reader.GetInt32(reader.GetOrdinal("userid")));
                        row.Add(aes.Decryptstring(reader.GetString(reader.GetOrdinal("username")), reader.GetString(reader.GetOrdinal("userid"))));
                        row.Add(aes.Decryptstring(reader.GetString(reader.GetOrdinal("email")), reader.GetString(reader.GetOrdinal("userid"))));
                        row.Add(reader.GetString(reader.GetOrdinal("firstname")) + " " + reader.GetString(reader.GetOrdinal("lastname")));
                        row.Add(aes.Decryptstring(reader.GetString(reader.GetOrdinal("contact")), reader.GetString(reader.GetOrdinal("userid"))));
                        row.Add(reader.GetString(reader.GetOrdinal("verificationflag")));
                        dataAccountGrid.Rows.Add(row.ToArray());
                        count++;
                    }
                    noOfAccounts.Text = count.ToString();
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
        public ObsWebsocketSettingDataModel Load()
        {
            if (loaded)
            {
                return(cache);
            }

            var data = FileIOUtility.Read <ObsWebsocketSettingDataModel>("ObsWebsocket");

            try
            {
                data.ServerAddress = AesEncryption.Decrypt(data.ServerAddress);
                data.Password      = AesEncryption.Decrypt(data.Password);
            }
            catch (Exception e)
            {
                Debug.LogError("Encryption info is updated. please re-enter address and password.");
                data.ServerAddress = "";
                data.Password      = "";
            }

            loaded = true;

            cache = data;

            return(data);
        }
Ejemplo n.º 7
0
        public void TestPassPhrase()
        {
            // encrypt and decrypt
            AesEncryption aes = new AesEncryption("AustralianOpenTennis2008");

            aes.EncryptFile(TestFile, TestFileEncrypted);
            aes.DecryptFile(TestFileEncrypted, TestFileDecrypted);

            // test results
            Hashing h = new Hashing();

            byte[] b     = h.Sha512HashFile(TestFile);
            string hash1 = Convert.ToBase64String(b);

            Console.WriteLine(hash1);

            b = h.Sha512HashFile(TestFileEncrypted);
            string hash2 = Convert.ToBase64String(b);

            Console.WriteLine(hash2);

            b = h.Sha512HashFile(TestFileDecrypted);
            string hash3 = Convert.ToBase64String(b);

            Console.WriteLine(hash3);

            Assert.AreEqual(hash1, hash3);
            Assert.AreNotEqual(hash1, hash2);
        }
Ejemplo n.º 8
0
        //string salt = "!@3esxC$Wqasdrt6yUJKO(*&";

        public void encodeConnection(string p, string aDB, string pDB)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            string password = p;                                                // Key for encryption
            string serverDB = AesEncryption.EncryptWithPassword(aDB, password); // Server DB
            string passwdDB = AesEncryption.EncryptWithPassword(pDB, password); // Password to DB


            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("kycu");  // Server adrdess
                writer.WriteValue(serverDB);
                writer.WritePropertyName("losiu"); // Password
                writer.WriteValue(passwdDB);
                writer.WriteEndObject();
            }

            File.WriteAllText(@"C:\Projekty\TicketApp\MaturaZGier\keys.json", sb.ToString());
            MessageBox.Show("Para kluczy została wygenerowana");
        }
Ejemplo n.º 9
0
        static string DecryptValueCommand(string?value)
        {
            var encrypted    = VariableEncryptor.Encrypt(value ?? "");
            var rawEncrypted = AesEncryption.ExtractIV(encrypted, out var iv);

            return($@"decrypt(""{Convert.ToBase64String(rawEncrypted)}"",""{ToHex(iv)}"")");
        }
        private void InitAndEncryptLocalLogin()
        {
            if (_cache.Contains(StringConstants.AesKeyCacheKey) == false)
            {
                _encoder.GenerateKey();
                _encoder.GenerateIV();
                _cache[StringConstants.AesKeyCacheKey]    = _encoder.Key;
                _cache[StringConstants.AesVectorCacheKey] = _encoder.IV;
            }
            else
            {
                _encoder.Key = (byte[])_cache[StringConstants.AesKeyCacheKey];
                _encoder.IV  = (byte[])_cache[StringConstants.AesVectorCacheKey];
            }

            //set up user name and password
            _userName = _cache[StringConstants.UserNameCacheKey] as string;
            var passwordBytes = _cache[StringConstants.PasswordCacheKey] as byte[];

            try
            {
                _userPassword = AesEncryption.DecryptStringFromBytes_Aes(passwordBytes, _encoder.Key, _encoder.IV);
            }
            catch (Exception)
            {
                // ignored
            }
        }
Ejemplo n.º 11
0
            /// <summary>
            /// Ctor - create encr data field
            /// </summary>
            /// <param name="type"></param>
            /// <param name="id">Action ID</param>
            /// <param name="aes">AesEncryption</param>
            /// <param name="sIV">Only for testing, normally pass null to generate</param>
            public E_ACTION(type type, int id, AesEncryption aes, string sIV = null)
            {
                ACTION action = new ACTION(type, id);

                this.data = MakeEncr(action, aes, sIV);
                this.mac  = hmac(data, aes);
            }
Ejemplo n.º 12
0
        public string FormatCommandArguments(string bootstrapFile, string debuggingBootstrapFile, IVariables variables)
        {
            var encryptionKey         = Convert.ToBase64String(AesEncryption.GetEncryptionKey(SensitiveVariablePassword));
            var commandArguments      = new StringBuilder();
            var executeWithoutProfile = variables[PowerShellVariables.ExecuteWithoutProfile];
            var traceCommand          = GetPsDebugCommand(variables);

            foreach (var argument in ContributeCommandArguments(variables))
            {
                commandArguments.Append(argument);
            }

            bool noProfile;

            if (bool.TryParse(executeWithoutProfile, out noProfile) && noProfile)
            {
                commandArguments.Append("-NoProfile ");
            }
            commandArguments.Append("-NoLogo ");
            commandArguments.Append("-NonInteractive ");
            commandArguments.Append("-ExecutionPolicy Unrestricted ");

            var fileToExecute = IsDebuggingEnabled(variables)
                ? debuggingBootstrapFile.EscapeSingleQuotedString()
                : bootstrapFile.EscapeSingleQuotedString();

            commandArguments.AppendFormat("-Command \"{0}Try {{. {{. '{1}' -OctopusKey '{2}'; if ((test-path variable:global:lastexitcode)) {{ exit $LastExitCode }}}};}} catch {{ throw }}\"", traceCommand, fileToExecute, encryptionKey);
            return(commandArguments.ToString());
        }
Ejemplo n.º 13
0
        private void userdataRetrieval()
        {
            AesEncryption aes = new AesEncryption();

            using (MySqlConnection con = new MySqlConnection("server = 35.240.129.112; user id = asguarduser; database = da_schema"))
            {
                con.Open();
                String       query   = "SELECT * FROM Userinfo WHERE userid=@userid";
                MySqlCommand command = new MySqlCommand(query, con);
                command.Parameters.AddWithValue("@userid", CSClass.Logininfo.userid.ToString());
                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Username.Text = aes.Decryptstring(reader.GetString(reader.GetOrdinal("username")), Logininfo.userid.ToString());
                        FName.Text    = reader.GetString(reader.GetOrdinal("firstname")) + " " + reader.GetString(reader.GetOrdinal("lastname"));
                        Contact.Text  = "****" + aes.Decryptstring(reader.GetString(reader.GetOrdinal("contact")), Logininfo.userid.ToString()).Substring(4, 4);
                        Email.Text    = aes.Decryptstring(reader.GetString(reader.GetOrdinal("email")), Logininfo.userid.ToString());
                        DOB.Text      = reader.GetString(reader.GetOrdinal("dob"));
                    }

                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
Ejemplo n.º 14
0
        static string EncryptVariable(string value)
        {
            var encrypted    = VariableEncryptor.Encrypt(value);
            var rawEncrypted = AesEncryption.ExtractIV(encrypted, out var iv);

            return($@"decryptString ""{Convert.ToBase64String(rawEncrypted)}"" ""{Convert.ToBase64String(iv)}""");
        }
        protected override void CopyModelToData(hcc_OrderTransactions data, OrderTransaction model)
        {
            data.Action = (int)model.Action;
            data.Amount = model.Amount;

            data.GiftCard = model.GiftCard.ObjectToJson();

            var json = model.CreditCard.ObjectToJson();
            var key  = KeyManager.GetKey(0);

            data.CreditCard = AesEncryption.Encode(json, key);

            var additionalSettings = model.AdditionalSettings.ObjectToJson();

            data.AdditionalSettings = additionalSettings;

            data.Id = model.Id;
            data.LinkedToTransaction = model.LinkedToTransaction;
            data.OrderId             = DataTypeHelper.BvinToGuid(model.OrderId);
            data.OrderNumber         = model.OrderNumber;
            data.RefNum1             = model.RefNum1;
            data.RefNum2             = model.RefNum2;
            data.StoreId             = model.StoreId;
            data.Success             = model.Success;
            data.Timestamp           = model.TimeStampUtc;
            data.Voided               = model.Voided;
            data.Messages             = model.Messages;
            data.GiftCard             = model.GiftCard.ObjectToJson();
            data.CheckNumber          = model.CheckNumber;
            data.PurchaseOrderNumber  = model.PurchaseOrderNumber;
            data.CompanyAccountNumber = model.CompanyAccountNumber;
            data.MethodId             = model.MethodId;
            data.LineItemId           = model.LineItemId;
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            IEntrance entrance = new AesEncryption();

            Console.WriteLine($"Start running class: {entrance.GetType().Name}\n");
            entrance.Run();
        }
Ejemplo n.º 17
0
        public FileReaderV7(Stream stream, string password)
        {
            _stream = stream;

            // only userVersion was avaiable in old file format versions
            _header = this.ReadPage(0);

            this.UserVersion = _header["userVersion"].AsInt32;

            if (password == null && _header["salt"].AsBinary.IsFullZero() == false)
            {
                throw new LiteException(0, "Current data file requires password");
            }
            else if (password != null)
            {
                if (_header["salt"].AsBinary.IsFullZero())
                {
                    throw new LiteException(0, "Current data file has no encryption - do not use password");
                }

                var hash = AesEncryption.HashSHA1(password);

                if (hash.SequenceEqual(_header["password"].AsBinary) == false)
                {
                    throw new LiteException(0, "Invalid password");
                }
            }

            _aes = password == null ?
                   null :
                   new AesEncryption(password, _header["salt"].AsBinary);
        }
Ejemplo n.º 18
0
        public static string FormatCommandArguments(string bootstrapFile, string debuggingBootstrapFile, CalamariVariableDictionary variables)
        {
            var encryptionKey           = Convert.ToBase64String(AesEncryption.GetEncryptionKey(SensitiveVariablePassword));
            var commandArguments        = new StringBuilder();
            var customPowerShellVersion = variables[SpecialVariables.Action.PowerShell.CustomPowerShellVersion];

            if (!string.IsNullOrEmpty(customPowerShellVersion))
            {
                commandArguments.Append($"-Version {customPowerShellVersion} ");
            }
            var  executeWithoutProfile = variables[SpecialVariables.Action.PowerShell.ExecuteWithoutProfile];
            bool noProfile;

            if (bool.TryParse(executeWithoutProfile, out noProfile) && noProfile)
            {
                commandArguments.Append("-NoProfile ");
            }
            commandArguments.Append("-NoLogo ");
            commandArguments.Append("-NonInteractive ");
            commandArguments.Append("-ExecutionPolicy Unrestricted ");

            var filetoExecute = IsDebuggingEnabled(variables)
                ? debuggingBootstrapFile.EscapeSingleQuotedString()
                : bootstrapFile.EscapeSingleQuotedString();

            commandArguments.AppendFormat("-Command \"Try {{. {{. '{0}' -OctopusKey '{1}'; if ((test-path variable:global:lastexitcode)) {{ exit $LastExitCode }}}};}} catch {{ throw }}\"", filetoExecute, encryptionKey);
            return(commandArguments.ToString());
        }
        /// <summary>
        /// Creates a new wire message.
        /// </summary>
        /// <param name="messageType">Message type name</param>
        /// <param name="serializedMessage">Serialized message</param>
        /// <param name="serializer">Serializer used to serialize the signed content</param>
        /// <param name="keyPair">RSA key pair to be used for creating a RSA signature for the message data</param>
        /// <param name="sharedSecret">Shared secret (wire message will be not encrypted, if null)</param>
        /// <param name="error">Species whether the wire message is in error state</param>
        /// <param name="uniqueCallKey">Unique key to correlate RPC call</param>
        /// <returns>The created wire message</returns>
        /// <exception cref="ArgumentException">Thrown if the message type is left empty.</exception>
        public WireMessage CreateWireMessage(
            string messageType,
            byte[] serializedMessage,
            ISerializerAdapter serializer,
            RsaKeyPair keyPair   = null,
            byte[] sharedSecret  = null,
            bool error           = false,
            byte[] uniqueCallKey = null)
        {
            if (string.IsNullOrWhiteSpace(messageType))
            {
                throw new ArgumentException("Message type must not be empty.", nameof(messageType));
            }

            byte[] iv =
                sharedSecret == null
                    ? new byte[0]
                    : AesEncryption.GenerateIv();

            byte[] rawContent;

            if (keyPair != null && sharedSecret != null)
            {
                var signedMessageData =
                    new SignedMessageData()
                {
                    MessageRawData = serializedMessage,
                    Signature      =
                        RsaSignature.CreateSignature(
                            keySize: keyPair.KeySize,
                            sendersPrivateKeyBlob: keyPair.PrivateKey,
                            rawData: serializedMessage)
                };

                rawContent = serializer.Serialize(typeof(SignedMessageData), signedMessageData);
            }
            else
            {
                rawContent = serializedMessage;
            }

            byte[] messageContent =
                sharedSecret == null
                    ? rawContent
                    : AesEncryption.Encrypt(
                    dataToEncrypt: rawContent,
                    sharedSecret: sharedSecret,
                    iv: iv);

            return
                (new WireMessage()
            {
                MessageType = messageType,
                Data = messageContent,
                Iv = iv,
                Error = error,
                UniqueCallKey = uniqueCallKey
            });
        }
Ejemplo n.º 20
0
        public void GiftCardSettingsSet(string gcGatewayId, MethodSettings settings)
        {
            var json      = Json.ObjectToJson(settings);
            var key       = KeyManager.GetKey(0);
            var encrypted = AesEncryption.Encode(json, key);

            SetProp(string.Concat(Constants.STORESETTING_PAYMENTGIFTCARDSETTINGS, gcGatewayId), encrypted);
        }
Ejemplo n.º 21
0
        public void TaxProviderSettingsSet(string providerID, TaxProviderSettings settings)
        {
            var json      = Json.ObjectToJson(settings);
            var key       = KeyManager.GetKey(0);
            var encrypted = AesEncryption.Encode(json, key);

            SetProp("taxprovsetting" + providerID, encrypted);
        }
Ejemplo n.º 22
0
        public void GiftCardSettingsSet(string gcGatewayId, MethodSettings settings)
        {
            var json      = Json.ObjectToJson(settings);
            var key       = KeyManager.GetKey(0);
            var encrypted = AesEncryption.Encode(json, key);

            SetProp("gcpaysettings" + gcGatewayId, encrypted);
        }
Ejemplo n.º 23
0
        public void MethodSettingsSet(string methodId, MethodSettings settings)
        {
            var json      = Json.ObjectToJson(settings);
            var key       = KeyManager.GetKey(0);
            var encrypted = AesEncryption.Encode(json, key);

            SetProp(string.Concat(Constants.STORESETTING_PAYMENTMETHODSETTINGS, methodId), encrypted);
        }
        public void TestGenerateCek()
        {
            // WHEN
            byte[] cek = AesEncryption.GenerateCek(256);

            // THEN
            Assert.AreEqual(32, cek.Length);
        }
        public void TestGenerateIV()
        {
            // WHEN
            byte[] iv = AesEncryption.GenerateIV();

            // THEN
            Assert.AreEqual(12, iv.Length);
        }
Ejemplo n.º 26
0
        public static string FormatCommandArguments(string bootstrapFile)
        {
            var encryptionKey    = ToHex(AesEncryption.GetEncryptionKey(SensitiveVariablePassword));
            var commandArguments = new StringBuilder();

            commandArguments.AppendFormat("\"{0}\" \"{1}\"", bootstrapFile, encryptionKey);
            return(commandArguments.ToString());
        }
Ejemplo n.º 27
0
        public void TaxProviderSettingsSet(string providerID, TaxProviderSettings settings)
        {
            var json      = Json.ObjectToJson(settings);
            var key       = KeyManager.GetKey(0);
            var encrypted = AesEncryption.Encode(json, key);

            SetProp(string.Concat(Constants.STORESETTING_TAXPROVIDERSETTING, providerID), encrypted);
        }
Ejemplo n.º 28
0
        public void MethodSettingsSet(string methodId, MethodSettings settings)
        {
            var json      = Json.ObjectToJson(settings);
            var key       = KeyManager.GetKey(0);
            var encrypted = AesEncryption.Encode(json, key);

            SetProp("methodsettings" + methodId, encrypted);
        }
Ejemplo n.º 29
0
        public static string FormatCommandArguments(string bootstrapFile, string?scriptParameters)
        {
            var encryptionKey    = Convert.ToBase64String(AesEncryption.GetEncryptionKey(SensitiveVariablePassword));
            var commandArguments = new StringBuilder();

            commandArguments.AppendFormat("\"{0}\" {1} \"{2}\"", bootstrapFile, scriptParameters, encryptionKey);
            return(commandArguments.ToString());
        }
Ejemplo n.º 30
0
        public static string FormatCommandArguments(string bootstrapFile, string?scriptParameters)
        {
            var encryptionKey    = ToHex(AesEncryption.GetEncryptionKey(SensitiveVariablePassword));
            var commandArguments = new StringBuilder();

            commandArguments.Append($"\"{bootstrapFile}\" {scriptParameters} \"{encryptionKey}\"");
            return(commandArguments.ToString());
        }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            /* Step 1. Get a list of xlsl files in current folder */
            String[] Files = Directory.GetFiles(Environment.CurrentDirectory, "*.xlsm");

            /* Create an instance of our encryption class */
            AesEncryption Encryptor = new AesEncryption(Key, Vector);

            /* Step 2. Iterate */
            foreach (String pFile in Files)
            {
                /* Has a template already been generated? */
                if (File.Exists(Path.GetFileNameWithoutExtension(pFile) + " Template.xlsx")) {
                    continue;
                }

                /* Debug */
                Console.WriteLine("Generating template for " + Path.GetFileNameWithoutExtension(pFile));

                /* Open Workbook */
                SpreadsheetGear.IWorkbook _ReadWB =
                    SpreadsheetGear.Factory.GetWorkbook(pFile);

                SpreadsheetGear.IWorkbookSet _OutWbSet =
                    SpreadsheetGear.Factory.GetWorkbookSet();
                SpreadsheetGear.IWorkbook _WriteWB =
                    _OutWbSet.Workbooks.Add();

                /* Generate a model guid */
                _ReadWB.Worksheets[0].Cells["A150"].Formula = Guid.NewGuid().ToString();

                /* Get parameter model, Index 0 always */
                SpreadsheetGear.IWorksheet _ModelSheet = _ReadWB.Worksheets[0];
                SpreadsheetGear.IWorksheet _ListSheet = _ReadWB.Worksheets["Lists"];

                /* Transfer */
                SpreadsheetGear.ISheet is2 = _ListSheet.CopyAfter(_WriteWB.Worksheets[0]);
                SpreadsheetGear.ISheet is1 = _ModelSheet.CopyAfter(_WriteWB.Worksheets[0]);

                /* Set their names */
                is1.Name = "Model Param";
                is2.Name = "Lists";

                _WriteWB.Worksheets[1].Cells["B29"].Validation.Add(SpreadsheetGear.ValidationType.List,
                    SpreadsheetGear.ValidationAlertStyle.Information, SpreadsheetGear.ValidationOperator.Default,
                    "=Lists!$A$1:$A$3", "");
                _WriteWB.Worksheets[1].Cells["B30"].Validation.Delete();
                _WriteWB.Worksheets[1].Cells["B30"].Validation.Add(SpreadsheetGear.ValidationType.List,
                    SpreadsheetGear.ValidationAlertStyle.Information, SpreadsheetGear.ValidationOperator.Default,
                    "=Lists!$C$1:$C$4", "");
                _WriteWB.Worksheets[1].Cells["B33"].Validation.Add(SpreadsheetGear.ValidationType.List,
                    SpreadsheetGear.ValidationAlertStyle.Information, SpreadsheetGear.ValidationOperator.Default,
                    "=Lists!$E$1:$E$3", "");
                _WriteWB.Worksheets[1].Cells["B36"].Validation.Add(SpreadsheetGear.ValidationType.List,
                    SpreadsheetGear.ValidationAlertStyle.Information, SpreadsheetGear.ValidationOperator.Default,
                    "=Lists!$G$1:$G$6", "");
                _WriteWB.Worksheets[1].Cells["B37"].Validation.Add(SpreadsheetGear.ValidationType.List,
                    SpreadsheetGear.ValidationAlertStyle.Information, SpreadsheetGear.ValidationOperator.Default,
                    "=Lists!$I$1:$I$9", "");

                /* Remove left-owers */
                _WriteWB.Worksheets[0].Delete();

                /* Save original workbook */
                _ReadWB.Save();
                _ReadWB.Close();

                /* Save file */
                _WriteWB.SaveAs(Path.GetFileNameWithoutExtension(pFile) + " Template.xlsx",
                    SpreadsheetGear.FileFormat.OpenXMLWorkbook);

                /* Now encrypt our workbook */
                Byte[] WbData = File.ReadAllBytes(pFile);
                Byte[] EncryptedData = Encryptor.Encrypt(Encryptor.ByteArrToString(WbData));
                File.WriteAllBytes(pFile, EncryptedData);
            }
        }
Ejemplo n.º 32
0
        /* Opens a workbook handle based on a request */
        public SpreadsheetGear.IWorkbook GetWorkBook(EIA.Repository.CModelRequest Request)
        {
            /* Shared */
            Guid mGuid = Guid.Parse(Request.Model.Guid);
            Byte[] WbData, WbDataCopy;

            /* Sanitize the cache before we decrypt */
            if (lDecryptedCache.ContainsKey(mGuid)) {
                WbData = lDecryptedCache[mGuid];
            }
            else
            {
                /* Create a new instance of encryptor */
                AesEncryption Decryptor = new AesEncryption(Key, Vector);

                /* Calculate Path */
                String ModelPath = Environment.GetFolderPath(
                    Environment.SpecialFolder.CommonDocuments) + "\\EIA\\Models\\"
                    + Request.Model.Name + " - " + Request.Model.Country + " - " + Request.Model.Type + ".xlsm";

                /* Read in model */
                Byte[] EncryptedWbData = File.ReadAllBytes(ModelPath);
                WbData = Decryptor.StrToByteArray(Decryptor.Decrypt(EncryptedWbData));

                /* Store */
                lDecryptedCache.Add(mGuid, WbData);
            }

            /* Create a copy of the data */
            WbDataCopy = new Byte[WbData.Length];
            WbData.CopyTo(WbDataCopy, 0);

            /* Create the memory stream */
            MemoryStream mStream = new MemoryStream(WbDataCopy);

            /* Open Workbook */
            return SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.OpenFromStream(mStream);
        }