コード例 #1
1
        public Secret UpdateSecret(string vaultName, string secretName, string secretVersion, SecretAttributes secretAttributes)
        {
            if (string.IsNullOrEmpty(vaultName))
                throw new ArgumentNullException("vaultName");
            if (string.IsNullOrEmpty(secretName))
                throw new ArgumentNullException("secretName");
            if (secretAttributes == null)
                throw new ArgumentNullException("secretAttributes");

            var secretIdentifier = new SecretIdentifier(this.vaultUriHelper.CreateVaultAddress(vaultName), secretName, secretVersion);

            Azure.KeyVault.Models.SecretAttributes attributes = (Azure.KeyVault.Models.SecretAttributes)secretAttributes;

            SecretBundle secret;
            try
            {
                secret = this.keyVaultClient.UpdateSecretAsync(secretIdentifier.Identifier,
                    secretAttributes.ContentType, attributes, secretAttributes.TagsDictionary).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                throw GetInnerException(ex);
            }

            return new Secret(secret, this.vaultUriHelper);
        }
コード例 #2
0
        /// <summary>
        /// Imports a new CRL for group id.
        /// </summary>
        public async Task ImportIssuerCACrl(string id, X509Certificate2 certificate, Opc.Ua.X509CRL crl, CancellationToken ct = default)
        {
            try
            {
                string           secretIdentifier = CrlSecretName(id, certificate.Thumbprint);
                SecretAttributes secretAttributes = new SecretAttributes()
                {
                    Enabled   = true,
                    NotBefore = crl.UpdateTime
                };

                // do not set tag for a CRL, the CA cert is already tagged.

                var result = await _keyVaultClient.SetSecretAsync(
                    _vaultBaseUrl,
                    secretIdentifier,
                    Convert.ToBase64String(crl.RawData),
                    null,
                    ContentTypeCrl,
                    secretAttributes,
                    ct)
                             .ConfigureAwait(false);
            }
            catch (Exception)
            {
                // TODO: add logging (is this a fatal error?)
            }
        }
コード例 #3
0
        /// <summary>
        /// Accept Private Key for certificate in group.
        /// </summary>
        public async Task AcceptCertKey(string id, string requestId, CancellationToken ct = default)
        {
            string secretIdentifier = KeySecretName(id, requestId);
            var    secretItem       = await _keyVaultClient.GetSecretVersionsAsync(_vaultBaseUrl, secretIdentifier, null, ct);

            while (secretItem != null)
            {
                foreach (var secret in secretItem)
                {
                    var secretAttributes = new SecretAttributes
                    {
                        Enabled = false,
                        Expires = DateTime.UtcNow
                    };
                    await _keyVaultClient.UpdateSecretAsync(secret.Id, null, secretAttributes, null, ct).ConfigureAwait(false);
                }
                if (secretItem.NextPageLink != null)
                {
                    secretItem = await _keyVaultClient.GetSecretVersionsNextAsync(secretItem.NextPageLink, ct);
                }
                else
                {
                    secretItem = null;
                }
            }
        }
コード例 #4
0
        public SetKeyVaultSecretAttributeTests()
        {
            base.SetupTest();

            secretAttributes = new SecretAttributes(true, DateTime.UtcNow.AddYears(2), DateTime.UtcNow, "contenttype", null);
            secret           = new Secret()
            {
                VaultName = VaultName, Name = SecretName, Version = SecretVersion, SecretValue = null, Attributes = secretAttributes
            };

            cmdlet = new SetAzureKeyVaultSecretAttribute()
            {
                CommandRuntime    = commandRuntimeMock.Object,
                DataServiceClient = keyVaultClientMock.Object,
                VaultName         = secret.VaultName,
                Name        = secret.Name,
                Version     = secret.Version,
                Enable      = secretAttributes.Enabled,
                Expires     = secretAttributes.Expires,
                NotBefore   = secretAttributes.NotBefore,
                ContentType = secretAttributes.ContentType,
                Tags        = secretAttributes.Tags,
                PassThru    = true
            };
        }
