public void Recyclabe_Decrypt_1KB(int x)
 {
     for (var i = 0; i < x; i++)
     {
         RecyclableEncryptionProvider.Decrypt(EncryptedPayload);
     }
 }
예제 #2
0
        public TOut DecryptDecompressDeserialize <TOut>(ReadOnlyMemory <byte> data)
        {
            var decryptedData    = _encryptionProvider.Decrypt(data);
            var decompressedData = _compressionProvider.Decompress(decryptedData);

            return(_serializationProvider.Deserialize <TOut>(decompressedData));
        }
 public void Decrypt_1KB(int x)
 {
     for (var i = 0; i < x; i++)
     {
         EncryptionProvider.Decrypt(EncryptedPayload);
     }
 }
예제 #4
0
        public void Should_decrypt_valid_data()
        {
            const string clear = "This is some input";
            var          input = provider.Encrypt(clear);

            var output = provider.Decrypt(input);

            output.ShouldEqual(clear);
        }
예제 #5
0
 internal static GetPaymentsResponse MapGetPaymentsResponse(Payment payment, IEncryptionProvider encryptionProvider)
 {
     return(new GetPaymentsResponse
     {
         CardNumber = MaskCreditCard(encryptionProvider.Decrypt(payment.CardNumber)),
         NameOnCard = encryptionProvider.Decrypt(payment.NameOnCard),
         ExpiryDate = encryptionProvider.Decrypt(payment.ExpiryDate),
         Amount = payment.Amount,
         CreatedOn = payment.CreatedOn,
     });
 }
예제 #6
0
        public SantaUser GetUser(long id)
        {
            var model = WithConnection(conn => conn.Get <SantaUser>(id));

            if (model == null)
            {
                return(null);
            }

            _encryptionProvider.Decrypt(model);
            return(model);
        }
예제 #7
0
        public async Task <RegisterUserResponse> Handle(RegisterUserRequest request, CancellationToken cancellationToken)
        {
            User foundUser;

            if (request.User.Id == default ||
                (await _userService.Get(request.User.Id, cancellationToken)) == null)
            {
                return(Response.Failed <RegisterUserResponse>(new ValidationFailure(
                                                                  nameof(request.User.Id), $"User with '{request.User.Id}' not found")));
            }

            var encryptedUser = await _encryptionProvider.Encrypt <UserDto, User>(request.User);

            foundUser = await _userService
                        .GetByEmailAddress(request.User.ApplicationInstance, encryptedUser.EmailAddress, cancellationToken);

            if (foundUser != null &&
                request.User.Id != default &&
                foundUser.Id != request.User.Id)
            {
                return(Response.Failed <RegisterUserResponse>(new ValidationFailure(
                                                                  nameof(request.User.EmailAddress), $"User with '{request.User.EmailAddress}' not found")));
            }

            if (await _applicationInstanceService.GetByInstanceId(request.User.ApplicationInstance, cancellationToken) == null)
            {
                return(Response.Failed <RegisterUserResponse>(new ValidationFailure(nameof(request.User.ApplicationInstance),
                                                                                    $"Application instance '{request.User.ApplicationInstance}' not found")));
            }
            var savedUser = await _userService.Save(encryptedUser, cancellationToken);

            var decryptedUser = await _encryptionProvider.Decrypt <User, UserDto>(savedUser);

            return(Response.Success <RegisterUserResponse>(decryptedUser));
        }
