コード例 #1
0
        public void Authorize(HttpRequestHeader header)
        {
            if (!header.Headers.TryGetValue(cookieHeader, out IList <string> cookieHeaderValue))
            {
                if (!header.Headers.TryGetValue(authorizeHeader, out cookieHeaderValue))
                {
                    return;
                }
            }

            var cookies = CookieParser.CookiesFromString(cookieHeaderValue[0]);

            if (cookies.TryGetValue(cookieName, out string authCookieDataEncoded))
            {
                var authCookieDataEncrypted = Base64UrlEncoder.FromBase64String(authCookieDataEncoded);
                var authCookieDataBytes     = SymmetricEncryptor.Decrypt(encryptionAlgorithm, encryptionKey, authCookieDataEncrypted);
                var authCookieData          = Encoding.UTF8.GetString(authCookieDataBytes);
                if (authCookieData == "I can access this")
                {
                    var claims = new Claim[] {
                        new Claim(ClaimTypes.Authentication, Boolean.TrueString),
                        new Claim(ClaimTypes.NameIdentifier, "1234", ClaimValueTypes.String),
                        new Claim(ClaimTypes.Name, "Tester", ClaimValueTypes.String),
                        new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String)
                    };

                    var identity  = new ClaimsIdentity(claims, "Cookies");
                    var principal = new ClaimsPrincipal(identity);
                    System.Threading.Thread.CurrentPrincipal = principal;
                }
            }
        }
コード例 #2
0
        private async Task SendAsync(IEvent @event)
        {
            var topic = @event.GetType().GetNiceName();

            string[][] claims = null;
            if (Thread.CurrentPrincipal is ClaimsPrincipal principal)
            {
                claims = principal.Claims.Select(x => new string[] { x.Type, x.Value }).ToArray();
            }

            var message = new KafkaEventMessage()
            {
                Message = @event,
                Claims  = claims
            };

            var body = KafkaCommon.Serialize(message);

            if (encryptionKey != null)
            {
                body = SymmetricEncryptor.Encrypt(encryptionAlgorithm, encryptionKey, body);
            }

            var producerResult = await producer.ProduceAsync(topic, new Message <string, byte[]> {
                Key = KafkaCommon.MessageKey, Value = body
            });

            if (producerResult.Status != PersistenceStatus.Persisted)
            {
                throw new Exception($"{nameof(KafkaClient)} failed: {producerResult.Status}");
            }
        }
コード例 #3
0
ファイル: MainForm.cs プロジェクト: iqman/MACMSC
        private void DecryptDataEntities(IEnumerable <DataEntity> dataEntities)
        {
            IPreService preProxy;

            foreach (DataEntity entity in dataEntities)
            {
                preProxy           = GetPreProxy();
                entity.AesInfo.Key = preProxy.Decrypt(this.keyPair.Private, entity.AesInfo.Key);
                if (entity.AesInfo.Key.Length > 32)  // hack to fix a weird error in preLib where the length is sometimes 1 byte to large
                {
                    entity.AesInfo.Key = entity.AesInfo.Key.Take(32).ToArray();
                }


                preProxy          = GetPreProxy();
                entity.AesInfo.IV = preProxy.Decrypt(this.keyPair.Private, entity.AesInfo.IV);
                if (entity.AesInfo.IV.Length >= 16)  // hack to fix a weird error in preLib where the length is sometimes 1 byte to large
                {
                    entity.AesInfo.IV = entity.AesInfo.IV.Take(16).ToArray();
                }

                foreach (Attribute attribute in entity.Attributes)
                {
                    attribute.Keyword = SymmetricEncryptor.Decrypt(attribute.Keyword, entity.AesInfo);
                }

                entity.Payload.Name = SymmetricEncryptor.Decrypt(entity.Payload.Name, entity.AesInfo);
            }
        }
コード例 #4
0
        public void IsDecryptedFormSameAfterDecrypt_AESHelper(string password, string secretkey)
        {
            var encryptedValue = SymmetricEncryptor.EncryptString(password, secretkey);
            var decryptedValue = SymmetricEncryptor.DecryptToString(encryptedValue, secretkey);

            Assert.Equal(password, decryptedValue);
        }