コード例 #5
0
ファイル: CallAzure.cs プロジェクト: asta96/MyCodeBase
        private static async Task <SecretBundle> WriteKeyVault(CreateSecret Obj)// string szPFX, string szCER, string szPassword)
        {
            SecretBundle     bundle  = null;
            SecretAttributes attribs = new SecretAttributes
            {
                Enabled = true //,
                               //Expires = DateTime.UtcNow.AddYears(2), // if you want to expire the info
                               //NotBefore = DateTime.UtcNow.AddDays(1) // if you want the info to
                               // start being available later
            };

            /*  IDictionary<string, string> alltags = new Dictionary<string, string>();
             * alltags.Add("Test1", "This is a test1 value");
             * alltags.Add("Test2", "This is a test2 value");
             * alltags.Add("CanBeAnything", "Including a long encrypted string if you choose");
             * string TestName = "TestSecret";
             * string TestValue = "searchValue"; // this is what you will use to search for the item later
             * string contentType = "SecretInfo"; // whatever you want to categorize it by; you name it
             */

            IDictionary <string, string> alltags = Obj.KeyValue;
            string TestName    = Obj.SecretName;
            string TestValue   = Obj.SecretValue; // this is what you will use to search for the item later
            string contentType = Obj.ContenType;

            bundle = await kvc.SetSecretAsync
                         (BASESECRETURI, TestName, TestValue, alltags, contentType, attribs);

            return(bundle);

            //kvc.GetKeyAsync(BASESECRETURI, "");
            // Console.WriteLine("Bundle:" + bundle.Tags["Test1"].ToString());
        }
コード例 #6
0
        public SetKeyVaultSecretTests()
        {
            base.SetupTest();

            secretAttributes  = new SecretAttributes(true, null, null, null, null);
            secureSecretValue = SecretValue.ConvertToSecureString();
            secret            = new Secret()
            {
                VaultName = VaultName, Name = SecretName, Version = SecretVersion, SecretValue = secureSecretValue, Attributes = secretAttributes
            };

            cmdlet = new SetAzureKeyVaultSecret()
            {
                CommandRuntime    = commandRuntimeMock.Object,
                DataServiceClient = keyVaultClientMock.Object,
                VaultName         = secret.VaultName,
                Name        = secret.Name,
                SecretValue = secret.SecretValue,
                Disable     = new SwitchParameter(!(secretAttributes.Enabled.Value)),
                Expires     = secretAttributes.Expires,
                NotBefore   = secretAttributes.NotBefore,
                ContentType = secretAttributes.ContentType,
                Tags        = secretAttributes.Tags
            };
        }
コード例 #7
0
        public void CreateSecret(string secretName, string secretValue, string vaultURI = "", bool secretIsEnabled = true, DateTime?expirationDate = null, DateTime?notEnabledBeforeThisDate = null, Dictionary <string, string> tags = null)
        {
            SecretAttributes attr = new SecretAttributes();

            attr.Expires   = expirationDate;
            attr.NotBefore = notEnabledBeforeThisDate;
            attr.Enabled   = secretIsEnabled;
            string uri = string.Empty;

            if (!string.IsNullOrEmpty(vaultURI))
            {
                uri = vaultURI;
            }
            else
            {
                uri = vaulturi;
            }

            if (string.IsNullOrEmpty(uri))
            {
                vault.SetSecretAsync(uri, secretName, secretValue, tags, "string", attr);
            }
            else
            {
                throw new KeyVaultErrorException("Vault URI not set. Please use SetVault().");
            }
        }
コード例 #8
0
 internal SecretProperties(string value, string contentType, SecretAttributes attributes, string secretUri, string secretUriWithVersion)
 {
     Value                = value;
     ContentType          = contentType;
     Attributes           = attributes;
     SecretUri            = secretUri;
     SecretUriWithVersion = secretUriWithVersion;
 }