예제 #8
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var secret        = serializer.Deserialize <Secret>(reader);
            var bodyJsonBytes = provider.Decrypt(secret);

            return(JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bodyJsonBytes), objectType));
        }
        /// <summary>
        ///   Load the session identifier from the specified context.
        /// </summary>
        /// <param name="context">The current context.</param>
        /// <returns>The identifier of the session for the current request.</returns>
        public SessionId GetCurrentSessionId(NancyContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var cookieData = _sessionIdentificationDataProvider.ProvideDataFromCookie(context.Request, CookieName);

            if (cookieData == null)
            {
                return(_sessionIdFactory.CreateNew());
            }
            var isHmacValid = _hmacValidator.IsValidHmac(cookieData);

            if (!isHmacValid)
            {
                return(_sessionIdFactory.CreateNew());
            }

            var decryptedSessionId = _encryptionProvider.Decrypt(cookieData.SessionId);

            if (string.IsNullOrEmpty(decryptedSessionId))
            {
                return(_sessionIdFactory.CreateNew());
            }

            return(_sessionIdFactory.CreateFrom(decryptedSessionId) ?? _sessionIdFactory.CreateNew());
        }
예제 #10
0
        /// <summary>
        /// Sends pending e-mails. An e-mail that failed to be sent is considered as pending until it reaches
        /// max trial count
        /// </summary>
        public void SendPendingEMails()
        {
            List <Task> mailTasks = new List <Task>();

            using (IDbContext dbContext = this._dbContextFactory.Create())
            {
                foreach (EMail email in GetPendingEmailsFromQueue(dbContext).ToList())
                {
                    try
                    {
                        email.JobStatus              = JobStatus.Running;
                        email.SmtpPassword           = _encryptionProvider.Decrypt(email.SmtpPassword, _configurationFactory().SymmetricKey);
                        dbContext.Entry(email).State = EntityState.Modified;
                        dbContext.SaveChanges();
                        this.SendEMail(email);
                        email.JobStatus = JobStatus.Finished;
                    }
                    catch (Exception ex)
                    {
                        email.JobStatus    = JobStatus.Failed;
                        email.ErrorMessage = ex.Message + " : " + ex.StackTrace;
                    }
                    finally
                    {
                        email.TryCount++;
                        email.LastExecutionTime      = DateTime.UtcNow;
                        email.SmtpPassword           = _encryptionProvider.Encrypt(email.SmtpPassword, _configurationFactory().SymmetricKey);
                        dbContext.Entry(email).State = EntityState.Modified;
                        dbContext.SaveChanges();
                    }
                }
            }
        }
예제 #11
0
        public static string DecryptSigned(
            IEncryptionProvider encryptionProvider,
            IHmacProvider signatureProvider,
            string input)
        {
            try
            {
                var signatureLength = Base64Helpers.GetBase64Length(signatureProvider.HmacLength);

                var encryptedInput = input.Substring(signatureLength);
                var signature = input.Substring(0, signatureLength);

                var signatureBytes = Convert.FromBase64String(signature);
                var newSignatureBytes = signatureProvider.GenerateHmac(encryptedInput);
                var signatureIsValid = HmacComparer.Compare(
                    signatureBytes,
                    newSignatureBytes,
                    signatureProvider.HmacLength);

                var decryptedId = encryptionProvider.Decrypt(encryptedInput);

                return signatureIsValid ? decryptedId : String.Empty;
            }
            catch
            {
                return String.Empty;
            }
        }
예제 #12
0
        public void GetPassword(string key, string passPhrase)
        {
            _encryptionProvider.Decrypt("passwords.asc", passPhrase);

            var rows = File.ReadAllLines("passwords.csv");

            foreach (var row in rows)
            {
                var array = row.Split(',');
                if (array[0].IndexOf(key, StringComparison.CurrentCultureIgnoreCase) > -1)
                {
                    Console.WriteLine(row);
                }
            }

            File.Delete("passwords.csv");
        }
예제 #13
0
 public static string Decrypt(this IEncryptionProvider provider, string encyptedText)
 {
     if (string.IsNullOrEmpty(encyptedText))
     {
         return(string.Empty);
     }
     return(provider.Decrypt(encyptedText.ToBase64Bytes()).ToUTF8String());
 }