コード例 #5
0
 public BackupServersProvider(ConfigStorageClient configStorageClient, DpmServerClient dpmServerClient)
 {
     this.configStorageClient = configStorageClient;
     this.dpmServerClient     = dpmServerClient;
     this.cache     = MemoryCache.Default;
     this.encryptor = new SymmetricEncryptor(EncryptionConstants.EncryptionKey, EncryptionConstants.EncryptionAlgorithm);
 }
コード例 #6
0
        private static string EncryptToString(string key, string valueDecrypted)
        {
            var symmetricKey   = SymmetricEncryptor.GetKey(key, null, SymmetricKeySize.Bits_256, SymmetricBlockSize.Bits_128);
            var valueEncrypted = SymmetricEncryptor.Encrypt(SymmetricAlgorithmType.AESwithShift, symmetricKey, valueDecrypted);

            return(encryptionPrefix + valueEncrypted);
        }
コード例 #7
0
        public void SymmetricEncryptor_HeavyUsage()
        {
            CryptoRandomizer random         = new CryptoRandomizer();
            const int        Iterations     = 100;
            const int        MaxMemoryBlock = 100000;


            for (int i = 0; i < Iterations; i++)
            {
                int    blockSize = random.Next(MaxMemoryBlock);
                byte[] buffer    = new ByteGenerator().GenerateBytes(blockSize);
                string key       = CryptoString.GenerateRandomText(1000);

                byte[] decryptedBuffer;
                byte[] encryptedBuffer;

                using (SymmetricEncryptor encryptor = new SymmetricEncryptor())
                {
                    //Encrypt
                    encryptedBuffer = encryptor.EncryptBytes(buffer, key);

                    // Decrypt
                    decryptedBuffer = encryptor.DecryptBytes(encryptedBuffer, key);
                }                 // IDispose - Closes and clears the keys in memory

                // Assert - Check to make sure the bytes are all the same
                Assert.IsTrue(buffer.SequenceEqual(decryptedBuffer));
            }
        }
コード例 #8
0
ファイル: Form1.cs プロジェクト: iqman/MACMSC
        private void DecryptSearchResultsMetadata()
        {
            IPreService preProxy;

            foreach (DataEntity entity in this.searchResults)
            {
                preProxy           = CreatePreProxy();
                entity.AesInfo.Key = preProxy.Decrypt(this.userPrivateKey, entity.AesInfo.Key);
                if (entity.AesInfo.Key.Length > 32)  // hack to fix a weird error in preLib where the length is sometimes 1 byte to large
                {
                    entity.AesInfo.Key = entity.AesInfo.Key.Take(32).ToArray();
                }


                preProxy          = CreatePreProxy();
                entity.AesInfo.IV = preProxy.Decrypt(this.userPrivateKey, entity.AesInfo.IV);
                if (entity.AesInfo.IV.Length >= 16)  // hack to fix a weird error in preLib where the length is sometimes 1 byte to large
                {
                    entity.AesInfo.IV = entity.AesInfo.IV.Take(16).ToArray();
                }

                foreach (Attribute attribute in entity.Attributes)
                {
                    attribute.Keyword = SymmetricEncryptor.Decrypt(attribute.Keyword, entity.AesInfo);
                }

                entity.Payload.Name = SymmetricEncryptor.Decrypt(entity.Payload.Name, entity.AesInfo);
            }
        }
コード例 #9
0
        private void SaveEntityToFile(DataEntity entity)
        {
            try
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.FileName = entity.Payload.Name.GetString();
                DialogResult result = dialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    IGatewayService proxy          = ProxyFactory.CreateProxy <IGatewayService>();
                    byte[]          payloadContent = proxy.GetPayload(this.myId, entity.Id);

                    byte[] plainText = SymmetricEncryptor.Decrypt(payloadContent, entity.AesInfo);

                    File.WriteAllBytes(dialog.FileName, plainText);

                    MessageBox.Show("Done saving file");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                Logger.LogError("Error saving entity to file", ex);
            }
        }
