/*
         * HELPER ROUTINES
         */

        internal IAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(ISecret secret, IServiceProvider services = null)
        {
            return CreateImplementationOptions()
                .ToConfiguration(services)
                .CreateDescriptorFromSecret(secret)
                .CreateEncryptorInstance();
        }
示例#2
0
        /// <summary>
        /// Creates a new Secret from another secret object.
        /// </summary>
        public Secret(ISecret secret)
        {
            if (secret == null)
            {
                throw new ArgumentNullException(nameof(secret));
            }

            Secret other = secret as Secret;

            if (other != null)
            {
                // Fast-track: simple deep copy scenario.
                this._localAllocHandle = other._localAllocHandle.Duplicate();
                this._plaintextLength  = other._plaintextLength;
            }
            else
            {
                // Copy the secret to a temporary managed buffer, then protect the buffer.
                // We pin the temp buffer and zero it out when we're finished to limit exposure of the secret.
                byte[] tempPlaintextBuffer = new byte[secret.Length];
                fixed(byte *pbTempPlaintextBuffer = tempPlaintextBuffer)
                {
                    try
                    {
                        secret.WriteSecretIntoBuffer(new ArraySegment <byte>(tempPlaintextBuffer));
                        _localAllocHandle = Protect(pbTempPlaintextBuffer, (uint)tempPlaintextBuffer.Length);
                        _plaintextLength  = (uint)tempPlaintextBuffer.Length;
                    }
                    finally
                    {
                        UnsafeBufferUtil.SecureZeroMemory(pbTempPlaintextBuffer, tempPlaintextBuffer.Length);
                    }
                }
            }
        }
示例#3
0
        /// <summary>
        /// Converts an <see cref="ISecret"/> to an &lt;masterKey&gt; element which is marked
        /// as requiring encryption.
        /// </summary>
        /// <param name="secret">The secret for accessing the master key.</param>
        /// <returns>The master key <see cref="XElement"/>.</returns>
        public static XElement ToMasterKeyElement(this ISecret secret)
        {
            // Technically we'll be keeping the unprotected secret around in memory as
            // a string, so it can get moved by the GC, but we should be good citizens
            // and try to pin / clear our our temporary buffers regardless.
            byte[] unprotectedSecretRawBytes = new byte[secret.Length];
            string unprotectedSecretAsBase64String;

            fixed(byte *__unused__ = unprotectedSecretRawBytes)
            {
                try
                {
                    secret.WriteSecretIntoBuffer(new ArraySegment <byte>(unprotectedSecretRawBytes));
                    unprotectedSecretAsBase64String = Convert.ToBase64String(unprotectedSecretRawBytes);
                }
                finally
                {
                    Array.Clear(unprotectedSecretRawBytes, 0, unprotectedSecretRawBytes.Length);
                }
            }

            var masterKeyElement = new XElement("masterKey",
                                                new XComment(" Warning: the key below is in an unencrypted form. "),
                                                new XElement("value", unprotectedSecretAsBase64String));

            masterKeyElement.MarkAsRequiresEncryption();
            return(masterKeyElement);
        }
示例#4
0
        public void AddAwsSecretHappyPath()
        {
            ISecret secret      = null;
            var     builderMock = new Mock <ISecretsConfigurationBuilder>();

            builderMock
            .Setup(bm => bm.AddSecret(It.IsAny <ISecret>()))
            .Callback <ISecret>(s => secret = s);

            var configurationKey  = "configurationKey";
            var secretId          = "secretId";
            var secretKey         = "secretKey";
            var awsSecretsManager = new Mock <IAmazonSecretsManager>().Object;

            builderMock.Object.AddAwsSecret(configurationKey, secretId, secretKey, awsSecretsManager);

            builderMock.Verify(bm => bm.AddSecret(It.IsAny <ISecret>()), Times.Once);

            var awsSecret = secret.Should().BeOfType <AwsSecret>().Subject;

            awsSecret.ConfigurationKey.Should().Be(configurationKey);
            awsSecret.SecretId.Should().Be(secretId);
            awsSecret.SecretKey.Should().Be(secretKey);
            awsSecret.SecretsManager.Should().BeSameAs(awsSecretsManager);
        }