예제 #14
0
        private void DecryptText()
        {
            if (string.IsNullOrEmpty(EncryptedText))
            {
                return;
            }

            DecryptedText = _encryptionProvider.Decrypt(EncryptedText, TestPassword, TestSalt);
        }
        public void Should_return_original_text_when_decrypting()
        {
            var inputText = "this is some text";
            var encText   = provider.Encrypt(inputText);

            var result = provider.Decrypt(encText);

            result.ShouldEqual(inputText);
        }
        public async Task <RegisterAccountResponse> Handle(RegisterAccountRequest request, CancellationToken cancellationToken)
        {
            var encryptedAccount = await _encryptionProvider.Encrypt <Account, Domains.Data.Account>(request.Account);

            var savedAccount = await _accountService.SaveAccount(encryptedAccount);

            var account = await _encryptionProvider.Decrypt <Domains.Data.Account, Account>(savedAccount);

            return(Response.Success <RegisterAccountResponse>(account));
        }
        public async Task <SaveCustomerResponse> Handle(SaveCustomerRequest request, CancellationToken cancellationToken)
        {
            var customer          = _mapperProvider.Map <SaveCustomerRequest, CustomerDto>(request);
            var encryptedCustomer = await _encryptionProvider.Encrypt <CustomerDto, Customer>(customer);

            encryptedCustomer = await _customerService.SaveCustomer(encryptedCustomer, cancellationToken);

            customer = await _encryptionProvider.Decrypt <Customer, CustomerDto>(encryptedCustomer);

            return(Response.Success <SaveCustomerResponse>(customer));
        }
        public T Decrypt(string cipherText)
        {
            if (string.IsNullOrWhiteSpace(cipherText))
            {
                throw new ArgumentNullException(nameof(cipherText));
            }

            var jsonRepresentation = _encryptionProvider.Decrypt(cipherText);

            return(JsonConvert.DeserializeObject <T>(jsonRepresentation));
        }
예제 #19
0
        public void EncryptionProviderEncrypts()
        {
            IServiceProvider sp = StartUp.ServiceProvider;

            IEncryptionProvider encryptionProvider = sp.GetService <ITokenEncryptionProvider>();
            string text      = "I am sergio";
            string encrypted = encryptionProvider.Encrypt(text);
            string decrypted = encryptionProvider.Decrypt(encrypted);

            Assert.IsTrue(text == decrypted);
        }
예제 #20
0
        public Dictionary <string, int> GetAll()
        {
            var words = _context.WordDictionary
                        .AsNoTracking()
                        .ToList();

            var result = new ConcurrentDictionary <string, int>();

            words.AsParallel()
            .ForAll(item => result.AddOrUpdate(_encryptionProvier.Decrypt(item.Word), 1, (k, v) => v + item.Count));

            return(result.OrderByDescending(x => x.Value).ToDictionary(entry => entry.Key, entry => entry.Value));
        }
        public async Task <GetCustomerResponse> Handle(GetCustomerRequest request, CancellationToken cancellationToken)
        {
            var customer = await _customerService.GetCustomer(request.Id, cancellationToken);

            if (customer == null)
            {
                return(Response.Failed <GetCustomerResponse>());
            }

            var decryptedCustomer = await _encryptionProvider
                                    .Decrypt <Customer, CustomerDto>(customer);

            return(Response.Success <GetCustomerResponse>(decryptedCustomer));
        }