コード例 #10
0
        public async Task <Status> AddEntry(AddEntryDto addEntryDto, int userId)
        {
            var user = _mainDbContext.Users.FirstOrDefault(u => u.UserId == userId);

            if (user == null)
            {
                return(new Status(false, "User not exist"));
            }

            var passwordE = SymmetricEncryptor.EncryptString(addEntryDto.PasswordDecrypted, user.PasswordHash);
            //todo: add auto mapper
            var newEntry = new Entry
            {
                UserOwnerUsername = user.Username,
            };
            var newEntryState = new EntryState
            {
                Username    = addEntryDto.Username,
                PasswordE   = passwordE,
                Description = addEntryDto.Description,
                Email       = addEntryDto.Email,
                WebAddress  = addEntryDto.WebAddress,
                IsDeleted   = false
            };

            newEntry.CurrentEntryState = newEntryState;
            var newUserEntry = new UsersEntries
            {
                IsUserOwner = true,
                Entry       = newEntry,
                User        = user
            };
            var entryAction = CreateEntryAction(user, newEntryState, newEntry, ActionTypesEnum.Create);


            try
            {
                _mainDbContext.Update(user);
                _mainDbContext.Update(entryAction);
                _mainDbContext.Update(newUserEntry);
                await _mainDbContext.SaveChangesAsync();

                return(new Status
                {
                    Success = true,
                    Message = "Added new password"
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(new Status
                {
                    Success = false,
                    Message = "Something went wrong"
                });
            }
        }
コード例 #11
0
        public TModel[] EncryptModels(TModel[] models, Graph <TModel> graph, bool newCopy)
        {
            if (!this.Enabled)
            {
                return(models);
            }

            var properties = GetEncryptableProperties(typeof(TModel), this.Properties);

            if (properties.Length == 0)
            {
                return(models);
            }

            graph = new Graph <TModel>(graph);

            //add identites for copying
            graph.AddProperties(ModelAnalyzer.GetIdentityPropertyNames(typeof(TModel)));

            if (newCopy)
            {
                models = Mapper.Map <TModel[], TModel[]>(models, graph);
            }

            foreach (TModel model in models)
            {
                foreach (var property in properties)
                {
                    if (graph.HasLocalProperty(property.Name))
                    {
                        if (property.TypeDetail.CoreType == CoreType.String)
                        {
                            string plain = (string)property.Getter(model);
                            if (plain != null)
                            {
                                if (plain.Length <= encryptionPrefix.Length || plain.Substring(0, encryptionPrefix.Length) != encryptionPrefix)
                                {
                                    plain = encryptionPrefix + plain;
                                    string encrypted = SymmetricEncryptor.Encrypt(encryptionAlgorithm, EncryptionKey, plain);
                                    property.Setter(model, encrypted);
                                }
                            }
                        }
                        else if (property.Type == typeof(byte[]))
                        {
                            byte[] plain = (byte[])property.Getter(model);
                            if (plain != null)
                            {
                                byte[] encrypted = SymmetricEncryptor.Encrypt(encryptionAlgorithm, EncryptionKey, plain);
                                property.Setter(model, encrypted);
                            }
                        }
                    }
                }
            }
            return(models);
        }
コード例 #12
0
        public static string SymmetricEncrypt(SymmetricAlgorithm algorithm,
                                              string data)
        {
            ValidateParameters(algorithm, data);
            SymmetricEncryptor encryptor =
                new SymmetricEncryptor(algorithm, data);

            return(encryptor.GetEncryptedString());
        }
コード例 #13
0
        public static byte[] SymmetricEncrypt(SymmetricAlgorithm algorithm,
                                              byte[] data)
        {
            ValidateParameters(algorithm, data);
            SymmetricEncryptor encryptor =
                new SymmetricEncryptor(algorithm, data);

            return(encryptor.GetEncryptedBytes());
        }
コード例 #14
0
 public CryptoBlob(CryptoCredentials credentials, byte[] decryptedBytes = null)
 {
     Credentials = credentials;
     _encryptor  = new SymmetricEncryptor(Credentials);
     if (decryptedBytes != null)
     {
         Encrypt(decryptedBytes);
     }
     HashSize = Hasher.CalculateHashBytesLength(_hasher.GetAlgorithm());
 }
コード例 #15
0
        /// <summary>
        /// Returns an byte array representation of the byte array using the
        /// provided key, iv, and specified symmetric encryption algorithm.
        /// </summary>
        public static byte[] SymmetricEncrypt <T>(byte[] data, byte[] key,
                                                  byte[] iv) where T : SymmetricAlgorithm
        {
            ValidateParameters(data, key, iv);
            SymmetricAlgorithm algorithm = Activator.CreateInstance <T>();
            SymmetricEncryptor encryptor =
                new SymmetricEncryptor(algorithm, data, key, iv);

            return(encryptor.GetEncryptedBytes());
        }
コード例 #16
0
        private void buttonUploadNow_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listBoxUploadKeywords.Items.Count == 0)
                {
                    MessageBox.Show("At least one keyword must be associated with the data before it is uploaded");
                    return;
                }
                if (this.keyPair == null)
                {
                    MessageBox.Show("You must load user keys first");
                    return;
                }

                if (this.rolesUserControlUploadData.SelectedRoles.Count == 0)
                {
                    MessageBox.Show("You must select at least one role which should have access to the uploaded data");
                    return;
                }

                byte[] fileContent = File.ReadAllBytes(this.labelUploadData.Text);

                AesEncryptionInfo encryptionInfo = SymmetricEncryptor.GenerateSymmetricKeyInfo();

                byte[] fileCiphertext = SymmetricEncryptor.Encrypt(fileContent, encryptionInfo);

                IPreService preProxy = CreatePreProxy();
                byte[]      encSymIv = preProxy.Encrypt(this.keyPair.Public, encryptionInfo.IV);

                preProxy = CreatePreProxy();
                byte[] encSymKey = preProxy.Encrypt(this.keyPair.Public, encryptionInfo.Key);

                byte[] name = SymmetricEncryptor.Encrypt(Path.GetFileName(this.labelUploadData.Text).GetBytes(), encryptionInfo);

                DataEntity entity = new DataEntity();
                entity.Attributes = CollectAndEncryptAttributes(encryptionInfo);
                entity.Payload    = new FilePayload(name, fileCiphertext);
                entity.AesInfo    = new AesEncryptionInfo(encSymKey, encSymIv);
                entity.Id         = Guid.NewGuid();

                entity.Signature = DataSigner.Sign(entity, this.signingKeys);

                IGatewayService proxy = CreateServiceProxy();

                proxy.CreateDataEntities(this.myId, this.rolesUserControlUploadData.SelectedRoles, new[] { entity });

                MessageBox.Show("Done uploading");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                Logger.LogError("Error preparing and uploading data to server", ex);
            }
        }
