示例#1
0
        public void Test_Decrypt_IsThrowingCryptographicExceptionForWrongData()
        {
            var aesAlgorithm = new AesAlgorithm();

            Assert.Throws <CryptographicException>(() =>
                                                   aesAlgorithm.Decrypt(new byte[] { 12, 20, 25 },
                                                                        new byte[] { 212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126, 212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126 },
                                                                        new byte[] { 212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126 }));
        }
示例#2
0
        /// <summary>
        /// Validates the masterkey by decrypting the given fortress and flushing the memory afterwards.
        /// </summary>
        /// <param name="fortressFullPath"></param>
        /// <param name="fortressName"></param>
        /// <param name="password"></param>
        internal void ValidateMasterKey(string fortressFullPath, string fortressName, string password)
        {
            try
            {
                Logger.log.Info($"Start validating the masterkey of fortress {fortressFullPath}...");
                var aesHelper = new AesHelper();

                // =========================================================== Unzip the fortress - Read salt

                var unzippedFortress = ZipHelper.UnzipSavedZip(fortressFullPath);
                using (unzippedFortress)
                {
                    var entryOfSalt = fortressName + "/salt" + TermHelper.GetTextFileEnding();
                    var saltEntry   = unzippedFortress.GetEntry(entryOfSalt);

                    var saltBytes = new byte[32];
                    using (var stream = saltEntry.Open())
                    {
                        saltBytes = ByteHelper.ReadBytesOfStream(stream);
                    }
                    Logger.log.Debug("Unzipped fortress - Salt bytes read.");

                    // =========================================================== Create masterkey

                    var hashedKey = aesHelper.CreateKey(password, 256, saltBytes);
                    password = string.Empty; // Delete the password in plaintext from RAM
                    var masterKey = new Masterkey(hashedKey);
                    Logger.log.Debug("Masterkey created.");

                    // =========================================================== Decrypt database

                    var entryOfDatabase = fortressName + "/" + TermHelper.GetDatabaseTerm() + TermHelper.GetDatabaseEnding();
                    var databaseEntry   = unzippedFortress.GetEntry(entryOfDatabase);
                    var aesAlg          = new AesAlgorithm();

                    using (var stream = databaseEntry.Open())
                    {
                        var dbBytes     = ByteHelper.ReadBytesOfStream(stream);
                        var decryptedDb = aesAlg.Decrypt(dbBytes, masterKey.Value, saltBytes);
                        Logger.log.Info($"Validated {TermHelper.GetDatabaseTerm()}");
                        decryptedDb = null;
                    }
                }
            }
            catch (Exception ex)
            {
                ex.SetUserMessage(WellKnownExceptionMessages.DataExceptionMessage());
                throw ex;
            }
        }
示例#3
0
        public void DecryptTest()
        {
            string cipherText  = "jTIXGJHmu4AjzU2dG1mhz4lRVvC8gmi5udHfHO3sovA=";
            string decryptText = AesAlgorithm.Decrypt(cipherText);

            if (!String.IsNullOrWhiteSpace(decryptText))
            {
                Assert.AreEqual(decryptText, m_sourceString);
            }
            else
            {
                Assert.Fail();
            }
        }
示例#4
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Get the start page
            var startPage = _config.Value.GFCUrls.StartPage;

            //Get the controller
            var controller = (BaseController)filterContext.Controller;

            //Check the allowed CORS Domains
            var origin = GetOrigin(filterContext);

            //Get the allowed domains
            var allowedDomains = string.IsNullOrEmpty(_config.Value.AllowedCorsDomains)
                ? new string[] { }
                : _config.Value.AllowedCorsDomains.Split(',');

            //Check origin against allowed domains
            var isOriginAllowed = allowedDomains.Contains(origin.Host);


            //If origin is not allowed send user to error page
            if (!isOriginAllowed)
            {
                filterContext.Result = controller.GetCustomErrorCode(EnumStatusCode.CrossDomainOriginResourcesSharing,
                                                                     $"Cross Origin Resources Sharing - Invalid Domain - {origin.Host}");
            }



            //Check the encrypted key in the form post
            var encKeyFromPost = filterContext.HttpContext.Request.Form[_gfcKeyName].FirstOrDefault();
            var keyFromPost    = AesAlgorithm.Decrypt(_corsConfig.Value.GFCKey, encKeyFromPost);

            // If no key or invalid key, send user to error page
            if (string.IsNullOrEmpty(keyFromPost) || _corsConfig.Value.GFCPassword != keyFromPost)
            {
                filterContext.Result = controller.GetCustomErrorCode(EnumStatusCode.CrossDomainOriginResourcesSharing,
                                                                     "Cross Origin Resources Sharing - Form Post key was invalid");
            }



            //We've passed our checks, add the headers to the response
            filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", $"{origin.Scheme}://{origin.Host}");
            filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
            filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "POST, GET, OPTIONS" }); // new[] { "GET, POST, PUT, DELETE, OPTIONS" }
        }