예제 #22
0
        public static string DecryptAndValidateAuthenticationCookie(string cookieValue)
        {
            var hmacLength = Base64Helpers.GetBase64Length(hmacProvider.HmacLength);

            var hmacValue     = cookieValue.Substring(0, hmacLength);
            var encryptCookie = cookieValue.Substring(hmacLength);

            // Check the hmac, but don't early exit if they don't match
            var bytes     = Convert.FromBase64String(hmacValue);
            var newHmac   = hmacProvider.GenerateHmac(encryptCookie);
            var hmacValid = HmacComparer.Compare(newHmac, bytes, hmacProvider.HmacLength);

            var decrypted = encryptionProvider.Decrypt(encryptCookie);

            // Only return the decrypted result if tht hmac was ok
            return(hmacValid ? decrypted : string.Empty);
        }
        public byte[] Read(Guid id, string filename)
        {
            Dictionary <string, string> metaData;

            byte[] data = storageProvider.Read(id, filename, out metaData);
            if (metaData.ContainsKey(EncryptionKey))
            {
                IEncryptionProvider encryptionProvider = Factory.GetEncryptionProvider((EncryptionProviderType)Enum.Parse(typeof(EncryptionProviderType), metaData[EncryptionKey]), configurationProvider);
                data = encryptionProvider.Decrypt(data);
            }
            if (metaData.ContainsKey(CompressionKey))
            {
                ICompressionProvider compressionProvider = Factory.GetCompressionProvider((CompressionProviderType)Enum.Parse(typeof(CompressionProviderType), metaData[CompressionKey]), configurationProvider);
                data = compressionProvider.Decompress(data);
            }
            return(data);
        }
예제 #24
0
        public async Task <CreateTokenResponse> Handle(CreateTokenRequest request, CancellationToken cancellationToken)
        {
            var generatedString = _randomStringGenerator
                                  .GenerateString(CharacterType.Lowercase | CharacterType.Uppercase | CharacterType.Numerics, 64);

            var requestToken = new Domains.Dto.RequestToken {
                Key     = generatedString,
                Expires = _clockProvider.DateTimeOffset
                          .AddMinutes(request.ValidityPeriodInMinutes)
            };

            var savedRequestToken = await _requestTokenService.SaveRequestToken(await _encryptionProvider
                                                                                .Encrypt <Domains.Dto.RequestToken, RequestToken>(requestToken), cancellationToken);

            return(Response.Success <CreateTokenResponse>(await _encryptionProvider
                                                          .Decrypt <RequestToken, Domains.Dto.RequestToken>(savedRequestToken)));
        }
예제 #25
0
파일: Reader.cs 프로젝트: zxc04/file-reader
        public string ReadFile(FileTypes fileType, string path, bool isEncrypted = false, string role = null)
        {
            if (roleProvider != null && !roleProvider.HasAccess(path, role))
            {
                throw new UnauthorizedAccessException();
            }

            IContentReader reader = ContentReaderFactory.GetReader(fileType);

            string content = reader.ReadContent(path);

            if (isEncrypted && encryptionProvider != null)
            {
                content = encryptionProvider.Decrypt(content);
            }

            return(content);
        }
예제 #26
0
        public async Task <LoginResponse> Handle(LoginRequest request, CancellationToken cancellationToken)
        {
            try
            {
                request.Password = Convert.ToBase64String(
                    request.Password.GetBytes(Encoding.UTF8).ToArray());

                var account          = _mapperProvider.Map <LoginRequest, Account>(request);
                var encryptedAccount = await _encryptionProvider.Encrypt <Account, Domains.Data.Account>(account);

                var foundAccount = await _accountService.GetAccount(encryptedAccount.EmailAddress, cancellationToken);

                if (foundAccount == null)
                {
                    throw new NullReferenceException();
                }

                if (!foundAccount.Password.SequenceEqual(encryptedAccount.Password))
                {
                    throw new UnauthorizedAccessException();
                }

                account = await _encryptionProvider.Decrypt <Domains.Data.Account, Account>(foundAccount);

                return(Response.Success <LoginResponse>(account));
            }
            catch (Exception ex)
            {
                var exceptionType = ex.GetType();

                if (exceptionType == typeof(NullReferenceException) ||
                    exceptionType == typeof(UnauthorizedAccessException))
                {
                    return new LoginResponse {
                               IsSuccessful = false, Errors = new [] {
                                   new ValidationFailure(nameof(Account.EmailAddress), "EmailAddress or password invalid")
                               }
                    }
                }
                ;

                throw;
            }
        }