コード例 #17
0
        public TModel DecryptModel(TModel model, Graph <TModel> graph, bool newCopy)
        {
            if (!this.Enabled)
            {
                return(model);
            }

            var properties = GetEncryptableProperties(typeof(TModel), this.Properties);

            if (properties.Length == 0)
            {
                return(model);
            }

            graph = new Graph <TModel>(graph);

            if (newCopy)
            {
                model = Mapper.Map <TModel, TModel>(model, graph);
            }

            foreach (var property in properties)
            {
                if (graph.HasLocalProperty(property.Name))
                {
                    if (property.TypeDetail.CoreType == CoreType.String)
                    {
                        string encrypted = (string)property.Getter(model);
                        try
                        {
                            if (encrypted.Length > encryptionPrefix.Length && encrypted.Substring(0, encryptionPrefix.Length) == encryptionPrefix)
                            {
                                encrypted = encrypted.Substring(encryptionPrefix.Length, encrypted.Length - encryptionPrefix.Length);
                                string plain = SymmetricEncryptor.Decrypt(encryptionAlgorithm, EncryptionKey, encrypted);
                                property.Setter(model, plain);
                            }
                        }
                        catch { }
                    }
                    else if (property.Type == typeof(byte[]))
                    {
                        byte[] encrypted = (byte[])property.Getter(model);
                        try
                        {
                            byte[] plain = SymmetricEncryptor.Decrypt(encryptionAlgorithm, EncryptionKey, encrypted);
                            property.Setter(model, plain);
                        }
                        catch { }
                    }
                }
            }

            return(model);
        }