示例#5
0
        /*
         * HELPER ROUTINES
         */

        internal GcmAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(ISecret secret, ILogger logger = null)
        {
            return(new GcmAuthenticatedEncryptor(
                       keyDerivationKey: new Secret(secret),
                       symmetricAlgorithmHandle: GetSymmetricBlockCipherAlgorithmHandle(logger),
                       symmetricAlgorithmKeySizeInBytes: (uint)(EncryptionAlgorithmKeySize / 8)));
        }
示例#6
0
        public static byte[] ProtectWithDpapiNG(ISecret secret, NCryptDescriptorHandle protectionDescriptorHandle)
        {
            Debug.Assert(secret != null);
            Debug.Assert(protectionDescriptorHandle != null);

            var plaintextSecret = new byte[secret.Length];

            fixed(byte *pbPlaintextSecret = plaintextSecret)
            {
                try
                {
                    secret.WriteSecretIntoBuffer(new ArraySegment <byte>(plaintextSecret));

                    byte dummy; // used to provide a valid memory address if secret is zero-length
                    return(ProtectWithDpapiNGCore(
                               protectionDescriptorHandle: protectionDescriptorHandle,
                               pbData: (pbPlaintextSecret != null) ? pbPlaintextSecret : &dummy,
                               cbData: (uint)plaintextSecret.Length));
                }
                finally
                {
                    // Limits secret exposure to garbage collector.
                    Array.Clear(plaintextSecret, 0, plaintextSecret.Length);
                }
            }
        }