コード例 #9
0
 private ListViewItemSecret(ISession session, SecretIdentifier identifier, SecretAttributes attributes, string contentTypeStr, IDictionary <string, string> tags) :
     base(session, ContentTypeEnumConverter.GetValue(contentTypeStr).IsCertificate() ? CertificatesGroup : SecretsGroup,
          identifier, tags, attributes.Enabled, attributes.Created, attributes.Updated, attributes.NotBefore, attributes.Expires)
 {
     Attributes     = attributes;
     ContentTypeStr = contentTypeStr;
     ContentType    = ContentTypeEnumConverter.GetValue(contentTypeStr);
 }
コード例 #10
0
        public override async Task <ListViewItemBase> ResetExpirationAsync(CancellationToken cancellationToken)
        {
            var sa = new SecretAttributes()
            {
                NotBefore = (this.NotBefore == null) ? (DateTime?)null : DateTime.UtcNow.AddHours(-1),
                Expires   = (this.Expires == null) ? (DateTime?)null : DateTime.UtcNow.AddYears(1)
            };
            SecretBundle s = await Session.CurrentVault.UpdateSecretAsync(Name, null, new Dictionary <string, string>(Tags), null, sa, cancellationToken); // Reset only NotBefore and Expires attributes

            return(new ListViewItemSecret(Session, s));
        }
コード例 #11
0
        public static async Task <string> UpdateSecretAttributes(string secretKeyIdentifier)
        {
            var client = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(GetAccessTokenAsync),
                new System.Net.Http.HttpClient());

            SecretAttributes attributes = new SecretAttributes();

            attributes.Expires = DateTime.UtcNow.AddDays(15);

            var secret = await client.UpdateSecretAsync(secretKeyIdentifier, null, attributes, null).ConfigureAwait(false);

            return(secret.Value);
        }
コード例 #12
0
        async void WriteKeyAsync(string name, string value)
        {
            var attributes = new SecretAttributes
            {
                Enabled = true
            };

            await _client.SetSecretAsync(
                vaultBaseUrl : _baseUrl,
                secretName : name,
                value : value,
                tags : new Dictionary <string, string>(),
                contentType : string.Empty,
                secretAttributes : attributes);;
        }
コード例 #13
0
        public async Task CreateSecret(VehiclePolicies policydata)
        {
            // Create the content for the Policy data to be stored as Secret
            Insdata akvdata = new Insdata {
                Id       = policydata.Id, Inscompany = policydata.Inscompany,
                Policyno = policydata.Policyno, Userid = policydata.Userid, Vehicleno = policydata.Vehicleno
            };

            //Create a JSON String of the Policy data to be stored as Secret
            string insurancepolicysecret = JsonConvert.SerializeObject(akvdata);

            byte[] datatoencrypt = System.Text.Encoding.UTF8.GetBytes(insurancepolicysecret);
            string keyUri        = string.Format("https://{0}.vault.azure.net/keys/{1}", _keyVaultName, _keyName);
            string keyVaultUri   = string.Format("https://{0}.vault.azure.net", _keyVaultName);


            //Encrypt the data before it is stored as a Secret
            KeyOperationResult result = await _keyVaultClient.EncryptAsync(keyUri, JsonWebKeyEncryptionAlgorithm.RSAOAEP256,
                                                                           datatoencrypt);

            byte[] encdata       = result.Result;
            string encrypteddata = Convert.ToBase64String(encdata);

            //Set the Policy Start and Expiry Data to be added as attributes to the secret
            SecretAttributes attribs = new SecretAttributes
            {
                Enabled   = true,
                Expires   = DateTime.UtcNow.AddYears(1),
                NotBefore = DateTime.UtcNow
            };

            IDictionary <string, string> alltags = new Dictionary <string, string>
            {
                { "InsuranceCompany", policydata.Inscompany }
            };
            string contentType = "DigitalInsurance";

            // Create a Secret with the encrypted Policy data
            SecretBundle bundle = await _keyVaultClient.SetSecretAsync(keyVaultUri, policydata.Uidname,
                                                                       encrypteddata, alltags, contentType, attribs);

            string bundlestr = bundle.Value;

            policydata.Version   = bundle.SecretIdentifier.Version;
            policydata.Lastmod   = bundle.Attributes.Updated;
            policydata.Startdate = bundle.Attributes.NotBefore;
            policydata.Enddate   = bundle.Attributes.Expires;
        }