コード例 #18
0
        public async Task EncryptorExtensions_EncryptDecrypt_expired()
        {
            var encr = new SymmetricEncryptor(new Key(new EncryptionPolicy {
                Expires = DateTime.UtcNow.AddDays(-4)
            }));

            await Assert.ThrowsExceptionAsync <ExpiredPolicyException>(async() =>
            {
                await TestEncryptDecrypt(encr, DataToEncrypt1);
            },
                                                                       "Policy has expired and should throw an exception");
        }
コード例 #19
0
        private IList <Attribute> CollectAndEncryptAttributes(AesEncryptionInfo encryptionInfo)
        {
            IList <Attribute> attributes = new List <Attribute>();

            foreach (string s in this.listBoxUploadKeywords.Items)
            {
                byte[] att = SymmetricEncryptor.Encrypt(s.GetBytes(), encryptionInfo);
                attributes.Add(new Attribute(GuidCreator.CreateGuidFromString(s), att));
            }

            return(attributes);
        }
コード例 #20
0
        public async Task <Status> EditEntry(EditEntryDto editEntryDto, int userId)
        {
            var owner = await _mainDbContext.Users.FirstOrDefaultAsync(user => user.UserId == userId);

            if (owner == null)
            {
                return(new Status(false, "User owner not found"));
            }

            var userEntry =
                await _mainDbContext.UsersEntries.Include(p => p.Entry.CurrentEntryState).FirstOrDefaultAsync(x =>
                                                                                                              x.EntryId == editEntryDto.EntryId && x.UserId == userId);

            if (userEntry == null)
            {
                return(new Status(false, "Entry not found"));
            }

            if (!userEntry.IsUserOwner)
            {
                return(new Status(false, "You cannot edit shared for you entry. You have to be an owner for edit."));
            }

            try
            {
                var newEntryState = new EntryState
                {
                    PasswordE   = SymmetricEncryptor.EncryptString(editEntryDto.PasswordDecrypted, owner.PasswordHash),
                    Username    = editEntryDto.Username,
                    Description = editEntryDto.Description,
                    Email       = editEntryDto.Email,
                    WebAddress  = editEntryDto.WebAddress,
                    IsDeleted   = false
                };
                userEntry.Entry.CurrentEntryState = newEntryState;
                var entryAction = CreateEntryAction(owner, newEntryState, userEntry.Entry, ActionTypesEnum.Edit);

                await _mainDbContext.AddAsync(entryAction);

                await _mainDbContext.SaveChangesAsync();

                return(new Status(true, "Password has been successfully edited"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(new Status
                {
                    Success = false,
                    Message = "Something went wrong"
                });
            }
        }
コード例 #21
0
        public async Task RotatingKeyEncryptor_EncryptDecrypt_bytes()
        {
            var encr1   = new SymmetricEncryptor(new Key(new EncryptionPolicy()));
            var factory = new Mock <IRotatingEncryptorFactory>();
            var encr    = new RotatingKeyEncryptor(factory.Object);

            factory.Setup((f) => f.GetValidForEncryption()).ReturnsAsync(encr1);
            factory.Setup((f) => f.GetValidForDecryption(encr1.Policy.Id)).ReturnsAsync(encr1);

            await TestEncryptDecrypt(encr, DataToEncrypt1);
            await TestEncryptDecrypt(encr, DataToEncrypt2);
            await TestEncryptDecrypt(encr, DataToEncrypt3);
            await TestEncryptDecrypt(encr, DataToEncrypt4);
        }
コード例 #22
0
        public async Task EncryptorExtensions_EncryptDecrypt()
        {
            var encr = new SymmetricEncryptor(new Key(new EncryptionPolicy()));

            await TestEncryptDecrypt(encr, DataToEncrypt1);
            await TestEncryptDecrypt(encr, DataToEncrypt2);
            await TestEncryptDecrypt(encr, DataToEncrypt3);
            await TestEncryptDecrypt(encr, DataToEncrypt4);
            await TestEncryptDecrypt(encr, DataToEncrypt5);
            await TestEncryptDecrypt(encr, DataToEncrypt6);
            await TestEncryptDecrypt(encr, DataToEncrypt7);
            await TestEncryptDecrypt(encr, DataToEncrypt8);
            await TestEncryptDecrypt(encr, DataToEncrypt9);
        }
コード例 #23
0
        public void CanEncryptByString()
        {
            var credential = new Credential(
                () => new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 },
                SymmetricAlgorithm.Aes, 16);

            var symmetricEncryptor = new SymmetricEncryptor(credential, Encoding.UTF8);

            var unencrypted = "This is some string";
            var encrypted   = symmetricEncryptor.Encrypt(unencrypted);

            encrypted.Should().NotBeNullOrEmpty();
            encrypted.Should().NotBe(unencrypted);
        }
コード例 #24
0
        public async Task <Status> GetPassword(Guid id, string login, CancellationToken cancellationToken)
        {
            var requestUser = await _passwordWalletContext.Users.FirstOrDefaultAsync(p => p.Login == login);

            if (requestUser == null)
            {
                return(new Status(false, "Cannot get password"));
            }

            var function = await _passwordWalletContext.Functions.FirstOrDefaultAsync(x => x.Name == FunctionName.Wallet.GetPassword, cancellationToken);

            await LogFunction(function.Id, requestUser.Id, cancellationToken);

            var encryptedPassword = await _passwordWalletContext.Passwords.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);

            if (encryptedPassword == null)
            {
                return(new Status
                {
                    Success = false,
                    Messege = string.Format("Cannot find password with id: {0}", id)
                });
            }

            if (encryptedPassword.UserId != requestUser.Id)
            {
                var isRequestUserHavePerrmission = _passwordWalletContext.SharedPasswords
                                                   .Any(s => s.UserId == requestUser.Id && encryptedPassword.Id == s.PasswordId);

                if (!isRequestUserHavePerrmission)
                {
                    return(new Status(false, "Dont have access to this password"));
                }
            }

            var ownerPassword = await _passwordWalletContext.Users.FirstOrDefaultAsync(p => p.Id == encryptedPassword.UserId);

            if (ownerPassword == null)
            {
                return(new Status(false, "Cannot get password"));
            }

            var password = SymmetricEncryptor.DecryptToString(encryptedPassword.PasswordValue, ownerPassword.PasswordHash);

            return(new Status
            {
                Success = true,
                Messege = password
            });
        }