示例#7
0
    // ReSharper disable once SuggestBaseTypeForParameter
    internal async Task WriteToFileAsync <TResult>(ISecret <TResult> secret, string xml, bool sample, bool encrypted, IErrorsAndInfos errorsAndInfos) where TResult : class, ISecretResult <TResult>, new()
    {
        if (!XmlSchemer.Valid(secret.Guid, xml, typeof(TResult), errorsAndInfos))
        {
            return;
        }

        var fileName = FileName(secret, sample, encrypted);

        if (!encrypted)
        {
            await File.WriteAllTextAsync(fileName, xml);

            await File.WriteAllTextAsync(fileName.Replace(".xml", ".xsd"), XmlSchemer.Create(typeof(TResult)));

            return;
        }

        var disguisedPassphrase = await GetDisguisedPassphraseAsync(errorsAndInfos);

        if (string.IsNullOrEmpty(disguisedPassphrase))
        {
            return;
        }

        var unencryptedFileName = FileName(secret, sample, false);

        unencryptedFileName        = unencryptedFileName[(unencryptedFileName.LastIndexOf("\\", StringComparison.Ordinal) + 1)..];
示例#8
0
        public AesGcmAuthenticatedEncryptor(ISecret keyDerivationKey, int derivedKeySizeInBytes, IManagedGenRandom?genRandom = null)
        {
            _keyDerivationKey      = new Secret(keyDerivationKey);
            _derivedkeySizeInBytes = derivedKeySizeInBytes;

            switch (_derivedkeySizeInBytes)
            {
            case 16:
                _contextHeader = AES_128_GCM_Header;
                break;

            case 24:
                _contextHeader = AES_192_GCM_Header;
                break;

            case 32:
                _contextHeader = AES_256_GCM_Header;
                break;

            default:
                throw CryptoUtil.Fail("Unexpected AES key size in bytes only support 16, 24, 32.");     // should never happen
            }

            _genRandom = genRandom ?? ManagedGenRandomImpl.Instance;
        }
        public void EstimatedUnsignedSizeIsSameAsSignedSize2()
        {
            var tool = new Tool();
            var keys = new ISecret[]
            {
                FromPrivKey.GetBitcoinSecret(Network.RegTest),
                FeePrivKey.GetBitcoinSecret(Network.RegTest)
            };

            var dust            = Money.Parse(this.DustCostBTC.ToString());
            var fromUnspentCoin = new List <UnspentCoin>
            {
                tool.NewUnspentCoin(FromAddress, dust + Money.Parse("0.00000001"))
            };

            var feeUnspentCoins = new List <UnspentCoin>
            {
                tool.NewUnspentCoin(FeeAddress, Money.Parse("2")),
                tool.NewUnspentCoin(FeeAddress, Money.Parse("3.53"))
            };


            var feeRate = new FeeRate(Money.Parse("10"));

            var result = this.InvokeBuild(fromUnspentCoin, feeUnspentCoins, dust, feeRate);
            var tx     = result.Transaction;

            tx.Sign(keys, result.InputCoins.ToArray());

            var esitmatedSize = result.SizeFromFee;
            var actualSize    = tx.GetSerializedSize();
            var delta         = esitmatedSize - actualSize;

            Assert.IsTrue(delta == 34 + tx.Inputs.Count);
        }
示例#10
0
        protected override async Task <string> GenerateSecret(ISecret secret, ILogger log)
        {
            log.LogInformation($"Resource Name: {secret.ResourceName}");
            log.LogInformation($"Resource Group Name: {secret.ResourceGroupName}");
            log.LogInformation($"Subscription Id: {secret.SubscriptionId}");
            log.LogInformation($"Expires In (days): {secret.ExpiresInDays}");

            var creds = new DefaultAzureCredential(includeInteractiveCredentials: true);
            StorageManagementClient managementClient = new StorageManagementClient(secret.SubscriptionId, creds);
            var accountKey = (await managementClient.StorageAccounts.ListKeysAsync(secret.ResourceGroupName, secret.ResourceName)).Value.Keys[0];

            AccountSasBuilder sasBuilder = new AccountSasBuilder()
            {
                Services      = AccountSasServices.Blobs,
                ResourceTypes = AccountSasResourceTypes.Service,
                ExpiresOn     = DateTimeOffset.UtcNow.AddDays(int.Parse(secret.ExpiresInDays)),
                Protocol      = SasProtocol.Https,
            };

            sasBuilder.SetPermissions(AccountSasPermissions.Read |
                                      AccountSasPermissions.Write | AccountSasPermissions.List);

            // Use the key to get the SAS token.
            string sasToken = sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(secret.ResourceName, accountKey.Value)).ToString();

            return(sasToken);
        }
        /*
         * HELPER ROUTINES
         */

        internal GcmAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(ISecret secret, ILogger logger = null)
        {
            return new GcmAuthenticatedEncryptor(
                keyDerivationKey: new Secret(secret),
                symmetricAlgorithmHandle: GetSymmetricBlockCipherAlgorithmHandle(logger),
                symmetricAlgorithmKeySizeInBytes: (uint)(EncryptionAlgorithmKeySize / 8));
        }
    internal IAuthenticatedEncryptor?CreateAuthenticatedEncryptorInstance(
        ISecret secret,
        AuthenticatedEncryptorConfiguration?authenticatedConfiguration)
    {
        if (authenticatedConfiguration == null)
        {
            return(null);
        }

        if (IsGcmAlgorithm(authenticatedConfiguration.EncryptionAlgorithm))
        {
#if NETCOREAPP
            return(new AesGcmAuthenticatedEncryptor(secret, GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm) / 8));
#else
            // GCM requires CNG, and CNG is only supported on Windows.
            if (!OSVersionUtil.IsWindows())
            {
                throw new PlatformNotSupportedException(Resources.Platform_WindowsRequiredForGcm);
            }

            Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));

            var configuration = new CngGcmAuthenticatedEncryptorConfiguration()
            {
                EncryptionAlgorithm        = GetBCryptAlgorithmNameFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm)
            };

            return(new CngGcmAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
#endif
        }
        else
        {
            if (OSVersionUtil.IsWindows())
            {
                Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
                // CNG preferred over managed implementations if running on Windows
                var configuration = new CngCbcAuthenticatedEncryptorConfiguration()
                {
                    EncryptionAlgorithm        = GetBCryptAlgorithmNameFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                    EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm),
                    HashAlgorithm = GetBCryptAlgorithmNameFromValidationAlgorithm(authenticatedConfiguration.ValidationAlgorithm)
                };

                return(new CngCbcAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
            }
            else
            {
                // Use managed implementations as a fallback
                var configuration = new ManagedAuthenticatedEncryptorConfiguration()
                {
                    EncryptionAlgorithmType    = GetManagedTypeFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                    EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm),
                    ValidationAlgorithmType    = GetManagedTypeFromValidationAlgorithm(authenticatedConfiguration.ValidationAlgorithm)
                };

                return(new ManagedAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
            }
        }
    }
