Esempio n. 1
0
        public async Task <IActionResult> Create([DataSourceRequest] DataSourceRequest request)
        {
            var model = new Tenant();

            if (ModelState.IsValid)
            {
                await this.TryUpdateModelAsync <TenantViewModel, Tenant>(model);

                if (options.Value.UseExplicitTenantPasswords)
                {
                    model.TenantPassword = Convert.ToBase64String(AesEncryptor.CreateKey());
                }

                db.Tenants.Add(model);

                await db.SaveChangesAsync();
            }

            return(Json(await new[] { model.ToViewModel <Tenant, TenantViewModel>() }.ToDataSourceResultAsync(request, ModelState)));
        }
Esempio n. 2
0
        public AesKeyWrapper(SymmetricJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
            : base(key, encryptionAlgorithm, algorithm)
        {
#if SUPPORT_SIMD
            if (algorithm == KeyManagementAlgorithm.Aes128KW)
            {
                _encryptor = new Aes128NiCbcEncryptor(key.K);
            }
            else if (algorithm == KeyManagementAlgorithm.Aes256KW)
            {
                _encryptor = new Aes256NiCbcEncryptor(key.K);
            }
            else if (algorithm == KeyManagementAlgorithm.Aes192KW)
            {
                _encryptor = new Aes192NiCbcEncryptor(key.K);
            }
            else
            {
                ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm);
                _encryptor = new Aes128NiCbcEncryptor(default);
Esempio n. 3
0
        public async Task <IActionResult> Update([DataSourceRequest] DataSourceRequest request, WebPluginConstantViewModel viewModel)
        {
            var tenantId = viewModel.TenantId;

            if (!isSysAdmin)
            {
                tenantId = db.CurrentTenantId;
            }

            var model = db.WebPluginConstants.First(n => n.TenantId == tenantId && n.WebPluginConstantId == viewModel.WebPluginConstantId);

            if (ModelState.IsValid)
            {
                await this.TryUpdateModelAsync <WebPluginConstantViewModel, WebPluginConstant>(model, "", m => { return(m.ElementType == null); });

                if (model.Value.StartsWith("encrypt:"))
                {
                    if (tenantId == null || !options.Value.UseExplicitTenantPasswords)
                    {
                        model.Value = PasswordSecurity.Encrypt(model.Value.Substring(8));
                    }
                    else
                    {
                        var t = db.Tenants.First(n => n.TenantId == tenantId);
                        if (!string.IsNullOrEmpty(t.TenantPassword))
                        {
                            var pwd = Convert.FromBase64String(t.TenantPassword);
                            model.Value = AesEncryptor.Encrypt(model.Value.Substring(8), pwd, false);
                        }
                        else
                        {
                            model.Value = PasswordSecurity.Encrypt(model.Value.Substring(8));
                        }
                    }
                }
                model.TenantId = tenantId;
                await db.SaveChangesAsync();
            }

            return(Json(await new[] { model.ToViewModel <WebPluginConstant, WebPluginConstantViewModel>() }.ToDataSourceResultAsync(request, ModelState)));
        }
        public void TestAes200()
        {
            int length = 100;
            var rand   = new RandomGenerator();

            for (int i = 0; i < length; i++)
            {
                using (var password = rand.RandomSecureStringPassword(10, 50))
                {
                    var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section";
                    // base 64
                    var encryptedBase64 = AesEncryptor.Encrypt200(stringToEncrypt, password);
                    var decryptedBase64 = AesEncryptor.Decrypt(encryptedBase64, password);
                    Assert.AreEqual(stringToEncrypt, decryptedBase64);
                    // base 36
                    var encryptedBase36 = AesEncryptor.Encrypt200(stringToEncrypt, password, true);
                    var decryptedBase36 = AesEncryptor.Decrypt(encryptedBase36, password, true);
                    Assert.AreEqual(stringToEncrypt, decryptedBase36);
                }
            }
        }
Esempio n. 5
0
 public static byte[] LoadBytesFromPersistentStorage(string filename)
 {
     try
     {
         string path   = Path.Combine(Application.persistentDataPath, filename);
         byte[] buffer = null;
         if (ConfigApp.PersistentStorageEncryptionEnabled)
         {
             buffer = AesEncryptor.Decrypt(File.ReadAllBytes(path));
         }
         else
         {
             buffer = File.ReadAllBytes(path);
         }
         return(buffer);
     }
     catch (Exception)
     {
         return(null);
     }
 }
Esempio n. 6
0
        public string ApplyFormat(string name, object rawValue, Func <string, string, string, object> argumentsCallback)
        {
            var    pass      = argumentsCallback(name, "decrypt", "password");
            var    useRawKey = argumentsCallback(name, "decrypt", "useRawKey");
            var    keyIsRaw  = useRawKey is bool db && db;
            string retVal    = rawValue?.ToString();

            if (!string.IsNullOrEmpty(retVal))
            {
                bool success = false;
                if (pass is string pwd && !string.IsNullOrEmpty(pwd))
                {
                    try
                    {
                        retVal  = AesEncryptor.Decrypt(retVal, Convert.FromBase64String(pwd), !keyIsRaw);
                        success = true;
                    }
                    catch
                    {
                    }
                }
                else if (pass is byte[] pwb && pwb.Length != 0)
                {
                    try
                    {
                        retVal  = AesEncryptor.Decrypt(retVal, pwb, !keyIsRaw);
                        success = true;
                    }
                    catch
                    {
                    }
                }

                if (!success)
                {
                    retVal = retVal.Decrypt();
                }

                return(retVal);
            }
Esempio n. 7
0
 public static string LoadFromEditorDataPath(string filename, bool encrypted)
 {
     try
     {
         string path  = Path.Combine(Application.dataPath, filename);
         byte[] bytes = null;
         if (encrypted)
         {
             bytes = AesEncryptor.Decrypt(File.ReadAllBytes(path));
         }
         else
         {
             bytes = File.ReadAllBytes(path);
         }
         return(Encoding.UTF8.GetString(bytes));
     }
     catch (Exception exception)
     {
         Debug.LogError(string.Concat(new object[] { "Cannot load '", filename, "' from editor data path: ", exception }));
     }
     return(null);
 }
Esempio n. 8
0
        public void ShouldEncryptAndDecrypt()
        {
            var aesEncryptor    = new AesEncryptor();
            var stringGenerator = new StringGenerator();

            for (int i = 0; i < 1000; i++)
            {
                string randomString = stringGenerator.CreateRandomString(random.Next(1, 30));

                var    parameters = aesEncryptor.GenerateAesParameters();
                byte[] keyBytes   = parameters.Key;
                byte[] ivBytes    = parameters.IV;

                byte[] encryptedBytes = aesEncryptor.EncryptString(randomString, keyBytes, ivBytes);

                Assert.IsNotNull(encryptedBytes);

                string unencrypted = aesEncryptor.DecryptBytes(encryptedBytes, keyBytes, ivBytes);

                Assert.AreEqual(randomString, unencrypted);
            }
        }
        public void TestAes20000_Bytes()
        {
            int length = 100;
            var rand   = new RandomGenerator();

            //byte[] entropy = new byte[20];

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            for (int i = 0; i < length; i++)
            {
                byte[] newKey = new byte[rand.RandomNumber(75, 88)];
                using (var rng = new RNGCryptoServiceProvider())
                {
                    //rng.GetBytes(entropy);
                    rng.GetBytes(newKey);
                }

                var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section";

                var bytes = System.Text.Encoding.UTF8.GetBytes(stringToEncrypt);

                // base 64
                var encryptedBytes = AesEncryptor.Encrypt20000(bytes, newKey);
                var decryptedBytes = AesEncryptor.Decrypt(encryptedBytes, newKey);

                Assert.IsTrue(decryptedBytes.SequenceEqual(bytes));

                var decryptedString = System.Text.Encoding.UTF8.GetString(decryptedBytes);
                Assert.AreEqual(stringToEncrypt, decryptedString);

                Console.WriteLine(string.Format("{0:N0}\t{1}", i, stopwatch.Elapsed));
                stopwatch.Stop();
                stopwatch.Reset();
                stopwatch.Start();
            }
        }
        public void TestProtectPasswordDualKey()
        {
            var cert2      = LoadCertificate();
            var publicKey  = new X509CertificatePublicKey(cert2);
            var privateKey = new X509Certificate2KeyEncryptionKey(cert2);

            var cert2Dual   = LoadCertificate2();
            var publicKey2  = new X509CertificatePublicKey(cert2Dual);
            var privateKey2 = new X509Certificate2KeyEncryptionKey(cert2Dual);

            int length = 100;
            var rand   = new RandomGenerator();

            for (int i = 0; i < length; i++)
            {
                using (var password = rand.RandomSecureStringPassword(10, 50))
                {
                    var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section";

                    // base 64
                    var encryptedBase64 = AesEncryptor.Encrypt1000(stringToEncrypt, password);
                    var decryptedBase64 = AesEncryptor.Decrypt(encryptedBase64, password);
                    Assert.AreEqual(stringToEncrypt, decryptedBase64);

                    // base 36
                    var encryptedBase36 = AesEncryptor.Encrypt1000(stringToEncrypt, password, true);
                    var decryptedBase36 = AesEncryptor.Decrypt(encryptedBase36, password, true);
                    Assert.AreEqual(stringToEncrypt, decryptedBase36);

                    var protectedPwStr = AsymmetricEncryptor.EncryptToBase64StringAsync(password, publicKey, publicKey2).GetAwaiter().GetResult();

                    var unprotectedPwdStr = AsymmetricEncryptor.DecryptFromBase64String(protectedPwStr, privateKey, privateKey2);

                    var decryptedUnprotectedPw = AesEncryptor.Decrypt(encryptedBase64, unprotectedPwdStr);
                    Assert.AreEqual(stringToEncrypt, decryptedUnprotectedPw);
                }
            }
        }
Esempio n. 11
0
    void Awake()
    {
        //saveFilePath = Path.Combine(Application.persistentDataPath,"saveFile.json");
        saveFilePath = Path.Combine(Application.persistentDataPath, filename);
        saveFile     = new SaveFile();
        encryptor    = new AesEncryptor();


        if (!File.Exists(saveFilePath))
        {
            saveFile.saveVersion  = 1.00f;
            saveFile.creationDate = Convert.ToString(DateTime.Now);
            saveFile.saveDate     = Convert.ToString(DateTime.Now);
            // File.WriteAllText(saveFilePath, saveFile.GetJson());

            byte[] encryptedSaveFile = encryptor.Encrypt(saveFile.GetJson(), JSON_ENCRYPTED_KEY, JSON_ENCRYPTED_IV);
            File.WriteAllBytes(saveFilePath, encryptedSaveFile);
        }
        else
        {
            Load();
        }
    }
Esempio n. 12
0
        //private bool CheckLDevice(string devName)
        //{
        //    string LDate = CheckLDate();
        //    Encryptor en = new AesEncryptor();
        //    if (LInfo != null)
        //    {

        //    }
        //    return true;
        //}
        private void UpdateAppset()
        {
            Encryptor en = new AesEncryptor();

            using (RegistryKey skey = Registry.LocalMachine.OpenSubKey("Software", true))
            {
                using (RegistryKey key = skey.CreateSubKey("IdentaMaster", RegistryKeyPermissionCheck.ReadWriteSubTree))
                {
                    byte[] entropy = { 0x00, 0x01, 0x02, 0x01, 0x00, 0x04, 0xBB, 0x17, 0x8b, 0xf6, 0xa2, 0x15, 0xe2, 0x64, 0x11, 0x9a };
                    appSet[0] = DateTime.Now.ToString();
                    string newappset = appSet[0];

                    foreach (var set in appSet)
                    {
                        if (newappset != set)
                        {
                            newappset += "..." + set;
                        }
                    }
                    foreach (var devctrl in pluginManager.DeviceControls)
                    {
                        if (!appSet.Contains(devctrl.ToString()))
                        {
                            appSet.Add(devctrl.ToString());
                            newappset += "..." + devctrl.ToString();
                        }
                    }
                    newappset += "^^^";
                    //newappset = newappset.Replace("\\0", "");
                    var    encappset = System.Text.Encoding.Default.GetBytes(newappset);// System.Text.Encoding.UTF8.GetString();
                    byte[] toenc     = new byte[(16 - encappset.Length % 16) + encappset.Length];
                    encappset.CopyTo(toenc, 0);
                    byte[] encAppSet = en.Encrypt(toenc, entropy);
                    key.SetValue("AppSet", encAppSet);
                }
            }
        }
Esempio n. 13
0
 /// <summary>
 /// Initializes the <see cref="WindowsMemoryEncryptor"/> by assigning the encryptors to the <see cref="WindowsEncryptor"/> and creating our padding aes encryptor.
 /// </summary>
 /// <param name="encryptors"> The additional encryptors to use as our advanced entropy. </param>
 public WindowsMemoryEncryptor(params object[] encryptors) : base(encryptors)
 {
     aes           = new AesEncryptor(encryptors);
     randomEntropy = RandomBytes.Secure.SHA3.GetBytes(32).Shake_128();
 }
Esempio n. 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AesCbcHmacEncryptor"/> class.
        /// </summary>
        /// <param name="hmacKey"></param>
        /// <param name="encryptionAlgorithm"></param>
        /// <param name="encryptor"></param>
        public AesCbcHmacEncryptor(ReadOnlySpan <byte> hmacKey, EncryptionAlgorithm encryptionAlgorithm, AesEncryptor encryptor)
        {
            if (encryptionAlgorithm is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.encryptionAlgorithm);
            }

            if (encryptionAlgorithm.Category != EncryptionType.AesHmac)
            {
                ThrowHelper.ThrowNotSupportedException_EncryptionAlgorithm(encryptionAlgorithm);
            }

            int keyLength = encryptionAlgorithm.RequiredKeySizeInBits >> 4;

            if (hmacKey.Length < keyLength)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException_EncryptionKeyTooSmall(encryptionAlgorithm, encryptionAlgorithm.RequiredKeySizeInBits, hmacKey.Length >> 3);
            }

            _encryptor = encryptor;
            if (encryptionAlgorithm.SignatureAlgorithm is null)
            {
                ThrowHelper.ThrowNotSupportedException_SignatureAlgorithm(encryptionAlgorithm.SignatureAlgorithm);
            }

            _signer = new SymmetricSigner(hmacKey.Slice(0, keyLength), encryptionAlgorithm.SignatureAlgorithm);
        }
Esempio n. 15
0
        public void SetUp()
        {
            var subject = new AesEncryptor("SOME_KEY");

            _result = subject.Decrypt("ABZnmFTW8EcZLGqcDk2aQQ==");
        }
Esempio n. 16
0
        public void SetUp()
        {
            var subject = new AesEncryptor("SOME_KEY");

            _result = subject.Encrypt("PASSWORD");
        }
Esempio n. 17
0
 public AesStringValueConverter(AesEncryptor encryptor)
 {
     this.encryptor = encryptor;
 }
Esempio n. 18
0
        public void Encode(File file)
        {
            var aes = new AesEncryptor();

            aes.Encode(file.FullPath, GetDestinationFilePath(System.IO.Path.GetExtension(file.FullPath)), GetKeyFromDialog());
        }
Esempio n. 19
0
 public string HashPassword(ApplicationUser user, string password)
 {
     return(AesEncryptor.Encrypt(password));
 }
Esempio n. 20
0
        public static byte[] DecodePayload(Payload payload, string secret)
        {
            var keyBytes = KeyDerivedBytes.GetBytes(secret, AesEncryptor.KeySize);

            return(AesEncryptor.Decrypt(payload.EncryptedData, keyBytes, payload.Vector));
        }
Esempio n. 21
0
 void InitAesEncryptor()
 {
     m_AesEncryptor = new AesEncryptor(AesKey, AesIV);
 }