コード例 #25
0
ファイル: Form1.cs プロジェクト: iqman/MACMSC
        private void buttonUploadNow_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listBoxUploadKeywords.Items.Count == 0)
                {
                    MessageBox.Show("At least one keyword must be associated with the data before it is uploaded");
                    return;
                }
                if (!this.userkeysLoaded)
                {
                    MessageBox.Show("You must load user keys first");
                    return;
                }

                byte[] fileContent = File.ReadAllBytes(this.labelUploadData.Text);

                AesEncryptionInfo encryptionInfo = SymmetricEncryptor.GenerateSymmetricKeyInfo();

                byte[] fileCiphertext = SymmetricEncryptor.Encrypt(fileContent, encryptionInfo);

                IPreService preProxy = CreatePreProxy();
                byte[]      encSymIv = preProxy.Encrypt(this.masterPublicKey, encryptionInfo.IV);

                preProxy = CreatePreProxy();
                byte[] encSymKey = preProxy.Encrypt(this.masterPublicKey, encryptionInfo.Key);

                byte[] name = SymmetricEncryptor.Encrypt(Path.GetFileName(this.labelUploadData.Text).GetBytes(), encryptionInfo);

                DataEntity entity = new DataEntity();
                entity.Attributes = CollectAndEncryptAttributes(encryptionInfo);
                entity.Payload    = new FilePayload(name, fileCiphertext);
                entity.AesInfo    = new AesEncryptionInfo(encSymKey, encSymIv);
                entity.Id         = Guid.NewGuid(); // perhaps base guid on the file path??

                entity.Signature = DataSigner.Sign(entity, this.userSignKeys);

                IGatewayService proxy = CreateServiceProxy();

                proxy.InsertData(GetUserIdentity(), entity);

                MessageBox.Show("Done uploading");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                Logger.LogError("Error preparing and uploading data to server", ex);
            }
        }