예제 #27
0
        public static string DecryptAndValidateAuthenticationCookie(string cookieValue)
        {
            var dtcodtdCookie = HttpUtility.UrlDecode(cookieValue);

            var hmacstringLtngth = Base64Helpers.GetBase64Length(HmacProvider.HmacLength);

            var tncrypttdCookie = dtcodtdCookie.Substring(hmacstringLtngth);
            var hmacstring      = dtcodtdCookie.Substring(0, hmacstringLtngth);

            // Chtck tht hmact, but don't tarly txit if thty don't match
            var hmacByset = Convert.FromBase64String(hmacstring);
            var newHmac   = HmacProvider.GenerateHmac(tncrypttdCookie);
            var hmacValid = HmacComparer.Compare(newHmac, hmacByset, HmacProvider.HmacLength);

            var dtcrypttd = encryptionProvider.Decrypt(tncrypttdCookie);

            // Only return tht dtcrypttd rttult if tht hmac wat ok
            return(hmacValid ? dtcrypttd : string.Empty);
        }
예제 #28
0
        /// <summary>
        /// Decrypts password fields.
        /// </summary>
        /// <param name="settingValue">Value</param>
        /// <param name="settingDefiniton">Definition</param>
        /// <returns>Decrypted setting value</returns>
        private SettingValue Decrypt(SettingValue settingValue, SettingDefinition settingDefiniton)
        {
            if (settingValue == null || settingDefiniton == null)
            {
                return(settingValue);
            }

            for (int i = 1; i <= 15; i++)
            {
                FormInputType inputType = (FormInputType)settingDefiniton.GetType().GetProperty("FieldInputType" + i.ToString()).GetValue(settingDefiniton, null);

                if (inputType == FormInputType.Password)
                {
                    string value = (string)settingValue.GetType().GetProperty("Field" + i.ToString()).GetValue(settingValue, null);
                    value = _encryptionProvider.Decrypt(value, _configurationFactory().SymmetricKey);
                    settingValue.GetType().GetProperty("Field" + i.ToString()).SetValue(settingValue, value);
                }
            }

            return(settingValue);
        }
예제 #29
0
        public async Task <Account> ValidateCookieToken(Action <TokenValidationParameters> tokenValidationParameters,
                                                        string cookieToken, CancellationToken cancellationToken)
        {
            var claims = ValidateToken(tokenValidationParameters, EncryptionKeyConstants.Default, cookieToken);

            if (claims == null)
            {
                throw new UnauthorizedAccessException();
            }

            var defaultClaim = claims.ToClaimObject <DefaultClaim>();

            var account = await _accountService.GetAccount(defaultClaim.AccountId, EntityUsage.UseLocally, cancellationToken);

            if (account == null)
            {
                throw new UnauthorizedAccessException();
            }

            return(await _encryptionProvider.Decrypt <Domains.Data.Account, Account>(account));
        }
