public async Task KeyVault_KeyVaultKeyResolver_Secret256Base64()
        {
            // Arrange
            var client = CreateKeyVaultClient();
            var vault  = ConfigurationManager.AppSettings["VaultUrl"];

            var keyBytes = new byte[256 >> 3];

            new RNGCryptoServiceProvider().GetNonZeroBytes(keyBytes);

            var secret = await client.SetSecretAsync(vault, "TestSecret", Convert.ToBase64String(keyBytes), null, "application/octet-stream").ConfigureAwait(false);

            if (secret != null)
            {
                try
                {
                    // ctor with client
                    var resolver = new KeyVaultKeyResolver(client);

                    var baseKey = await resolver.ResolveKeyAsync(secret.SecretIdentifier.BaseIdentifier, default(CancellationToken)).ConfigureAwait(false);

                    var versionKey = await resolver.ResolveKeyAsync(secret.SecretIdentifier.Identifier, default(CancellationToken)).ConfigureAwait(false);

                    Assert.Equal(baseKey.Kid, versionKey.Kid);

                    // ctor with authentication callback
                    resolver = new KeyVaultKeyResolver(GetAccessToken);

                    baseKey = await resolver.ResolveKeyAsync(secret.SecretIdentifier.BaseIdentifier, default(CancellationToken)).ConfigureAwait(false);

                    versionKey = await resolver.ResolveKeyAsync(secret.SecretIdentifier.Identifier, default(CancellationToken)).ConfigureAwait(false);

                    Assert.Equal(baseKey.Kid, versionKey.Kid);

                    // ctor with vault name and client
                    resolver = new KeyVaultKeyResolver(vault, client);

                    baseKey = await resolver.ResolveKeyAsync(secret.SecretIdentifier.BaseIdentifier, default(CancellationToken)).ConfigureAwait(false);

                    versionKey = await resolver.ResolveKeyAsync(secret.SecretIdentifier.Identifier, default(CancellationToken)).ConfigureAwait(false);

                    Assert.Equal(baseKey.Kid, versionKey.Kid);

                    // ctor with vault name and authentication callback
                    resolver = new KeyVaultKeyResolver(vault, GetAccessToken);

                    baseKey = await resolver.ResolveKeyAsync(secret.SecretIdentifier.BaseIdentifier, default(CancellationToken)).ConfigureAwait(false);

                    versionKey = await resolver.ResolveKeyAsync(secret.SecretIdentifier.Identifier, default(CancellationToken)).ConfigureAwait(false);

                    Assert.Equal(baseKey.Kid, versionKey.Kid);
                }
                finally
                {
                    // Delete the key
                    client.DeleteSecretAsync(vault, "TestSecret").GetAwaiter().GetResult();
                }
            }
        }
        public async Task KeyVault_KeyVaultKeyResolver_Key()
        {
            // Arrange
            var client = CreateKeyVaultClient();
            var vault  = ConfigurationManager.AppSettings["VaultUrl"];

            var key = await client.CreateKeyAsync(vault, "TestKey", JsonWebKeyType.Rsa).ConfigureAwait(false);

            if (key != null)
            {
                try
                {
                    // ctor with client
                    var resolver = new KeyVaultKeyResolver(client);

                    var baseKey = await resolver.ResolveKeyAsync(key.KeyIdentifier.BaseIdentifier, default(CancellationToken)).ConfigureAwait(false);

                    var versionKey = await resolver.ResolveKeyAsync(key.KeyIdentifier.Identifier, default(CancellationToken)).ConfigureAwait(false);

                    Assert.Equal(baseKey.Kid, versionKey.Kid);

                    // ctor with authentication callback
                    resolver = new KeyVaultKeyResolver(GetAccessToken);

                    baseKey = await resolver.ResolveKeyAsync(key.KeyIdentifier.BaseIdentifier, default(CancellationToken)).ConfigureAwait(false);

                    versionKey = await resolver.ResolveKeyAsync(key.KeyIdentifier.Identifier, default(CancellationToken)).ConfigureAwait(false);

                    Assert.Equal(baseKey.Kid, versionKey.Kid);

                    // ctor with vault name and client
                    resolver = new KeyVaultKeyResolver(vault, client);

                    baseKey = await resolver.ResolveKeyAsync(key.KeyIdentifier.BaseIdentifier, default(CancellationToken)).ConfigureAwait(false);

                    versionKey = await resolver.ResolveKeyAsync(key.KeyIdentifier.Identifier, default(CancellationToken)).ConfigureAwait(false);

                    Assert.Equal(baseKey.Kid, versionKey.Kid);

                    // ctor with vault name and authentication callback
                    resolver = new KeyVaultKeyResolver(vault, GetAccessToken);

                    baseKey = await resolver.ResolveKeyAsync(key.KeyIdentifier.BaseIdentifier, default(CancellationToken)).ConfigureAwait(false);

                    versionKey = await resolver.ResolveKeyAsync(key.KeyIdentifier.Identifier, default(CancellationToken)).ConfigureAwait(false);

                    Assert.Equal(baseKey.Kid, versionKey.Kid);
                }
                finally
                {
                    // Delete the key
                    client.DeleteKeyAsync(vault, "TestKey").GetAwaiter().GetResult();
                }
            }
        }
        public async Task SaveContentAsync(EncryptedFile fileInfo, IFormFile formFile)
        {
            if (fileInfo == null)
            {
                return;
            }

            var blobParts     = fileInfo.BlobName.Split(ContainerNameSeparator);
            var containerName = blobParts[0];
            var blobName      = blobParts[1];

            var contain = _cloudBlobClient.GetContainerReference(containerName);

            contain.CreateIfNotExists();

            var rsa = await _cloudResolver.ResolveKeyAsync(
                _fileStorageKey,
                CancellationToken.None);

            var policy = new BlobEncryptionPolicy(rsa, null);

            var options = new BlobRequestOptions {
                EncryptionPolicy = policy
            };

            var blob = contain.GetBlockBlobReference(blobName);

            using (var stream = formFile.OpenReadStream())
            {
                // Options object is containing all information about the
                await blob.UploadFromStreamAsync(stream, stream.Length, null, options, null);
            }
        }
        public FileStreamResult File(string filename)
        {
            var stockpickFormsAzurequeueConnectionstring = "Stockpick.Forms.AzureQueue.Connectionstring";
            var connectionstring = Sitecore.Configuration.Settings.GetSetting(stockpickFormsAzurequeueConnectionstring);

            Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionstring);

            var cloudBlobClient = storageAccount.CreateCloudBlobClient();
            var blobContainer   = cloudBlobClient.GetContainerReference("stockpickformsblob");

            blobContainer.CreateIfNotExists();

            var cloudResolver = new KeyVaultKeyResolver(Keyvault.GetToken);
            var url           = Sitecore.Configuration.Settings.GetSetting("Stockpick.Forms.KeyFault.Key.URL");

            if (string.IsNullOrEmpty(url))
            {
                Log.Error("config key Stockpick.Forms.KeyFault.Key.URL is emty", this);
            }
            var key = cloudResolver.ResolveKeyAsync(url, CancellationToken.None).GetAwaiter().GetResult();

            CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);


            BlobEncryptionPolicy policy  = new BlobEncryptionPolicy(null, cloudResolver);
            BlobRequestOptions   options = new BlobRequestOptions()
            {
                EncryptionPolicy = policy
            };

            Stream blobStream = blob.OpenRead(null, options);

            return(new FileStreamResult(blobStream, "application/x-binary"));
        }
        internal static T Decrypt <T>(string encryptedData, KeyVaultKeyResolver cloudResolver, string keyId)
        {
            CipherData cb = Deserialize <CipherData>(encryptedData);
            IKey       keyEncryptionKey = null;

            try
            {
                keyEncryptionKey = cloudResolver.ResolveKeyAsync(keyId, CancellationToken.None).GetAwaiter().GetResult();
                var currentKeyVersion = new Uri(keyEncryptionKey.Kid).Segments.Last();

                if (!currentKeyVersion.Equals(cb.KeyVersion))
                {
                    Console.WriteLine("Data encrypted with different key version: {0} vs {1}", currentKeyVersion, cb.KeyVersion);
                    // version doesn't match - go get the correct key version to unwrap with.
                    string newKey = keyId + "/" + cb.KeyVersion;
                    Console.WriteLine("Retrieving different key: " + newKey);
                    try
                    {
                        keyEncryptionKey = cloudResolver.ResolveKeyAsync(newKey, CancellationToken.None).GetAwaiter().GetResult();
                    }
                    catch (AggregateException ae)
                    {
                        Console.WriteLine("Cloudresolver could not retrieve key, version '" + cb.KeyVersion + "': " + ae.Message);
                        return(default(T));
                    }
                }

                // Unwrap Key using KeyVault
                byte[] aesKey = keyEncryptionKey.UnwrapKeyAsync(Convert.FromBase64String(cb.WrapedKey), cb.AlgorithmName, CancellationToken.None).GetAwaiter().GetResult();

                string plainJson = Decrypt(Convert.FromBase64String(cb.CipherText), aesKey);

                using (var streamReader = new StringReader(plainJson))
                {
                    JsonReader jreader = new JsonTextReader(streamReader);
                    return(new JsonSerializer().Deserialize <T>(jreader));
                }
            }
            finally
            {
                if (keyEncryptionKey != null)
                {
                    keyEncryptionKey.Dispose();
                }
            }
        }