示例#13
0
        /// <summary>
        /// Creates a new Secret from another secret object.
        /// </summary>
        public Secret(ISecret secret)
        {
            if (secret == null)
            {
                throw new ArgumentNullException(nameof(secret));
            }

            Secret other = secret as Secret;
            if (other != null)
            {
                // Fast-track: simple deep copy scenario.
                this._localAllocHandle = other._localAllocHandle.Duplicate();
                this._plaintextLength = other._plaintextLength;
            }
            else
            {
                // Copy the secret to a temporary managed buffer, then protect the buffer.
                // We pin the temp buffer and zero it out when we're finished to limit exposure of the secret.
                byte[] tempPlaintextBuffer = new byte[secret.Length];
                fixed (byte* pbTempPlaintextBuffer = tempPlaintextBuffer)
                {
                    try
                    {
                        secret.WriteSecretIntoBuffer(new ArraySegment<byte>(tempPlaintextBuffer));
                        _localAllocHandle = Protect(pbTempPlaintextBuffer, (uint)tempPlaintextBuffer.Length);
                        _plaintextLength = (uint)tempPlaintextBuffer.Length;
                    }
                    finally
                    {
                        UnsafeBufferUtil.SecureZeroMemory(pbTempPlaintextBuffer, tempPlaintextBuffer.Length);
                    }
                }
            }
        }
        /*
         * HELPER ROUTINES
         */

        internal IAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(ISecret secret, IServiceProvider services = null)
        {
            return(CreateImplementationOptions()
                   .ToConfiguration(services)
                   .CreateDescriptorFromSecret(secret)
                   .CreateEncryptorInstance());
        }
示例#15
0
        private static async Task <string> WriteSecretToTempFileAsync(ISecret secret, CancellationToken cancellationToken)
        {
            var tempFileName = Path.GetTempFileName();
            await secret.WriteToFileAsync(tempFileName, cancellationToken);

            return(tempFileName);
        }
示例#16
0
    public async Task <TResult> GetAsync <TResult>(ISecret <TResult> secret, IErrorsAndInfos errorsAndInfos) where TResult : class, ISecretResult <TResult>, new()
    {
        TResult valueOrDefault;

        SaveSample(secret, false);

        var encrypted = secret is IEncryptedSecret <TResult>;
        var fileName  = FileName(secret, false, encrypted);

        if (!File.Exists(fileName))
        {
            if (SecretShouldDefaultSecretsBeStored == null)
            {
                SecretShouldDefaultSecretsBeStored = new SecretShouldDefaultSecretsBeStored();
                await GetAsync(SecretShouldDefaultSecretsBeStored, errorsAndInfos);
            }
            var shouldDefaultSecretsBeStored = await ValueOrDefaultAsync(SecretShouldDefaultSecretsBeStored, errorsAndInfos);

            if (!shouldDefaultSecretsBeStored.AutomaticallySaveDefaultSecretIfAbsent)
            {
                SaveSample(secret, true);
                var defaultFileName = FileName(secret, true, encrypted);
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.PleaseLoadSecretSampleAdjustAndThenSaveAs, defaultFileName, fileName));
                return(null);
            }

            await SetAsync(secret, errorsAndInfos);

            return(await ValueOrDefaultAsync(secret, errorsAndInfos));
        }

        if (Values.ContainsKey(secret.Guid))
        {
            valueOrDefault = await ValueOrDefaultAsync(secret, errorsAndInfos);

            return(valueOrDefault);
        }

        var xml = await ReadFromFileAsync(secret, false, encrypted, errorsAndInfos);

        if (string.IsNullOrEmpty(xml))
        {
            return(null);
        }

        valueOrDefault = XmlDeserializer.Deserialize <TResult>(xml);
        if (!IsGenericType(valueOrDefault.GetType()))
        {
            foreach (var property in valueOrDefault.GetType().GetProperties().Where(p => p.GetValue(valueOrDefault) == null))
            {
                SaveSample(secret, true);
                var defaultFileName = FileName(secret, true, encrypted);
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.AddedPropertyNotFoundInLoadedSecret, property.Name, fileName, defaultFileName));
            }
        }

        Values[secret.Guid] = valueOrDefault;
        return(valueOrDefault);
    }
示例#17
0
 public Secret(ISecret secret)
 {
     Value = secret.Value;
     Name = secret.Name;
     Version = secret.Version;
     ContentType = secret.ContentType;
     Id = secret.Id;
 }
        public static async Task <string> GetSecretAsync(this ISecret secret, string key)
        {
            var pairs = await secret.GetSecretAsync();

            var dictionary = pairs.FromJson <Dictionary <string, string> >();

            return(dictionary[key]);
        }
示例#19
0
        /*
         * HELPER ROUTINES
         */

        internal ManagedAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(ISecret secret, ILogger logger = null)
        {
            return(new ManagedAuthenticatedEncryptor(
                       keyDerivationKey: new Secret(secret),
                       symmetricAlgorithmFactory: GetSymmetricBlockCipherAlgorithmFactory(logger),
                       symmetricAlgorithmKeySizeInBytes: EncryptionAlgorithmKeySize / 8,
                       validationAlgorithmFactory: GetKeyedHashAlgorithmFactory(logger)));
        }
示例#20
0
 public MixCoin(SmartCoin coin, ISecret secret)
 {
     SmartCoin = Guard.NotNull(nameof(coin), coin);
     if (!SmartCoin.Locked)
     {
         throw new NotSupportedException("Lock SmartCoin before creating a MixCoin.");
     }
     Secret = Guard.NotNull(nameof(secret), secret);
 }
示例#21
0
文件: User.cs 项目: Mavtak/roomie
 public User(string alias, string email, int id, DateTime? registeredTimestamp, ISecret secret, string token)
 {
     Alias = alias;
     Email = email;
     Id = id;
     RegisteredTimestamp = registeredTimestamp;
     Secret = secret;
     Token = token;
 }
示例#22
0
        /// <inheritdoc />
        public async Task SaveSecretAsync(ISecret secret, string context, CancellationToken cancellationToken = default)
        {
            var tempFileName = await WriteSecretToTempFileAsync(secret, cancellationToken).ConfigureAwait(false);

            var command = $"replace -f \"{tempFileName}\"";
            await _kubectl.ExecuteAsync(command, context, cancellationToken).ConfigureAwait(false);

            File.Delete(tempFileName);
        }
示例#23
0
文件: User.cs 项目: Mavtak/roomie
 public User(string alias, string email, int id, DateTime?registeredTimestamp, ISecret secret, string token)
 {
     Alias = alias;
     Email = email;
     Id    = id;
     RegisteredTimestamp = registeredTimestamp;
     Secret = secret;
     Token  = token;
 }
        public string GetSecretValue(ISecret secret)
        {
            if (secret == null)
            {
                throw new ArgumentException("Can not retrieve a secret value from a null secret instance");
            }

            return(secret.SecretValue.ToJSON().ToString());
        }
示例#25
0
        public static string Format(this ISecret secret)
        {
            var result = new StringBuilder();

            result.Append(secret.Name);
            result.Append(":");
            result.Append(secret.StoredValue);

            return(result.ToString());
        }
        private Key GetWalletPrivateKeyForServer()
        {
            IWalletManager wm = this.node.FullNode.NodeService <IWalletManager>();

            Wallet    wallet             = wm.LoadWallet(Password, WalletName);
            HdAddress hdAddress          = wallet.GetAllAddresses().Last();
            ISecret   extendedPrivateKey = wallet.GetExtendedPrivateKeyForAddress(Password, hdAddress);

            return(extendedPrivateKey.PrivateKey);
        }
示例#27
0
        public async Task <string> GetSecretAsync()
        {
            if (string.IsNullOrEmpty(savedSecret))
            {
                savedSecret = await inner.GetSecretAsync();

                inner = null; // dont need inner anymore let's free up some memory
            }

            return(savedSecret);
        }
示例#28
0
 public override void Write(Utf8JsonWriter writer, ISecret <T> value, JsonSerializerOptions options)
 {
     if (value is SecretAddress <T> secretAddress)
     {
         JsonSerializer.Serialize(writer, secretAddress, options);
     }
     else if (value is SecretValue <T> secretValue)
     {
         throw new JsonException("SecretValue should not be serialized");
     }
 }
示例#29
0
    public async Task SetAsync <TResult>(ISecret <TResult> secret, IErrorsAndInfos errorsAndInfos) where TResult : class, ISecretResult <TResult>, new()
    {
        var valueOrDefault = await ValueOrDefaultAsync(secret, errorsAndInfos);

        var xml       = XmlSerializer.Serialize(valueOrDefault);
        var encrypted = secret is IEncryptedSecret <TResult>;

        await WriteToFileAsync(secret, xml, false, encrypted, errorsAndInfos);

        Values[secret.Guid] = valueOrDefault;
    }
示例#30
0
        public void key_test_from_bytes()
        {
            //Example private key taken from https://en.bitcoin.it/wiki/Private_key
            Byte[] privateKey = new Byte[32] { 0xE9, 0x87, 0x3D, 0x79, 0xC6, 0xD8, 0x7D, 0xC0, 0xFB, 0x6A, 0x57, 0x78, 0x63, 0x33, 0x89, 0xF4, 0x45, 0x32, 0x13, 0x30, 0x3D, 0xA6, 0x1F, 0x20, 0xBD, 0x67, 0xFC, 0x23, 0x3A, 0xA3, 0x32, 0x62 };
            Key key1 = new Key(privateKey, -1, false);

            ISecret wifKey = key1.GetWif(NBitcoin.Network.Main);

            //Example wif private key taken from https://en.bitcoin.it/wiki/Private_key
            const String expected = "5Kb8kLf9zgWQnogidDA76MzPL6TsZZY36hWXMssSzNydYXYB9KF";
            Assert.True(wifKey.ToString() == expected);
        }
示例#31
0
        internal IAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(
            ISecret secret,
            AuthenticatedEncryptorConfiguration authenticatedConfiguration)
        {
            if (authenticatedConfiguration == null)
            {
                return(null);
            }

            if (IsGcmAlgorithm(authenticatedConfiguration.EncryptionAlgorithm))
            {
                // GCM requires CNG, and CNG is only supported on Windows.
                if (!OSVersionUtil.IsWindows())
                {
                    throw new PlatformNotSupportedException("GCM algorithms require the Windows platform.");
                }

                var configuration = new CngGcmAuthenticatedEncryptorConfiguration()
                {
                    EncryptionAlgorithm        = GetBCryptAlgorithmNameFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                    EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm)
                };

                return(new CngGcmAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
            }
            else
            {
                if (OSVersionUtil.IsWindows())
                {
                    // CNG preferred over managed implementations if running on Windows
                    var configuration = new CngCbcAuthenticatedEncryptorConfiguration()
                    {
                        EncryptionAlgorithm        = GetBCryptAlgorithmNameFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                        EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm),
                        HashAlgorithm = GetBCryptAlgorithmNameFromValidationAlgorithm(authenticatedConfiguration.ValidationAlgorithm)
                    };

                    return(new CngCbcAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
                }
                else
                {
                    // Use managed implementations as a fallback
                    var configuration = new ManagedAuthenticatedEncryptorConfiguration()
                    {
                        EncryptionAlgorithmType    = GetManagedTypeFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                        EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm),
                        ValidationAlgorithmType    = GetManagedTypeFromValidationAlgorithm(authenticatedConfiguration.ValidationAlgorithm)
                    };

                    return(new ManagedAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
                }
            }
        }
 /// <summary>
 /// Scan the Transaction for StealthCoin given address and scan key
 /// </summary>
 /// <param name="tx">The transaction to scan</param>
 /// <param name="address">The stealth address</param>
 /// <param name="scan">The scan private key</param>
 /// <returns></returns>
 public StealthPayment[] GetPayments(Transaction transaction, ISecret scanKey)
 {
     if (transaction == null)
     {
         throw new ArgumentNullException(nameof(transaction));
     }
     if (scanKey == null)
     {
         throw new ArgumentNullException(nameof(scanKey));
     }
     return(GetPayments(transaction, scanKey.PrivateKey));
 }
        private static void CreateNewSecretVersion(ISecret secret, string newSecretValue)
        {
            // add new secret version to key vault
            var newSecret = new KeyVaultSecret(secret.Name, newSecretValue);

            foreach (var tag in secret.Tags)
            {
                newSecret.Properties.Tags.Add(tag.Key, tag.Value);
            }

            newSecret.Properties.ExpiresOn = DateTime.UtcNow.AddDays(int.Parse(secret.ValidityPeriodDays));
            secret.Client.SetSecret(newSecret);
        }