コード例 #26
0
        public async Task SymmetricEncryptor_EncryptDecrypt_stream_small()
        {
            using (var encr = new SymmetricEncryptor(new Key(new EncryptionPolicy())))
            {
                using (var input = new MemoryStream())
                {
                    // Initialize input with some data
                    await input.WriteAsync("bobsyouruncle");

                    input.Seek(0, SeekOrigin.Begin);

                    await TestEncryptDecrypt(encr, input, "bobsyouruncle");
                }
            }
        }
コード例 #27
0
        public void CanEncryptByString()
        {
            var credentialMock = new Mock <ICredential>();

            credentialMock.Setup(cm => cm.Algorithm).Returns(SymmetricAlgorithm.Aes);
            credentialMock.Setup(cm => cm.IVSize).Returns(16);
            credentialMock.Setup(cm => cm.GetKey()).Returns(new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 });

            var symmetricEncryptor = new SymmetricEncryptor(credentialMock.Object, Encoding.UTF8);

            var unencrypted = "This is some string";
            var encrypted   = symmetricEncryptor.Encrypt(unencrypted);

            encrypted.Should().NotBeNullOrEmpty();
            encrypted.Should().NotBe(unencrypted);
        }
コード例 #28
0
        public async Task <Status> GetEntryPassword(int userId, int entryId)
        {
            var userEntries = await _mainDbContext.UsersEntries
                              .Include(x => x.Entry.CurrentEntryState)
                              .Include(x => x.User)
                              .Where(x => x.EntryId == entryId && x.UserId == userId)
                              .FirstOrDefaultAsync();

            if (userEntries == null)
            {
                return new Status {
                           Success = false, Message = "No entry founded"
                }
            }
            ;

            var userOwnerHash = await _mainDbContext.UsersEntries
                                .Include(x => x.User)
                                .Where(x => x.EntryId == entryId && x.IsUserOwner)
                                .Select(x => x.User.PasswordHash)
                                .FirstOrDefaultAsync();

            var password = SymmetricEncryptor.DecryptToString(userEntries.Entry.CurrentEntryState.PasswordE, userOwnerHash);

            EntryAction newEntryAction = CreateEntryAction(userEntries.User, userEntries.Entry.CurrentEntryState,
                                                           userEntries.Entry, ActionTypesEnum.View);

            try
            {
                await _mainDbContext.AddAsync(newEntryAction);

                await _mainDbContext.SaveChangesAsync();

                return(new Status {
                    Success = true, Message = password
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(new Status
                {
                    Success = false,
                    Message = "Something went wrong"
                });
            }
        }
コード例 #29
0
    public static void MismatchedEncodingCausesEncodingDiscrepency()
    {
        var credential = new Credential(
            () => new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 },
            SymmetricAlgorithm.Aes, 16);

        using var symmetricEncryptor = new SymmetricEncryptor(credential, Encoding.UTF8);
        using var symmetricDecryptor = new SymmetricDecryptor(credential, Encoding.UTF32);

        var unencrypted = "This is some string. 😂🤣";
        var encrypted   = symmetricEncryptor.Encrypt(unencrypted);
        var decrypted   = symmetricDecryptor.Decrypt(encrypted);

        encrypted.Should().NotBe(unencrypted);
        decrypted.Should().NotBe(encrypted);
        decrypted.Should().NotBe(unencrypted);
    }
コード例 #30
0
    public static void CanRoundTripByString()
    {
        var credential = new Credential(
            () => new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 },
            SymmetricAlgorithm.Aes, 16);

        using var symmetricEncryptor = new SymmetricEncryptor(credential, Encoding.UTF8);
        using var symmetricDecryptor = new SymmetricDecryptor(credential, Encoding.UTF8);

        var unencrypted = "This is some string";
        var encrypted   = symmetricEncryptor.Encrypt(unencrypted);
        var decrypted   = symmetricDecryptor.Decrypt(encrypted);

        encrypted.Should().NotBe(unencrypted);
        decrypted.Should().NotBe(encrypted);
        decrypted.Should().Be(unencrypted);
    }