コード例 #14
0
        private static async void writeKeyVault(Dictionary <string, string> keysToBeUploaded) // string szPFX, string szCER, string szPassword)
        {
            SecretAttributes attribs = new SecretAttributes
            {
                Enabled   = true,
                Expires   = DateTime.UtcNow.AddYears(1), // if you want to expire the info
                NotBefore = DateTime.UtcNow.AddDays(1)   // if you want the info to
                                                         //start being available later
            };


            foreach (var key in keysToBeUploaded.Keys)
            {
                SecretBundle bundle = await kvc.SetSecretAsync
                                          (BASESECRETURI, key, keysToBeUploaded[key], null, null, attribs);
            }
        }
コード例 #15
0
 private SecretAttributes CreateSecretAttributes()
 {
     try
     {
         var attributes = new SecretAttributes()
         {
             Enabled   = true,
             Expires   = DateTime.Now.AddYears(30),
             NotBefore = DateTime.Now.AddDays(-1),
         };
         return(attributes);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="secret"></param>
        /// <param name="value"></param>
        /// <param name="token"></param>
        /// <returns>Key Vault Secret Version Identifier</returns>
        protected override async Task <string> OnPersistSecretToVaultAsync(Secret secret, string value, CancellationToken token)
        {
            //todo: store new secret value
            //todo: vary credential providers based on need (MI/Keys/etc)
            var            azureServiceTokenProvider = new AzureServiceTokenProvider();
            KeyVaultClient kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            SecretPolicy effectivePolicy = secret?.Configuration?.Policy;

            switch (secret.ObjectType)
            {
            case "secret":

                var attributes = new SecretAttributes()
                {
                    Enabled = true
                };
                if (null != effectivePolicy)
                {
                    attributes.Expires = DateTime.UtcNow.Add(TimeSpan.FromSeconds(effectivePolicy.RotationIntervalInSec));
                }

                value = await ProcessSecretExpressionAsync(secret, value, kvClient, token);

                var result = await kvClient.SetSecretAsync($"https://{secret.VaultName}.vault.azure.net", secret.ObjectName, value
                                                           , secretAttributes : attributes, cancellationToken : token);

                if (string.Compare(result.SecretIdentifier.Version, secret.Version, true) != 0)     //disable previous version...
                {
                    await kvClient.UpdateSecretAsync(secret.Uri, secretAttributes : new SecretAttributes()
                    {
                        Enabled = false
                    });
                }

                return(result.SecretIdentifier.Version);

            case "key":
                break;

            case "certificate":
                break;
            }

            return(null);
        }
コード例 #17
0
ファイル: Secret.cs プロジェクト: shuainie/azure-powershell
        /// <summary>
        /// Internal constructor used by KeyVaultDataServiceClient
        /// </summary>
        /// <param name="clientSecret">secret returned from service</param>
        /// <param name="vaultUriHelper">helper class</param>
        internal Secret(Microsoft.Azure.KeyVault.Secret secret, VaultUriHelper vaultUriHelper)
        {
            if (secret == null)
                throw new ArgumentNullException("secret");
            
            SetObjectIdentifier(vaultUriHelper, secret.SecretIdentifier);
            if (secret.Value != null)
                SecretValue = secret.Value.ConvertToSecureString();

            Attributes = new SecretAttributes(
                secret.Attributes.Enabled, 
                secret.Attributes.Expires, 
                secret.Attributes.NotBefore,
                secret.Attributes.Created,
                secret.Attributes.Updated,
                secret.ContentType, 
                secret.Tags);            
        }
コード例 #18
0
        public async Task <bool> SetEbayTokenByCompanyId(long companyId, EbayOAuthToken token)
        {
            try
            {
                var secretIdentifier = string.Empty;
                switch (token.Type)
                {
                case EbayOAuthTokenType.USERTOKEN:
                    secretIdentifier = $"ebay-user-token-company{companyId}";
                    break;

                case EbayOAuthTokenType.REFRESHTOKEN:
                    secretIdentifier = $"ebay-refresh-token-company{companyId}";
                    break;

                default:
                    throw new InvalidTokenTypeException("The token has an invalid type.");
                }

                var secretAttributes = new SecretAttributes
                {
                    Expires = token.Expiration.Value.ToUniversalTime()
                };

                //check to see if identifier exists
                var versionList = await keyVaultClient.GetSecretVersionsAsync(appSettings.Value.KeyVaultUrl, secretIdentifier);

                if (!versionList.Any())
                {
                    await keyVaultClient.SetSecretAsync(appSettings.Value.KeyVaultUrl, secretIdentifier, token.Token, null, null, secretAttributes);
                }
                else //exists, update it
                {
                    await keyVaultClient.SetSecretAsync(keyVaultUrl, secretIdentifier, token.Token, null, null, secretAttributes);
                }

                return(true);
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                return(false);
            }
        }
コード例 #19
0
        private static async void WriteKeyVault() // string szPFX, string szCER, string szPassword)
        {
            SecretAttributes attribs = new SecretAttributes
            {
                Enabled = true
            };

            IDictionary <string, string> alltags = new Dictionary <string, string>();

            alltags.Add("Test1", "This is a test1 value");
            alltags.Add("Test2", "This is a test2 value");
            alltags.Add("CanBeAnything", "Including a long encrypted string if you choose");
            string testValue   = "searchValue"; // this is what you will use to search for the item later
            string contentType = "SecretInfo";  // whatever you want to categorize it by; you name it

            SecretBundle bundle = await kvc.SetSecretAsync
                                      (BASESECRETURI, SECRETNAME, testValue, alltags, contentType, attribs);

            Console.WriteLine("Bundle:" + bundle.Tags["Test1"].ToString());
        }
コード例 #20
0
 /// <summary>
 /// Imports a Private Key for group id and certificate.
 /// </summary>
 public async Task ImportCertKey(string id, string requestId, byte[] privateKey, string privateKeyFormat, CancellationToken ct = default)
 {
     var              contentType      = PrivateKeyFormatToContentType(privateKeyFormat);
     string           secretIdentifier = KeySecretName(id, requestId);
     DateTime         now = DateTime.UtcNow;
     SecretAttributes secretAttributes = new SecretAttributes()
     {
         Enabled   = true,
         NotBefore = now
     };
     var result = await _keyVaultClient.SetSecretAsync(
         _vaultBaseUrl,
         secretIdentifier,
         (contentType == ContentTypePfx)?Convert.ToBase64String(privateKey) : Encoding.ASCII.GetString(privateKey),
         null,
         contentType,
         secretAttributes,
         ct)
                  .ConfigureAwait(false);
 }
コード例 #21
0
        private static async void writeKeyVault()
        {
            SecretAttributes attribs = new SecretAttributes
            {
                Enabled = true
            };

            IDictionary <string, string> alltags = new Dictionary <string, string>();

            alltags.Add("Test1", "This is a test1 value");

            alltags.Add("CanBeAnything", "Including a long encrypted string if you choose");
            string TestName    = "TestSecret";
            string TestValue   = "searchValue";
            string contentType = "SecretInfo";

            SecretBundle bundle = await kvc.SetSecretAsync
                                      (BASESECRETURI, TestName, TestValue, alltags, contentType, attribs);

            Console.WriteLine("Bundle:" + bundle.Tags["Test1"].ToString());
        }
コード例 #22
0
ファイル: KeyVault.cs プロジェクト: rbiles/prototypes
        public async Task <bool> StoreCertSecret(string secretName, string secretValue)
        {
            string keyVaultUri = sentinelApiConfig.KeyVaultUri;

            try
            {
                var kv = new KeyVaultClient(authenticationCallbacks.GetToken);
                // Craft the certificate URI

                var secretUri = new UriBuilder
                {
                    Host   = keyVaultUri,
                    Scheme = "https"
                }.Uri;

                SecretAttributes attribs = new SecretAttributes
                {
                    Enabled = true,
                    Expires = DateTime.UtcNow.AddDays(90), // if you want to expire the info
                    //NotBefore = DateTime.UtcNow.AddDays(1) // if you want the info to
                };

                IDictionary <string, string> alltags = new Dictionary <string, string>();
                alltags.Add("CreationDate", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ"));
                alltags.Add("MachineName", Environment.MachineName);
                string contentType = "SentinelWSAuth"; // whatever you want to categorize it by; you name it

                SecretBundle bundle = await kv.SetSecretAsync
                                          (secretUri.AbsoluteUri, secretName, secretValue, alltags, contentType, attribs);

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                throw new ApplicationException($"Error storing secret <{secretName}> to the KeyVault {sentinelApiConfig.KeyVaultUri}", ex);
            }
        }
コード例 #23
0
        public async Task <bool> ValidateAsync(VehiclePolicies vehPoliciesMaster)
        {
            bool   isValid     = false;
            string keyUri      = string.Format("https://{0}.vault.azure.net/keys/{1}", _keyVaultName, _keyName);
            string keyVaultUri = string.Format("https://{0}.vault.azure.net", _keyVaultName);
            var    bundle      = await _keyVaultClient.GetSecretAsync(keyVaultUri, vehPoliciesMaster.Uidname);

            string decryptedstring = bundle.Value;

            byte[]             encdata = Convert.FromBase64String(decryptedstring);
            KeyOperationResult result  = await _keyVaultClient.DecryptAsync(keyUri, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, encdata);

            byte[]           decrypteddata = result.Result;
            string           secretdata    = System.Text.Encoding.UTF8.GetString(decrypteddata);
            SecretAttributes attributes    = bundle.Attributes;

            if (attributes.Expires < System.DateTime.UtcNow || attributes.NotBefore > System.DateTime.UtcNow)
            {
                isValid = false;
            }
            VehiclePolicies _vehPoliciesMaster = JsonConvert.DeserializeObject <VehiclePolicies>(secretdata);

            if (vehPoliciesMaster.Id.Equals(_vehPoliciesMaster.Id) &&
                vehPoliciesMaster.Policyno.Equals(_vehPoliciesMaster.Policyno) &&
                vehPoliciesMaster.Userid.Equals(_vehPoliciesMaster.Userid) &&
                vehPoliciesMaster.Vehicleno.Equals(_vehPoliciesMaster.Vehicleno) &&
                vehPoliciesMaster.Inscompany.Equals(_vehPoliciesMaster.Inscompany)
                )
            {
                isValid = true;
            }
            else
            {
                return(isValid);
            }
            return(isValid);
        }
コード例 #24
0
        private static SecretAttributes NewSecretAttributes(bool enabled, bool active, bool expired)
        {
            if (!active && expired)
            {
                throw new ArgumentException("Secret cannot be both inactive and expired; math not possible");
            }

            var attributes = new SecretAttributes();

            attributes.Enabled = enabled;

            if (active == false)
            {
                // Set the secret to not be active for 12 hours
                attributes.NotBefore = (DateTime.UtcNow + new TimeSpan(0, 12, 0, 0));
            }

            if (expired)
            {
                // Set the secret to be expired 12 hours ago
                attributes.Expires = (DateTime.UtcNow - new TimeSpan(0, 12, 0, 0));
            }
            return(attributes);
        }
コード例 #25
0
 /// <inheritdoc/>
 public async Task SetKeyValueAsync(string key, string value, DateTime?notBefore,
                                    DateTime?notAfter, string contentType, CancellationToken ct)
 {
     if (string.IsNullOrEmpty(key))
     {
         throw new ArgumentNullException(nameof(key));
     }
     if (string.IsNullOrEmpty(value))
     {
         throw new ArgumentNullException(nameof(value));
     }
     try {
         var secretAttributes = new SecretAttributes {
             Enabled   = true,
             NotBefore = notBefore,
             Expires   = notAfter
         };
         var secret = await _keyVaultClient.SetSecretAsync(_vaultBaseUrl,
                                                           key, value, null, contentType, secretAttributes, ct);
     }
     catch (KeyVaultErrorException ex) {
         throw new ExternalDependencyException("Failed to set secret", ex);
     }
 }
コード例 #26
0
        /// <summary>
        /// Updates the attributes associated with the specified secret in both vaults
        /// </summary>
        /// <param name="secretName">The name of the secret in the given vault</param>
        /// <param name="secretVersion">The secret version (optional)</param>
        /// <param name="tags">Application-specific metadata in the form of key-value pairs</param>
        /// <param name="contentType">Type of the secret value such as a password</param>
        /// <param name="secretAttributes">Attributes for the secret. For more information on possible attributes, <see cref="SecretAttributes"/></param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>A response message containing the updated secret from first vault</returns>
        public async Task <SecretBundle> UpdateSecretAsync(string secretName, string secretVersion = null, Dictionary <string, string> tags = null, string contentType = null, SecretAttributes secretAttributes = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            tags          = Utils.AddMd5ChangedBy(tags, null, AuthenticatedUserName);
            secretVersion = secretVersion ?? string.Empty;
            var t0 = _keyVaultClients[0].UpdateSecretAsync(_keyVaultClients[0].VaultUri, secretName, secretVersion, contentType, secretAttributes, tags, cancellationToken);
            var t1 = Secondary ? _keyVaultClients[1].UpdateSecretAsync(_keyVaultClients[1].VaultUri, secretName, secretVersion, contentType, secretAttributes, tags, cancellationToken) : CompletedTask;
            await Task.WhenAll(t0, t1).ContinueWith((t) =>
            {
                if (t0.IsFaulted && t1.IsFaulted)
                {
                    throw new SecretException($"Failed to update secret {secretName} in both vaults {_keyVaultClients[0]} and {_keyVaultClients[1]}", t0.Exception, t1.Exception);
                }
                if (t0.IsFaulted)
                {
                    throw new SecretException($"Failed to update secret {secretName} in vault {_keyVaultClients[0]}", t0.Exception);
                }
                if (t1.IsFaulted)
                {
                    throw new SecretException($"Failed to update secret {secretName} in vault {_keyVaultClients[1]}", t1.Exception);
                }
            });

            return(t0.Result);
        }
コード例 #27
0
ファイル: KeyVault.cs プロジェクト: BOONRewardsInc/rewards
 public Task <Secret> UpdateSecretAsync(string secretName, string contentType = null, SecretAttributes secretAttributes = null, Dictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(this.keyVaultClient.UpdateSecretAsync(
                this.vaultUri,
                secretName,
                contentType,
                secretAttributes,
                tags,
                cancellationToken));
 }
コード例 #28
0
        public async Task <KeyVaultSecret> CreateSecret(string secretName, string value, SecretAttributes attributes = null)
        {
            await Client.SetSecretAsync(Vault.Properties.VaultUri, secretName, value, secretAttributes : attributes);

            return(await GetSecret(secretName));
        }
コード例 #29
0
        public Secret SetSecret(string vaultName, string secretName, SecureString secretValue, SecretAttributes secretAttributes)
        {
            if (string.IsNullOrEmpty(vaultName))
                throw new ArgumentNullException("vaultName");
            if (string.IsNullOrEmpty(secretName))
                throw new ArgumentNullException("secretName");
            if (secretValue == null)
                throw new ArgumentNullException("secretValue");
            if (secretAttributes == null)
                throw new ArgumentNullException("secretAttributes");

            string value = secretValue.ConvertToString();
            string vaultAddress = this.vaultUriHelper.CreateVaultAddress(vaultName);
            var attributes = (Azure.KeyVault.Models.SecretAttributes)secretAttributes;

            Azure.KeyVault.Models.SecretBundle secret;
            try
            {
                secret = this.keyVaultClient.SetSecretAsync(vaultAddress, secretName, value,
                    secretAttributes.TagsDictionary, secretAttributes.ContentType, attributes).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                throw GetInnerException(ex);
            }

            return new Secret(secret, this.vaultUriHelper);
        }
コード例 #30
0
        public async Task UpdateSecret(VehiclePolicies policydata)
        {
            //Create the updated Policy data to be stored as a new version of the Secret
            Insdata akvdata = new Insdata
            {
                Id         = policydata.Id,
                Inscompany = policydata.Inscompany,
                Policyno   = policydata.Policyno,
                Userid     = policydata.Userid,
                Vehicleno  = policydata.Vehicleno
            };

            //Create the JSON String of the updated Policy Object
            string insurancepolicysecret = JsonConvert.SerializeObject(akvdata);

            byte[] datatoencrypt = System.Text.Encoding.UTF8.GetBytes(insurancepolicysecret);
            string keyUri        = string.Format("https://{0}.vault.azure.net/keys/{1}", _keyVaultName, _keyName);
            string keyVaultUri   = string.Format("https://{0}.vault.azure.net", _keyVaultName);


            KeyOperationResult result = null;
            //Get the metadata from the existing Secret in Key Vault
            SecretBundle bundle = await _keyVaultClient.GetSecretAsync(keyVaultUri, policydata.Uidname);

            if (bundle == null)
            {
                throw new ApplicationException("Error locating Secret data to update");
                //No need to execute the rest of the steps if the Secret cannot be retrieved
            }
            SecretAttributes             _attribs     = bundle.Attributes;
            string                       _contentType = bundle.ContentType;
            IDictionary <string, string> dic          = bundle.Tags;

            //Create the attributes for the updated Secret
            SecretAttributes attribsNew = new SecretAttributes
            {
                Enabled   = true,
                Expires   = _attribs.Expires,
                NotBefore = DateTime.UtcNow
            };

            IDictionary <string, string> alltags = dic;
            string contentType = _contentType;

            // Encrypt the updated Secret data
            result = await _keyVaultClient.EncryptAsync(keyUri, JsonWebKeyEncryptionAlgorithm.RSAOAEP256,
                                                        datatoencrypt);

            byte[] encdata       = result.Result;
            string encrypteddata = Convert.ToBase64String(encdata);

            //Create a new version of the Secret by calling the SetSecret Method, and using the attributes from the previous version of the Secret
            bundle = await _keyVaultClient.SetSecretAsync(keyVaultUri, policydata.Uidname,
                                                          encrypteddata, alltags, contentType, attribsNew);

            string bundlestr = bundle.Value;

            policydata.Version   = bundle.SecretIdentifier.Version;
            policydata.Lastmod   = bundle.Attributes.Updated;
            policydata.Startdate = bundle.Attributes.NotBefore;
            policydata.Enddate   = bundle.Attributes.Expires;
        }