示例#34
0
        public void SetSecret(KeyId keyId, ISecret secret)
        {
            if (keyId == null)
            {
                throw new ArgumentNullException(nameof(keyId));
            }

            if (secret == null)
            {
                throw new ArgumentNullException(nameof(secret));
            }

            Secrets.AddOrReplace(keyId, secret);
        }
 public StoredSecret(ISecret secret)
 {
     ContentType = secret.ContentType;
     Id = secret.Id;
     if (Id == Guid.Empty)
     {
         Id = Guid.NewGuid();
     }
     Value = secret.Value;
     Name = secret.Name;
     Version = secret.Version;
     PartitionKey = Cloud.GetCoud().ToKey(Name);
     RowKey = PartitionKey + ":" + Version.ToString();
 }
        /// <summary>
        /// Creates a secret
        /// </summary>
        /// <param name="secretName">A secret</param>
        /// <param name="secret">More data about the secret</param>
        /// <returns>The saved secret</returns>
        public ISecret CreateSecret(string secretName, ISecret secret)
        {
            secret.Name = secretName;

            var store = new StoredSecret(secret);
            var table = _cloud.GetTable(Table, _connectionString);
            var exists = GetAllSecrets(table, store);

            store.Version = exists.Count() + 1;

            store = new StoredSecret(store);

            return _cloud.SetObject(table, store);
        }
示例#37
0
        internal CngGcmAuthenticatedEncryptor?CreateAuthenticatedEncryptorInstance(
            ISecret secret,
            CngGcmAuthenticatedEncryptorConfiguration configuration)
        {
            if (configuration == null)
            {
                return(null);
            }

            return(new CngGcmAuthenticatedEncryptor(
                       keyDerivationKey: new Secret(secret),
                       symmetricAlgorithmHandle: GetSymmetricBlockCipherAlgorithmHandle(configuration),
                       symmetricAlgorithmKeySizeInBytes: (uint)(configuration.EncryptionAlgorithmKeySize / 8)));
        }
        public AuthenticatedEncryptorDescriptor(AuthenticatedEncryptionSettings settings, ISecret masterKey, IServiceProvider services)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (masterKey == null)
            {
                throw new ArgumentNullException(nameof(masterKey));
            }

            Settings = settings;
            MasterKey = masterKey;
            _services = services;
        }
        public ManagedAuthenticatedEncryptorDescriptor(ManagedAuthenticatedEncryptionOptions options, ISecret masterKey, IServiceProvider services)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (masterKey == null)
            {
                throw new ArgumentNullException(nameof(masterKey));
            }

            Options = options;
            MasterKey = masterKey;
            _log = services.GetLogger<ManagedAuthenticatedEncryptorDescriptor>();
        }
        public CngCbcAuthenticatedEncryptorDescriptor(CngCbcAuthenticatedEncryptionSettings settings, ISecret masterKey, IServiceProvider services)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (masterKey == null)
            {
                throw new ArgumentNullException(nameof(masterKey));
            }

            Settings = settings;
            MasterKey = masterKey;
            _log = services.GetLogger<CngCbcAuthenticatedEncryptorDescriptor>();
        }
        /// <summary>
        /// Deletes all secrets ... this is a permanent operation
        /// </summary>
        /// <param name="secret">The secret</param>
        /// <returns></returns>
        public bool DeleteSecret(ISecret secret)
        {
            try
            {
                var table = _cloud.GetTable(Table, _connectionString);
                var all = GetAllSecrets(table, new StoredSecret(secret));

                foreach (var aSecret in all)
                {
                    table.Execute(TableOperation.Delete(aSecret));
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
        public static byte[] ProtectWithDpapi(ISecret secret, bool protectToLocalMachine = false)
        {
            Debug.Assert(secret != null);

            byte[] plaintextSecret = new byte[secret.Length];
            fixed (byte* pbPlaintextSecret = plaintextSecret)
            {
                try
                {
                    secret.WriteSecretIntoBuffer(new ArraySegment<byte>(plaintextSecret));
                    fixed (byte* pbPurpose = _purpose)
                    {
                        return ProtectWithDpapiCore(pbPlaintextSecret, (uint)plaintextSecret.Length, pbPurpose, (uint)_purpose.Length, fLocalMachine: protectToLocalMachine);
                    }
                }
                finally
                {
                    // To limit exposure to the GC.
                    Array.Clear(plaintextSecret, 0, plaintextSecret.Length);
                }
            }
        }
 IAuthenticatedEncryptorDescriptor IInternalAuthenticatedEncryptorConfiguration.CreateDescriptorFromSecret(ISecret secret)
 {
     return new ManagedAuthenticatedEncryptorDescriptor(Options, secret, _services);
 }
 IAuthenticatedEncryptorDescriptor IInternalAuthenticatedEncryptorConfiguration.CreateDescriptorFromSecret(ISecret secret)
 {
     return new CngGcmAuthenticatedEncryptorDescriptor(Settings, secret, _services);
 }
 public CngCbcAuthenticatedEncryptorDescriptor(CngCbcAuthenticatedEncryptionOptions options, ISecret masterKey)
     : this(options, masterKey, services: null)
 {
 }
        public static byte[] ProtectWithDpapiNG(ISecret secret, NCryptDescriptorHandle protectionDescriptorHandle)
        {
            Debug.Assert(secret != null);
            Debug.Assert(protectionDescriptorHandle != null);

            byte[] plaintextSecret = new byte[secret.Length];
            fixed (byte* pbPlaintextSecret = plaintextSecret)
            {
                try
                {
                    secret.WriteSecretIntoBuffer(new ArraySegment<byte>(plaintextSecret));

                    byte dummy; // used to provide a valid memory address if secret is zero-length
                    return ProtectWithDpapiNGCore(
                        protectionDescriptorHandle: protectionDescriptorHandle,
                        pbData: (pbPlaintextSecret != null) ? pbPlaintextSecret : &dummy,
                        cbData: (uint)plaintextSecret.Length);
                }
                finally
                {
                    // Limits secret exposure to garbage collector.
                    Array.Clear(plaintextSecret, 0, plaintextSecret.Length);
                }
            }
        }
示例#47
0
 /// <summary>
 /// Asserts that <paramref name="secret"/> has the length specified by <paramref name="expectedLengthInBits"/>.
 /// </summary>
 public static void LengthIs(int expectedLengthInBits, ISecret secret)
 {
     Assert.Equal(expectedLengthInBits, checked(secret.Length * 8));
 }
示例#48
0
 /// <summary>
 /// Asserts that two <see cref="ISecret"/> instances do not contain the same material.
 /// </summary>
 public static void NotEqual(ISecret secret1, ISecret secret2)
 {
     Assert.NotEqual(SecretToBase64String(secret1), SecretToBase64String(secret2));
 }
示例#49
0
 private static string SecretToBase64String(ISecret secret)
 {
     byte[] secretBytes = new byte[secret.Length];
     secret.WriteSecretIntoBuffer(new ArraySegment<byte>(secretBytes));
     return Convert.ToBase64String(secretBytes);
 }
 public CngCbcAuthenticatedEncryptorDescriptor(CngCbcAuthenticatedEncryptionSettings settings, ISecret masterKey)
     : this(settings, masterKey, services: null)
 {
 }
 private static AuthenticatedEncryptorDescriptor CreateDescriptor(EncryptionAlgorithm encryptionAlgorithm, ValidationAlgorithm validationAlgorithm, ISecret masterKey)
 {
     return new AuthenticatedEncryptorDescriptor(new AuthenticatedEncryptionOptions()
     {
         EncryptionAlgorithm = encryptionAlgorithm,
         ValidationAlgorithm = validationAlgorithm
     }, masterKey);
 }
示例#52
0
		/// <summary>
		/// Scan the Transaction for StealthCoin given address and scan key
		/// </summary>
		/// <param name="tx">The transaction to scan</param>
		/// <param name="address">The stealth address</param>
		/// <param name="scan">The scan private key</param>
		/// <returns></returns>
		public StealthPayment[] GetPayments(Transaction transaction, ISecret scanKey)
		{
			if(transaction == null)
				throw new ArgumentNullException("transaction");
			if(scanKey == null)
				throw new ArgumentNullException("scanKey");
			return GetPayments(transaction, scanKey.PrivateKey);
		}