示例#5
0
        static void Main(string[] args)
        {
            //Guid key generated with base64encoded and uppercase combination
            var key = "A+W2nzdpbEe3UHrCBZU5Qw==";

            //Console.WriteLine("Please enter a secret key for the symmetric algorithm.");
            //var key = Console.ReadLine();

            Console.WriteLine("Please enter a string for encryption");
            var str             = Console.ReadLine();
            var encryptedString = AesAlgorithm.Encrypt(key, str);

            Console.WriteLine($"encrypted string = {encryptedString}");

            var decryptedString = AesAlgorithm.Decrypt(key, encryptedString);

            Console.WriteLine($"decrypted string = {decryptedString}");

            Console.ReadKey();
        }
示例#6
0
        private void SucceedRequirementIfKeyPresentAndValid(AuthorizationHandlerContext context, KeyRequirement requirement)
        {
            if (context.Resource is AuthorizationFilterContext authorizationFilterContext)
            {
                if (!AllowCrossOrigin(authorizationFilterContext))
                {
                    _logger.LogError("Cross Domain Origin Resources Sharing Post Error Occured", EnumStatusCode.CrossDomainOriginResourcesSharing);
                    context.Fail();
                }


                //requested data using form-urlencoded
                var encryptedString = authorizationFilterContext.HttpContext.Request.Form[GFC_KEY_NAME].FirstOrDefault();

                if (encryptedString != null && requirement.Keys[GFC_PASSWORD] == AesAlgorithm.Decrypt(requirement.Keys[GFC_KEY], encryptedString))
                {
                    context.Succeed(requirement);
                }
            }
        }
示例#7
0
        /// <summary>
        /// Opens a <see cref="Fortress"/> and loads the database.
        /// </summary>
        public void BuildFortress(string fortressFullPath, string fortressName, string password)
        {
            try
            {
                Logger.log.Info($"Start opening the fortress {fortressFullPath}...");
                var aesHelper = new AesHelper();

                // =========================================================== Unzip the fortress - Read salt

                var unzippedFortress = ZipHelper.UnzipSavedZip(fortressFullPath);
                using (unzippedFortress)
                {
                    var entryOfSalt = fortressName + "/salt" + TermHelper.GetTextFileEnding();
                    var saltEntry   = unzippedFortress.GetEntry(entryOfSalt);

                    var saltBytes = new byte[32];
                    using (var stream = saltEntry.Open())
                    {
                        saltBytes = ByteHelper.ReadBytesOfStream(stream);
                    }
                    CurrentFortressData.Salt = saltBytes;
                    Logger.log.Debug("Unzipped fortress - Salt bytes read.");

                    // =========================================================== Create masterkey

                    var hashedKey = aesHelper.CreateKey(password, 256, saltBytes);
                    password = string.Empty; // Delete the password in plaintext from RAM
                    var masterKey = new Masterkey(hashedKey);
                    hashedKey = null;        // Hash also
                    Logger.log.Debug("Masterkey created.");

                    // =========================================================== Decrypt database

                    var entryOfDatabase = fortressName + "/" + TermHelper.GetDatabaseTerm() + TermHelper.GetDatabaseEnding();
                    var databaseEntry   = unzippedFortress.GetEntry(entryOfDatabase);
                    var aesAlg          = new AesAlgorithm();

                    using (var stream = databaseEntry.Open())
                    {
                        var dbBytes     = ByteHelper.ReadBytesOfStream(stream);
                        var decryptedDb = aesAlg.Decrypt(dbBytes, masterKey.Value, saltBytes);
                        Logger.log.Info($"Decrypted {TermHelper.GetDatabaseTerm()}");

                        // =========================================================== Unzip database
                        // We distinguish between sensible data and normal data. We put the sensible data into the secureDatacache.
                        var unzippedByteEntriesOfDb = ZipHelper.GetEntriesFromZipArchive(decryptedDb); // These are the entries in byte arrays
                        decryptedDb = null;
                        // Add to secureDC.
                        foreach (var sensibleBytes in unzippedByteEntriesOfDb.Item2.Item2.ToList()) // ToList() otherwise the iterations throws exception
                        {
                            AddToSecureMemoryDC(unzippedByteEntriesOfDb.Item2.Item1.Pop(), unzippedByteEntriesOfDb.Item2.Item2.Pop());
                        }
                        foreach (var bytes in unzippedByteEntriesOfDb.Item1.ToList()) // Add not sensible data to the "unsecure" DC.
                        {
                            AddToUnsecureMemoryDC(BuildModelsOutOfBytes <ModelBase>(unzippedByteEntriesOfDb.Item1.Pop()));
                        }
                        unzippedByteEntriesOfDb = null;
                    }
                    // Track the security parameters for scans later.
                    SecurityParameterProvider.Instance.UpdateHash(nameof(Fortress), fortressFullPath);
                }
            }
            catch (Exception ex)
            {
                ex.SetUserMessage(WellKnownExceptionMessages.DataExceptionMessage());
                throw ex;
            }
        }
示例#8
0
 /// <summary>
 /// Decodes the file name and then decrypts it using the file Key and Iv values with AES-OFB algorithm.
 /// </summary>
 /// <param name="aes">AES algorithm used for decryption of the full file name.</param>
 /// <returns>Full name of the file (name + extension).</returns>
 public string NameDecryption(AesAlgorithm aes)
 {
     return(Encoding.ASCII.GetString(aes.Decrypt(Convert.FromBase64String(EncryptedName.Replace('$', '/')))));
 }