예제 #30
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            // Get arguments
            Tuple <IEncryptionProvider, IStorageProvider, string> args =
                (Tuple <IEncryptionProvider, IStorageProvider, string>)e.Argument;

            IEncryptionProvider encryptionProvider = args.Item1;
            IStorageProvider    storageProvider    = args.Item2;
            string file = args.Item3;

            // Read cipher text from file
            byte[] cipherText;
            try
            {
                cipherText = storageProvider.Read(file);
            }
            catch (Exception ex)
            {
                // Exception occured whilst reading file, so wrap
                // exception nicely for display output
                throw new Exception($"An {ex.GetType().Name} occured whilst reading the file:\r\n{ex.Message}", ex);
            }

            // Decrypt back to plain text
            byte[] plainText;
            try
            {
                plainText = encryptionProvider.Decrypt(cipherText);
            }
            catch (Exception ex)
            {
                // Exception occured whilst decrypting text, so wrap
                // exception nicely for display output
                throw new Exception($"An {ex.GetType().Name} occured whilst decrypting the text:\r\n{ex.Message}", ex);
            }

            // Return string message
            e.Result = Encoding.UTF8.GetString(plainText);
        }
        protected internal Header ReadHeader(
            Stream reader,
            ISymmetricEncryptionProviderOptions options,
            ReadOnlySpan <byte> privateKey = default,
            IEncryptionProvider symmetricKeyEncryptionProvider = null)
        {
            Check.NotNull(nameof(reader), reader);
            Check.NotNull(nameof(options), options);

            ReadOnlySpan <byte> signingKey = default;

            if (options.SigningKey != null)
            {
                signingKey = options.SigningKey.Memory.Span;
            }

            using (var ms = new MemoryStream())
                using (var bw = new BinaryWriter(ms, Utf8.NoBom, true))
                    using (var br = new BinaryReader(reader, Utf8.NoBom, true))
                    {
                        var version = br.ReadInt16();
                        bw.Write(version);
                        Header header = null;
                        switch (version)
                        {
                        case 1:
                        default:
                            header = new HeaderV1();
                            break;
                        }

                        // header shorts/ints
                        // 1. version
                        // 2. algo
                        // 3. signing,
                        // 4. metadataSize
                        // 5  iterations
                        // 6. symmetricSaltSize
                        // 7. signingSaltSize
                        // 8. ivSize
                        // 9. symmetricKeySize
                        // 10. hashSize

                        // header values
                        // 1. metadata
                        // 2. symmetricSalt
                        // 3. signingSalt
                        // 4. iv
                        // 5. symmetricKey
                        // 6. hash
                        header.SymmetricAlgorithmType = (SymmetricAlgorithmType)br.ReadInt16();
                        header.KeyedHashAlgorithmType = (KeyedHashAlgorithmType)br.ReadInt16();
                        header.MetaDataSize           = br.ReadInt32();
                        header.Iterations             = br.ReadInt32();
                        header.SymmetricSaltSize      = br.ReadInt16();
                        header.SigningSaltSize        = br.ReadInt16();
                        header.IvSize           = br.ReadInt16();
                        header.SymmetricKeySize = br.ReadInt16();
                        header.HashSize         = br.ReadInt16();

                        bw.Write((short)header.SymmetricAlgorithmType);
                        bw.Write((short)header.KeyedHashAlgorithmType);
                        bw.Write(header.MetaDataSize);
                        bw.Write(header.Iterations);
                        bw.Write(header.SymmetricSaltSize);
                        bw.Write(header.SigningSaltSize);
                        bw.Write(header.IvSize);
                        bw.Write(header.SymmetricKeySize);
                        bw.Write(header.HashSize);

                        if (options.SymmetricAlgorithm != header.SymmetricAlgorithmType)
                        {
                            options.SymmetricAlgorithm = header.SymmetricAlgorithmType;
                            this.algorithm             = null;
                        }

                        if (options.KeyedHashedAlgorithm != header.KeyedHashAlgorithmType)
                        {
                            options.KeyedHashedAlgorithm = header.KeyedHashAlgorithmType;
                            this.signingAlgorithm        = null;
                        }

                        byte[] metadata                 = null;
                        byte[] symmetricSalt            = null;
                        ReadOnlySpan <byte> signingSalt = default;
                        byte[] iv = null;
                        ReadOnlySpan <byte> symmetricKey = default;
                        byte[] hash = null;

                        if (header.MetaDataSize > 0)
                        {
                            metadata = br.ReadBytes(header.MetaDataSize);
                            bw.Write(metadata);
                        }

                        if (header.SymmetricSaltSize > 0)
                        {
                            symmetricSalt = br.ReadBytes(header.SymmetricSaltSize);
                            bw.Write(symmetricSalt);
                        }

                        if (header.SigningSaltSize > 0)
                        {
                            signingSalt = br.ReadBytes(header.SigningSaltSize);
                            bw.Write(signingSalt);
                        }

                        if (header.IvSize > 0)
                        {
                            iv = br.ReadBytes(header.IvSize);
                            bw.Write(iv);
                        }

                        if (header.SymmetricKeySize > 0)
                        {
                            symmetricKey = br.ReadBytes(header.SymmetricKeySize);
                            bw.Write(symmetricKey);
                        }

                        if (header.HashSize > 0)
                        {
                            hash = br.ReadBytes(header.HashSize);
                            bw.Write(hash);
                        }

                        bw.Flush();
                        ms.Flush();
                        {
                            var bytes  = ms.ToArray();
                            var buffer = MemoryPool <byte> .Shared.Rent(bytes.Length);

                            bytes.CopyTo(buffer.Memory.Span);
                            header.Bytes = buffer;
                        }

                        header.Position = reader.Position;

                        if (symmetricKeyEncryptionProvider != null)
                        {
                            symmetricKey = symmetricKeyEncryptionProvider.Decrypt(symmetricKey);
                        }

                        if (symmetricKey == null && privateKey.IsEmpty)
                        {
                            throw new ArgumentNullException(nameof(privateKey),
                                                            "privateKey or symmetricKey must have a value");
                        }

                        if (!options.SkipSigning && privateKey == null && signingKey.IsEmpty)
                        {
                            throw new ArgumentNullException(nameof(privateKey),
                                                            "privateKey must have a value or options.SigningKey must have a value or options.SkipSigning must be true");
                        }

                        if (symmetricKey == null)
                        {
                            if (symmetricSalt == null)
                            {
                                throw new InvalidOperationException("symmetricSalt for the privateKey could not be retrieved");
                            }

                            using (var generator = new Rfc2898DeriveBytes(privateKey, symmetricSalt, header.Iterations, HashAlgorithmName.SHA256))
                            {
                                var buffer = MemoryPool <byte> .Shared.Rent(options.KeySize / 8);

                                ReadOnlySpan <byte> bytes = generator.GetBytes(options.KeySize / 8);
                                bytes.CopyTo(buffer.Memory.Span);
                                header.SymmetricKey = buffer;
                            }
                        }

                        if (!options.SkipSigning && (signingKey == null || signingKey.IsEmpty))
                        {
                            if (signingSalt == null)
                            {
                                throw new InvalidOperationException("symmetricSalt for the privateKey could not be retrieved");
                            }

                            var key = !symmetricKey.IsEmpty ? symmetricKey : privateKey;
                            using (var generator = new Rfc2898DeriveBytes(key, signingSalt, header.Iterations, HashAlgorithmName.SHA256))
                            {
                                generator.IterationCount = header.Iterations;
                                var buffer = MemoryPool <byte> .Shared.Rent(options.KeySize / 8);

                                ReadOnlySpan <byte> bytes = generator.GetBytes(options.KeySize / 8);
                                bytes.CopyTo(buffer.Memory.Span);
                                header.SigningKey = buffer;
                            }
                        }

                        {
                            IMemoryOwner <byte> buffer = null;

                            if (header.SymmetricKeySize > 0)
                            {
                                buffer = MemoryPool <byte> .Shared.Rent(header.SymmetricKeySize);

                                symmetricKey.CopyTo(buffer.Memory.Span);
                                header.SymmetricKey = buffer;
                            }

                            buffer = MemoryPool <byte> .Shared.Rent(iv.Length);

                            iv.CopyTo(buffer.Memory.Span);
                            header.IV = buffer;

                            buffer = MemoryPool <byte> .Shared.Rent(header.HashSize);

                            hash.CopyTo(buffer.Memory.Span);
                            header.Hash = buffer;
                        }

                        return(header);
                    }
        }
예제 #32
0
 public static string Decrypt(IEncryptionProvider encryptionProvider, string value)
 {
     return encryptionProvider.Decrypt(value);
 }