Example #6
0
        private void VerifyResolver(KeyVaultClient client, string vault, string baseIdentifier, string identifier)
        {
            // ctor with client
            var resolver = new KeyVaultKeyResolver(client);

            var baseKey    = resolver.ResolveKeyAsync(baseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
            var versionKey = resolver.ResolveKeyAsync(identifier, default(CancellationToken)).GetAwaiter().GetResult();

            Assert.Equal(baseKey.Kid, versionKey.Kid);

            // NOTE: ctor with authentication callback. We cannot test this ctor unless
            //       we are running in live mode as it will create a new KeyVaultClient.
            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                resolver = new KeyVaultKeyResolver(fixture.GetAccessToken);

                baseKey    = resolver.ResolveKeyAsync(baseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                versionKey = resolver.ResolveKeyAsync(identifier, default(CancellationToken)).GetAwaiter().GetResult();

                Assert.Equal(baseKey.Kid, versionKey.Kid);
            }

            // ctor with vault name and client
            resolver = new KeyVaultKeyResolver(vault, client);

            baseKey    = resolver.ResolveKeyAsync(baseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
            versionKey = resolver.ResolveKeyAsync(identifier, default(CancellationToken)).GetAwaiter().GetResult();

            Assert.Equal(baseKey.Kid, versionKey.Kid);

            // NOTE: ctor with authentication callback. We cannot test this ctor unless
            //       we are running in live mode as it will create a new KeyVaultClient.
            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                resolver = new KeyVaultKeyResolver(vault, fixture.GetAccessToken);

                baseKey    = resolver.ResolveKeyAsync(baseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                versionKey = resolver.ResolveKeyAsync(identifier, default(CancellationToken)).GetAwaiter().GetResult();

                Assert.Equal(baseKey.Kid, versionKey.Kid);
            }

            baseKey.Dispose();
            versionKey.Dispose();
        }
        public async override Task ExecutePostProcessingAsync()
        {
            KeyVaultKeyResolver cloudResolver = new KeyVaultKeyResolver(ServerUtils.GetToken);
            IKey rsa = await cloudResolver.ResolveKeyAsync(ConfidentialData.KeyLocation, CancellationToken.None);

            foreach (var file in FileData)
            {
                string fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Trim('"'));
                var    blob     = _container.GetBlockBlobReference(Path.Combine(currentFilePath, fileName));

                BlobEncryptionPolicy policy  = new BlobEncryptionPolicy(rsa, null);
                BlobRequestOptions   options = new BlobRequestOptions()
                {
                    EncryptionPolicy = policy
                };

                using (var stream = File.OpenRead(file.LocalFileName))
                {
                    await blob.UploadFromStreamAsync(stream, stream.Length, null, options, null);
                }

                Urls.Add(blob.Uri.AbsoluteUri);

                string ext = Path.GetExtension(fileName);

                if (ext == ".jpeg" || ext == ".jpg")
                {
                    Image original = Image.FromFile(file.LocalFileName);
                    float ratio    = (float)original.Width / (float)original.Height;
                    SizeF newSize  = new SizeF(350 * ratio, 350);

                    Image thumb = original.GetThumbnailImage((int)newSize.Width, (int)newSize.Height, null, IntPtr.Zero);

                    string thumbName = Path.GetFileNameWithoutExtension(fileName) + "_thumb.jpg";

                    var thumbBlob = _container.GetBlockBlobReference(Path.Combine(currentFilePath, thumbName));

                    MemoryStream thumbStream = new MemoryStream();

                    thumb.Save(thumbStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    thumbStream.Position = 0;

                    await thumbBlob.UploadFromStreamAsync(thumbStream, thumbStream.Length, null, options, null);

                    Urls.Add(thumbBlob.Uri.AbsoluteUri);
                }

                try
                {
                    File.Delete(file.LocalFileName);
                }
                catch (Exception e)
                { }
            }
        }
Example #8
0
        private static async Task UploadAndDownloadBlobAsync(TenantInfo tenant)
        {
            var container = await GetBlobContainerAsync(tenant.ContainerName);

            var  cloudResolver = new KeyVaultKeyResolver(GetTokenAsync);
            IKey key           = await cloudResolver.ResolveKeyAsync(GetKeyUrl(tenant.KeyName), CancellationToken.None);

            CloudBlob blob = await UploadBlobAsync(container, key);

            await DownloadBlobAsync(blob, cloudResolver);
        }
        private async Task <BlobEncryptionPolicy> GetEncryptionPolicyForUpload(EncryptedBlobAttribute config, string keyName, CancellationToken cancellationToken)
        {
            var kid = await _keyVaultClient.GetKidByName(config, keyName, cancellationToken) ?? throw new ArgumentException(nameof(EncryptedBlobAttribute.KeyName));

            var keyResolver = new KeyVaultKeyResolver(_keyVaultClient);
            var key         = await keyResolver.ResolveKeyAsync(kid, cancellationToken);

            var blobEncryptionPolicy = new BlobEncryptionPolicy(key, null);

            return(blobEncryptionPolicy);
        }
Example #10
0
        public async Task <HttpResponseMessage> Get(string imageId, bool thumb = false)
        {
            int id;

            if (string.IsNullOrEmpty(imageId) || !Int32.TryParse(imageId, out id))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            ServiceData.Models.Photo found = _photoRepository.GetById(id);
            if (found == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            ServiceData.Models.UserCondition foundCond = _conditionRepository.GetById(found.UserCondition.Id);
            if (foundCond.Owner.Email != User.Identity.Name)
            {
                return(Request.CreateResponse(HttpStatusCode.Forbidden));
            }

            string target = (thumb) ? found.ThumbUrl : found.Url;

            CloudBlobContainer container = await GetBlobContainer();

            Stream    blobStream = new MemoryStream();
            CloudBlob photoBlob  = container.GetBlobReference(target.Replace(ConfidentialData.BlobStorageUrl, ""));

            KeyVaultKeyResolver cloudResolver = new KeyVaultKeyResolver(ServerUtils.GetToken);
            IKey rsa = await cloudResolver.ResolveKeyAsync(ConfidentialData.KeyLocation, CancellationToken.None);

            BlobEncryptionPolicy policy  = new BlobEncryptionPolicy(null, cloudResolver);
            BlobRequestOptions   options = new BlobRequestOptions()
            {
                EncryptionPolicy = policy
            };

            await photoBlob.DownloadToStreamAsync(blobStream, null, options, null);

            blobStream.Position = 0;

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new StreamContent(blobStream);
            response.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = imageId + Path.GetExtension(target);

            string eventName = thumb ? "DownloadThumb" : "DownloadImage";

            ServerUtils.LogTelemetryEvent(User.Identity.Name, eventName);

            return(response);
        }
        static void Main(string[] args)
        {
            // This is standard code to interact with Blob storage.
            StorageCredentials creds = new StorageCredentials(
                CloudConfigurationManager.GetSetting("accountName"),
                CloudConfigurationManager.GetSetting("accountKey"));
            CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
            CloudBlobClient     client  = account.CreateCloudBlobClient();
            CloudBlobContainer  contain = client.GetContainerReference(CloudConfigurationManager.GetSetting("container"));

            contain.CreateIfNotExists();

            // The Resolver object is used to interact with Key Vault for Azure Storage.
            // This is where the GetToken method from above is used.
            KeyVaultKeyResolver cloudResolver = new KeyVaultKeyResolver(GetToken);


            //Encrypt Blob and upload
            // Retrieve the key that you created previously.
            // The IKey that is returned here is an RsaKey.
            var rsa = cloudResolver.ResolveKeyAsync(
                "https://phupaa-vault.vault.azure.net/keys/key01",
                CancellationToken.None).GetAwaiter().GetResult();

            // Now you simply use the RSA key to encrypt by setting it in the BlobEncryptionPolicy.
            BlobEncryptionPolicy policy  = new BlobEncryptionPolicy(rsa, null);
            BlobRequestOptions   options = new BlobRequestOptions()
            {
                EncryptionPolicy = policy
            };

            // Reference a block blob.
            CloudBlockBlob blob = contain.GetBlockBlobReference("MyFile.txt");

            // Upload using the UploadFromStream method.
            using (var stream = System.IO.File.OpenRead(@"C:\Temp\MyFile.txt"))
                blob.UploadFromStream(stream, stream.Length, null, options, null);



            //Decrypt blob
            // In this case, we will not pass a key and only pass the resolver because
            // this policy will only be used for downloading / decrypting.
            BlobEncryptionPolicy policy2  = new BlobEncryptionPolicy(null, cloudResolver);
            BlobRequestOptions   options2 = new BlobRequestOptions()
            {
                EncryptionPolicy = policy
            };

            using (var np = File.Open(@"C:\temp\MyFileDecrypted.txt", FileMode.Create))
                blob.DownloadToStream(np, null, options, null);
        }
        internal static void DecryptFile(string cipherTextPath, string encryptedMetadata, string decryptedOutput, KeyVaultKeyResolver cloudResolver, string keyId)
        {
            // Make sure encrypted file exists.
            if (!File.Exists(cipherTextPath))
            {
                throw new FileNotFoundException("File not found.", cipherTextPath);
            }

            CipherData cb = Deserialize <CipherData>(encryptedMetadata);
            IKey       keyEncryptionKey = null;

            try
            {
                keyEncryptionKey = cloudResolver.ResolveKeyAsync(keyId, CancellationToken.None).GetAwaiter().GetResult();
                var currentKeyVersion = new Uri(keyEncryptionKey.Kid).Segments.Last();

                if (!currentKeyVersion.Equals(cb.KeyVersion))
                {
                    Console.WriteLine("Data encrypted with different key version: {0} vs {1}", currentKeyVersion, cb.KeyVersion);
                    // version doesn't match - go get the correct key version to unwrap with.
                    string newKey = keyId + "/" + cb.KeyVersion;
                    Console.WriteLine("Retrieving different key: " + newKey);
                    keyEncryptionKey = cloudResolver.ResolveKeyAsync(newKey, CancellationToken.None).GetAwaiter().GetResult();
                }

                // Unwrap Key using KeyVault
                byte[] aesKey = keyEncryptionKey.UnwrapKeyAsync(Convert.FromBase64String(cb.WrapedKey), cb.AlgorithmName, CancellationToken.None).GetAwaiter().GetResult();

                DecryptFile(cipherTextPath, decryptedOutput, aesKey);
            }
            finally
            {
                if (keyEncryptionKey != null)
                {
                    keyEncryptionKey.Dispose();
                }
            }
        }
Example #13
0
        public async Task <ActionResult> Download(string imageId, bool thumb = false)
        {
            int id;

            if (string.IsNullOrEmpty(imageId) || !Int32.TryParse(imageId, out id))
            {
                return(new HttpUnauthorizedResult());
            }

            IReadWriteRepository <ServiceData.Models.Photo>         _photoRepository = new PhotoRepository();
            IReadWriteRepository <ServiceData.Models.UserCondition> _condRepository  = new UserConditionsRepository();

            ServiceData.Models.Photo found = _photoRepository.GetById(id);
            if (found == null)
            {
                return(new HttpNotFoundResult());
            }

            ServiceData.Models.UserCondition foundCond = _condRepository.GetById(found.UserCondition.Id);
            if (!IsSharedOrOwned(foundCond))
            {
                return(new HttpUnauthorizedResult());
            }

            string target = (thumb) ? found.ThumbUrl : found.Url;

            CloudBlobContainer container = await UploadController.GetBlobContainer();

            Stream    blobStream = new MemoryStream();
            CloudBlob photoBlob  = container.GetBlobReference(target.Replace(ConfidentialData.BlobStorageUrl, ""));

            KeyVaultKeyResolver cloudResolver = new KeyVaultKeyResolver(ServerUtils.GetToken);
            IKey rsa = await cloudResolver.ResolveKeyAsync(ConfidentialData.KeyLocation, CancellationToken.None);

            BlobEncryptionPolicy policy  = new BlobEncryptionPolicy(null, cloudResolver);
            BlobRequestOptions   options = new BlobRequestOptions()
            {
                EncryptionPolicy = policy
            };

            await photoBlob.DownloadToStreamAsync(blobStream, null, options, null);

            blobStream.Position = 0;

            return(File(blobStream, "image/jpeg"));
        }
        // Encrypts an Object and retunrs a JSON object holding the encryption
        internal static string Encrypt(object o, KeyVaultKeyResolver cloudResolver, string keyId)
        {
            string jsonStringToEncrypt = Utils.Serialize(o);

            // Generate Client Encryption Key (CEK)
            using (var random = new RNGCryptoServiceProvider())
            {
                var aeskey = new byte[KEY_SIZE_BYTES];
                try
                {
                    // Generate an 256 bit AES Key
                    random.GetBytes(aeskey);

                    // Encrypt the plaintext
                    string cipherText = Convert.ToBase64String(Encrypt(jsonStringToEncrypt, aeskey));

                    Console.WriteLine("Retrieving key: " + keyId);
                    using (var keyEncryptionKey = cloudResolver.ResolveKeyAsync(keyId, CancellationToken.None).GetAwaiter().GetResult())
                    {
                        Console.WriteLine("Retrived key: " + keyEncryptionKey.Kid);
                        // Take the AES Key we Generated and Encrypt it using KeyVault to wrap it.
                        Tuple <byte[], string> wrappedKey = keyEncryptionKey.WrapKeyAsync(aeskey, null /* algorithm */, CancellationToken.None).GetAwaiter().GetResult();

                        string     keyVersion = new Uri(keyEncryptionKey.Kid).Segments.Last();
                        CipherData cb         = new CipherData {
                            AlgorithmName = wrappedKey.Item2, WrapedKey = Convert.ToBase64String(wrappedKey.Item1), CipherText = cipherText, KeyVersion = keyVersion
                        };

                        // TODO: Determine if the CipherData should contain a signature to prevent tampering.
                        // Need to enumerate the risks.

                        return(Utils.Serialize(cb));
                    }
                }
                finally
                {
                    // Clear out the key material from memory
                    Array.Clear(aeskey, 0, aeskey.Length);
                }
            }
        }
Example #15
0
        private void RetriveRSA(KeyVaultKeyResolver cloudResolver, CloudBlobContainer contain)
        {
            log.LogInformation($"validando chave externa de integração rsa");

            log.LogInformation("recebendo parametros [endpoint]");

            // Retrieve the key that you created previously.
            // The IKey that is returned here is an RsaKey.
            var rsa = cloudResolver.ResolveKeyAsync(app.Endpoint, CancellationToken.None)
                      .GetAwaiter().GetResult();

            log.LogInformation($"chave rsa gerada com sucesso");
            log.LogInformation($"algoritimo {rsa.DefaultEncryptionAlgorithm}");
            log.LogInformation($"hash {rsa.DefaultKeyWrapAlgorithm}");
            log.LogInformation($"assinatura {rsa.DefaultSignatureAlgorithm}");

            // Now you simply use the RSA key to encrypt by setting it in the BlobEncryptionPolicy.
            var policy  = new BlobEncryptionPolicy(rsa, null);
            var options = new BlobRequestOptions()
            {
                EncryptionPolicy = policy
            };

            log.LogInformation($"iniciando teste de upload no blob com autenticação segura");

            log.LogInformation($"validando referencia do blob para File.txt");

            // Reference a block blob.
            CloudBlockBlob blob = contain.GetBlockBlobReference("File.txt");

            log.LogInformation($"iniciando processo de upload");

            // Upload using the UploadFromStream method.
            using var stream = File.OpenRead(Directory.GetCurrentDirectory() + "\\File.txt");
            blob.UploadFromStream(stream, stream.Length, null, options, null);

            log.LogInformation($"valide se o arquivo File.txt é ");
        }
        private static async Task EncryptAndStore(CloudBlobContainer blobContainer, string text, string id)
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var client   = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            var resolver = new KeyVaultKeyResolver(client);

            var rsa = await resolver.ResolveKeyAsync(Environment.GetEnvironmentVariable("RsaVaultKey"), CancellationToken.None);

            var policy  = new BlobEncryptionPolicy(rsa, null);
            var options = new BlobRequestOptions()
            {
                EncryptionPolicy = policy
            };

            var blob = blobContainer.GetBlockBlobReference(id);

            var bytes = Encoding.UTF8.GetBytes(text);

            using (Stream stream = new MemoryStream(bytes))
            {
                await blob.UploadFromStreamAsync(stream, bytes.Length, null, options, null);
            }
        }
        private void StoreFiles(CloudStorageAccount storageAccount, FormSubmitContext formSubmitContext, IEnumerable <Guid> fileIds)
        {
            var cloudBlobClient = storageAccount.CreateCloudBlobClient();
            var blob            = cloudBlobClient.GetContainerReference("stockpickformsblob");

            blob.CreateIfNotExists();

            var cloudResolver = new KeyVaultKeyResolver(Keyvault.GetToken);
            var url           = Sitecore.Configuration.Settings.GetSetting("Stockpick.Forms.KeyFault.Key.URL");

            if (string.IsNullOrEmpty(url))
            {
                Log.Error("config key Stockpick.Forms.KeyFault.Key.URL is emty", this);
            }
            var key = cloudResolver.ResolveKeyAsync(url, CancellationToken.None).GetAwaiter().GetResult();

            foreach (var gui in fileIds)
            {
                var file = FileStorageProvider.GetFile(gui);
                if (file != null)
                {
                    Log.Info("Upload to Cloud storage file " + file.FileInfo.FileName + " as " + gui.ToString() + " using key kid:" + key.Kid, this);

                    BlobEncryptionPolicy policy  = new BlobEncryptionPolicy(key, null);
                    BlobRequestOptions   options = new BlobRequestOptions()
                    {
                        EncryptionPolicy = policy
                    };

                    CloudBlockBlob cloudBlockBlob = blob.GetBlockBlobReference(gui.ToString());
                    using (var filestream = file.File)
                    {
                        cloudBlockBlob.UploadFromStream(filestream, null, options, null);
                    }
                }
            }
        }
Example #18
0
        public async Task <string> UploadDocumentAsync(HttpPostedFileBase documentFile, Guid customerId, Guid documentId)
        {
            var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["DocumentStore"].ConnectionString);
            var blobClient     = storageAccount.CreateCloudBlobClient();

            var container = blobClient.GetContainerReference(customerId.ToString().ToLower());
            await container.CreateIfNotExistsAsync();

            var keyvaultResolver = new KeyVaultKeyResolver(GetToken);
            var key = await keyvaultResolver.ResolveKeyAsync(KEY_URI, CancellationToken.None);

            var encryptionPolicy = new BlobEncryptionPolicy(key, null);
            var requestOptions   = new BlobRequestOptions {
                EncryptionPolicy = encryptionPolicy
            };

            var blobRelativePath = documentId.ToString().ToLower() + "/" + Path.GetFileName(documentFile.FileName).ToLower();

            var block = container.GetBlockBlobReference(blobRelativePath);

            await block.UploadFromStreamAsync(documentFile.InputStream, documentFile.InputStream.Length, null, requestOptions, null);

            return(blobRelativePath);
        }
Example #19
0
        public async Task <IKey> ResolveKeyAsync(string kid, CancellationToken token)
        {
            var key = await _resolver.ResolveKeyAsync(kid, token);

            return(key);
        }
        public void KeyVault_KeyResolver_ResolveKey()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                // Arrange
                var client = GetKeyVaultClient();
                var vault  = _vaultAddress;

                var key = client.CreateKeyAsync(vault, "TestKey", JsonWebKeyType.Rsa).GetAwaiter().GetResult();

                if (key != null)
                {
                    try
                    {
                        // ctor with client
                        var resolver = new KeyVaultKeyResolver(client);

                        var baseKey    = resolver.ResolveKeyAsync(key.KeyIdentifier.BaseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                        var versionKey = resolver.ResolveKeyAsync(key.KeyIdentifier.Identifier, default(CancellationToken)).GetAwaiter().GetResult();

                        Assert.Equal(baseKey.Kid, versionKey.Kid);

                        // NOTE: ctor with authentication callback. We cannot test this ctor unless
                        //       we are running in live mode as it will create a new KeyVaultClient.
                        if (HttpMockServer.Mode == HttpRecorderMode.Record)
                        {
                            resolver = new KeyVaultKeyResolver(GetAccessToken);

                            baseKey    = resolver.ResolveKeyAsync(key.KeyIdentifier.BaseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                            versionKey = resolver.ResolveKeyAsync(key.KeyIdentifier.Identifier, default(CancellationToken)).GetAwaiter().GetResult();

                            Assert.Equal(baseKey.Kid, versionKey.Kid);
                        }

                        // ctor with vault name and client
                        resolver = new KeyVaultKeyResolver(vault, client);

                        baseKey    = resolver.ResolveKeyAsync(key.KeyIdentifier.BaseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                        versionKey = resolver.ResolveKeyAsync(key.KeyIdentifier.Identifier, default(CancellationToken)).GetAwaiter().GetResult();

                        Assert.Equal(baseKey.Kid, versionKey.Kid);

                        // NOTE: ctor with authentication callback. We cannot test this ctor unless
                        //       we are running in live mode as it will create a new KeyVaultClient.
                        if (HttpMockServer.Mode == HttpRecorderMode.Record)
                        {
                            resolver = new KeyVaultKeyResolver(vault, GetAccessToken);

                            baseKey    = resolver.ResolveKeyAsync(key.KeyIdentifier.BaseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                            versionKey = resolver.ResolveKeyAsync(key.KeyIdentifier.Identifier, default(CancellationToken)).GetAwaiter().GetResult();

                            Assert.Equal(baseKey.Kid, versionKey.Kid);
                        }
                    }
                    finally
                    {
                        // Delete the key
                        client.DeleteKeyAsync(vault, "TestKey").GetAwaiter().GetResult();
                    }
                }
            }
        }
        public void KeyVault_KeyResolver_ResolveSecret256Base64()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                // Arrange
                var client = GetKeyVaultClient();
                var vault  = _vaultAddress;

                var keyBytes = new byte[256 >> 3];

                new RNGCryptoServiceProvider().GetNonZeroBytes(keyBytes);

                var secret = client.SetSecretAsync(vault, "TestSecret", Convert.ToBase64String(keyBytes), null, "application/octet-stream").GetAwaiter().GetResult();

                if (secret != null)
                {
                    try
                    {
                        // ctor with client
                        var resolver = new KeyVaultKeyResolver(client);

                        var baseKey    = resolver.ResolveKeyAsync(secret.SecretIdentifier.BaseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                        var versionKey = resolver.ResolveKeyAsync(secret.SecretIdentifier.Identifier, default(CancellationToken)).GetAwaiter().GetResult();

                        Assert.Equal(baseKey.Kid, versionKey.Kid);

                        // NOTE: ctor with authentication callback. We cannot test this ctor unless
                        //       we are running in live mode as it will create a new KeyVaultClient.
                        if (HttpMockServer.Mode == HttpRecorderMode.Record)
                        {
                            resolver = new KeyVaultKeyResolver(GetAccessToken);

                            baseKey    = resolver.ResolveKeyAsync(secret.SecretIdentifier.BaseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                            versionKey = resolver.ResolveKeyAsync(secret.SecretIdentifier.Identifier, default(CancellationToken)).GetAwaiter().GetResult();

                            Assert.Equal(baseKey.Kid, versionKey.Kid);
                        }

                        // ctor with vault name and client
                        resolver = new KeyVaultKeyResolver(vault, client);

                        baseKey    = resolver.ResolveKeyAsync(secret.SecretIdentifier.BaseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                        versionKey = resolver.ResolveKeyAsync(secret.SecretIdentifier.Identifier, default(CancellationToken)).GetAwaiter().GetResult();

                        Assert.Equal(baseKey.Kid, versionKey.Kid);

                        // NOTE: ctor with authentication callback. We cannot test this ctor unless
                        //       we are running in live mode as it will create a new KeyVaultClient.
                        if (HttpMockServer.Mode == HttpRecorderMode.Record)
                        {
                            resolver = new KeyVaultKeyResolver(vault, GetAccessToken);

                            baseKey    = resolver.ResolveKeyAsync(secret.SecretIdentifier.BaseIdentifier, default(CancellationToken)).GetAwaiter().GetResult();
                            versionKey = resolver.ResolveKeyAsync(secret.SecretIdentifier.Identifier, default(CancellationToken)).GetAwaiter().GetResult();

                            Assert.Equal(baseKey.Kid, versionKey.Kid);
                        }
                    }
                    finally
                    {
                        // Delete the key
                        client.DeleteSecretAsync(vault, "TestSecret").GetAwaiter().GetResult();
                    }
                }
            }
        }
Example #22
0
        static void Main(string[] args)
        {
            /* OVERVIEW OF HOW THIS WORKS :
             * The Azure Storage client SDK generates a content encryption key(CEK), which is a
             * one - time - use symmetric key. Customer data is encrypted using this CEK.
             * The CEK is then wrapped (encrypted) using the key encryption key(KEK).
             * The KEK is identified by a key identifier and can be managed locally or stored in Azure Key
             * Vault.
             * The Storage client itself never has access to the KEK. It just invokes the key wrapping
             * algorithm that is provided by Key Vault.
             * The encrypted data is then uploaded to the Azure Storage service.
             *
             * Decryption is really when using the Resolver classes make sense.
             * The ID of the key used for encryption is associated with the blob in its metadata, so there
             * is no reason for you to retrieve the key and remember the
             * association between key and blob.You just have to make sure that the key remains in Key Vault.
             * The private key of an RSA Key remains in Key Vault, so for decryption to occur, the Encrypted
             * Key from the blob metadata that contains the CEK is sent to
             * Key Vault for decryption.*/

            Console.WriteLine("Azure Key Vault Demo : Encryption and decryption of a file.");
            Console.WriteLine("Please enter storage account NAME :");
            var accountN = Console.ReadLine();

            Console.WriteLine("Please enter storage account KEY :");
            var accountK = Console.ReadLine();

            // This is standard code to interact with Blob storage.
            StorageCredentials creds = new StorageCredentials(
                accountN, accountK);
            CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
            CloudBlobClient     client  = account.CreateCloudBlobClient();
            CloudBlobContainer  contain = client.GetContainerReference(ConfigurationManager.AppSettings["container"]);

            contain.CreateIfNotExists();

            // The Resolver object is used to interact with Key Vault for Azure Storage.
            // This is where the GetToken method from above is used.
            KeyVaultKeyResolver cloudResolver = new KeyVaultKeyResolver(GetToken);


            // Retrieve the key that you created previously.
            // The IKey that is returned here is an RsaKey.
            //
            Console.WriteLine("Please enter URL of key, for example : https://myKeyVault.vault.azure.net/keys/MyKeyDemo");
            var kv  = Console.ReadLine();
            var rsa = cloudResolver.ResolveKeyAsync(kv, CancellationToken.None).GetAwaiter().GetResult();

            // Now you simply use the RSA key to encrypt by setting it in the BlobEncryptionPolicy.
            BlobEncryptionPolicy policy  = new BlobEncryptionPolicy(rsa, null);
            BlobRequestOptions   options = new BlobRequestOptions()
            {
                EncryptionPolicy = policy
            };

            // Reference a block blob.
            CloudBlockBlob blob = contain.GetBlockBlobReference("MyFile.txt");

            // Upload using the UploadFromStream method.
            Console.WriteLine("Ensure MyFile.txt is placed in the temp directory.");
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();

            using (var stream = System.IO.File.OpenRead(@"C:\temp\MyFile.txt"))
                blob.UploadFromStream(stream, stream.Length, null, options, null);

            Console.WriteLine("File encrypted and uploaded....");
            Console.WriteLine("Now use Storage Explorer or portal to retrive the encrypted file from the storage account and view it.");
            Console.WriteLine("Press ANY Key to continue...");
            Console.ReadLine();

            Console.WriteLine("Now let's retrieve and decrypt...");
            // In this case, we will not pass a key and only pass the resolver because
            // this policy will only be used for downloading / decrypting.
            BlobEncryptionPolicy policydecrypt  = new BlobEncryptionPolicy(null, cloudResolver);
            BlobRequestOptions   optionsdecrypt = new BlobRequestOptions()
            {
                EncryptionPolicy = policydecrypt
            };


            using (var np = File.Open(@"C:\temp\MyFileDecrypted.txt", FileMode.Create))
                blob.DownloadToStream(np, null, options, null);

            Console.WriteLine("File Downloaded and decrypted as MyFileDecrypted.txt into the temp directory. Check it out!");
            Console.WriteLine("Press ANY Key to continue...");
            Console.ReadLine();
        }
Example #23
0
 //uses a resolver object to retrieve a keyvault key
 public Microsoft.Azure.KeyVault.Core.IKey GetKey(KeyVaultKeyResolver Resolver)
 {
     return(Resolver.ResolveKeyAsync("https://fvdemokeyvault.vault.azure.net/keys/FileVaultKey", CancellationToken.None).GetAwaiter().GetResult());
 }
Example #24
0
        public async Task <HttpResponseMessage> Get()
        {
            try
            {
                string[] testUsers = new string[]
                {
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                };

                string baseFileLoc = "C:/Users/tgs03_000/Downloads/SkinSelfies";

                //if (Directory.Exists(baseFileLoc))
                //{
                //    Directory.Delete(baseFileLoc, true);
                //}

                if (!Directory.Exists(baseFileLoc))
                {
                    Directory.CreateDirectory(baseFileLoc);
                }

                List <Task>   allTasks   = new List <Task>();
                List <string> nullEmails = new List <string>();

                foreach (string userEmail in testUsers)
                {
                    ServiceData.Models.User user = _userRepository.Search(u => u.Email == userEmail).FirstOrDefault();

                    DirectoryInfo userDir = Directory.CreateDirectory(Path.Combine(baseFileLoc, userEmail));

                    if (user == null)
                    {
                        nullEmails.Add(userEmail);
                        continue;
                    }

                    AboutUser userDetails = new AboutUser
                    {
                        Id    = user.Id,
                        Email = user.Email,
                        Name  = user.Name,
                        Dob   = user.BirthDate
                    };

                    File.WriteAllText(Path.Combine(userDir.FullName, "AboutUser.txt"), JsonConvert.SerializeObject(userDetails, Formatting.Indented));

                    foreach (ServiceData.Models.UserCondition cond in user.Conditions)
                    {
                        ServiceData.Models.UserCondition fullCond = _conditionRepository.GetById(cond.Id);

                        string condPath = Path.Combine(userDir.FullName, cond.Id.ToString());

                        DirectoryInfo condDir = Directory.Exists(condPath)? new DirectoryInfo(condPath) : Directory.CreateDirectory(condPath);

                        AboutCondition condDetails = new AboutCondition
                        {
                            Id         = user.Id,
                            Name       = cond.Condition,
                            SkinRegion = fullCond.SkinRegion.BodyPart.Name + " - " + fullCond.SkinRegion.Name,
                            StartDate  = cond.StartDate,
                            NumPhotos  = fullCond.Photos.Count()
                        };

                        File.WriteAllText(Path.Combine(condDir.FullName, "AboutCondition.txt"), JsonConvert.SerializeObject(condDetails, Formatting.Indented));

                        foreach (ServiceData.Models.Photo photo in fullCond.Photos)
                        {
                            string filename = Path.Combine(condDir.FullName, photo.CreatedAt.ToString("yyyy-MM-dd-HH-mm-ss.") + Path.GetExtension(photo.Url));

                            if (File.Exists(filename))
                            {
                                continue;
                            }

                            CloudBlobContainer container = await GetBlobContainer();

                            Stream    blobStream = new MemoryStream();
                            CloudBlob photoBlob  = container.GetBlobReference(photo.Url.Replace(ConfidentialData.BlobStorageUrl, ""));

                            KeyVaultKeyResolver cloudResolver = new KeyVaultKeyResolver(ServerUtils.GetToken);
                            IKey rsa = await cloudResolver.ResolveKeyAsync(ConfidentialData.KeyLocation, CancellationToken.None);

                            BlobEncryptionPolicy policy  = new BlobEncryptionPolicy(null, cloudResolver);
                            BlobRequestOptions   options = new BlobRequestOptions()
                            {
                                EncryptionPolicy = policy
                            };

                            await photoBlob.DownloadToStreamAsync(blobStream, null, options, null);

                            blobStream.Position = 0;

                            using (var fileStream = File.Create(filename))
                            {
                                await blobStream.CopyToAsync(fileStream);
                            }
                        }
                    }
                }

                string nullString = "";

                foreach (string nEmail in nullEmails)
                {
                    nullString += nEmail + ", ";
                }

                return(Request.CreateResponse(HttpStatusCode.OK, "Files located at " + baseFileLoc + " Null emails: " + nullString));
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }