Ejemplo n.º 1
0
        private static string DecryptedFile(IIngestManifestFile ingestManifestFile, string encryptedPath, CloudMediaContext context)
        {
            IIngestManifestAsset ingestManifestAsset = context.IngestManifestAssets.Where(a => a.Id == ingestManifestFile.ParentIngestManifestAssetId).FirstOrDefault();

            Assert.IsNotNull(ingestManifestAsset);

            IList <IContentKey> keys = ingestManifestAsset.Asset.ContentKeys.Where(c => c.ContentKeyType == ContentKeyType.StorageEncryption).ToList();

            Assert.AreEqual(1, keys.Count, "Expecting only one storage key per asset");
            IContentKey key = keys.FirstOrDefault();

            Assert.IsNotNull(ingestManifestAsset);


            Guid           keyId          = EncryptionUtils.GetKeyIdAsGuid(key.Id);
            FileEncryption fileEncryption = new FileEncryption(key.GetClearKeyValue(), keyId);

            ulong iv            = Convert.ToUInt64(ingestManifestFile.InitializationVector, CultureInfo.InvariantCulture);
            var   decryptedPath = @".\Resources\TestFiles\Decrypted" + Guid.NewGuid();

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

            decryptedPath = Path.Combine(decryptedPath, ingestManifestFile.Name);
            FileInfo      fileInfo        = new FileInfo(encryptedPath);
            var           maxblocksize    = GetBlockSize(fileInfo.Length);
            List <string> blockList       = new List <string>();
            int           numberOfthreads = 1;
            var           queue           = PreapreDownloadQueue(maxblocksize, fileInfo.Length, ref numberOfthreads, out blockList);

            using (var fs = new FileStream(decryptedPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
            {
                KeyValuePair <int, int> block;
                while (queue.TryDequeue(out block))
                {
                    fs.Seek(block.Key * maxblocksize, SeekOrigin.Begin);
                    using (FileStream stream = File.OpenRead(encryptedPath))
                    {
                        byte[] buffer = new byte[block.Value];
                        stream.Seek(block.Key * maxblocksize, SeekOrigin.Begin);
                        int read = stream.Read(buffer, 0, (int)block.Value);
                        if (fileEncryption != null)
                        {
                            lock (fileEncryption)
                            {
                                using (FileEncryptionTransform encryptor = fileEncryption.GetTransform(iv, block.Key * maxblocksize))
                                {
                                    encryptor.TransformBlock(inputBuffer: buffer, inputOffset: 0, inputCount: buffer.Length, outputBuffer: buffer, outputOffset: 0);
                                }
                            }
                        }

                        fs.Write(buffer, 0, buffer.Length);
                    }
                }
            }
            return(decryptedPath);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Uploads the destinationPath with given path asynchronously
        /// </summary>
        /// <param name="path">The path of a destinationPath to upload</param>
        /// <param name="blobTransferClient">The <see cref="BlobTransferClient"/> which is used to upload files.</param>
        /// <param name="locator">An asset <see cref="ILocator"/> which defines permissions associated with the Asset.</param>
        /// <param name="token">A <see cref="CancellationToken"/> to use for canceling upload operation.</param>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task UploadAsync(string path, BlobTransferClient blobTransferClient, ILocator locator, CancellationToken token)
        {
            if (blobTransferClient == null)
            {
                throw new ArgumentNullException("blobTransferClient");
            }

            if (locator == null)
            {
                throw new ArgumentNullException("locator");
            }

            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            ValidateFileName(path);

            IContentKey          contentKeyData       = null;
            FileEncryption       fileEncryption       = null;
            AssetCreationOptions assetCreationOptions = this.Asset.Options;

            if (assetCreationOptions.HasFlag(AssetCreationOptions.StorageEncrypted))
            {
                contentKeyData = this.Asset.ContentKeys.Where(c => c.ContentKeyType == ContentKeyType.StorageEncryption).FirstOrDefault();
                if (contentKeyData == null)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, StringTable.StorageEncryptionContentKeyIsMissing, this.Asset.Id));
                }

                fileEncryption = new FileEncryption(contentKeyData.GetClearKeyValue(), EncryptionUtils.GetKeyIdAsGuid(contentKeyData.Id));
            }

            EventHandler <BlobTransferProgressChangedEventArgs> handler = (s, e) => OnUploadProgressChanged(path, e);

            blobTransferClient.TransferProgressChanged += handler;

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetBlobStorageClientRetryPolicy();

            return(blobTransferClient.UploadBlob(
                       new Uri(locator.BaseUri),
                       path,
                       null,
                       fileEncryption,
                       token,
                       retryPolicy.AsAzureStorageClientRetryPolicy(),
                       () => locator.ContentAccessComponent)
                   .ContinueWith(
                       ts =>
            {
                blobTransferClient.TransferProgressChanged -= handler;
                this.PostUploadAction(ts, path, fileEncryption, assetCreationOptions, token);
            }));
        }
Ejemplo n.º 3
0
        private FileEncryption GetFileEncryption()
        {
            if (!this.IsEncrypted)
            {
                return(null);
            }

            // We want to support downloading PlayReady encrypted content too.
            if (this.EncryptionScheme != FileEncryption.SchemeName)
            {
                return(null);
            }

            IContentKey key   = this.Asset.ContentKeys.Where(c => c.ContentKeyType == ContentKeyType.StorageEncryption).FirstOrDefault();
            Guid        keyId = EncryptionUtils.GetKeyIdAsGuid(key.Id);

            return(new FileEncryption(key.GetClearKeyValue(), keyId));
        }
        static void Main(string[] args)
        {
            AzureAdTokenCredentials tokenCredentials =
                new AzureAdTokenCredentials(_AADTenantDomain,
                                            new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret),
                                            AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);

            bool   tokenRestriction    = true;
            string tokenTemplateString = null;

            IContentKey key = CreateCommonTypeContentKey();

            // Print out the key ID and Key in base64 string format
            Console.WriteLine("Created key {0} with key value {1} ",
                              key.Id, System.Convert.ToBase64String(key.GetClearKeyValue()));

            Console.WriteLine("PlayReady License Key delivery URL: {0}",
                              key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense));

            Console.WriteLine("Widevine License Key delivery URL: {0}",
                              key.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine));

            if (tokenRestriction)
            {
                tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key);
            }
            else
            {
                AddOpenAuthorizationPolicy(key);
            }

            Console.WriteLine("Added authorization policy: {0}",
                              key.AuthorizationPolicyId);
            Console.WriteLine();
            Console.ReadLine();
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            // Create and cache the Media Services credentials in a static class variable.
            _cachedCredentials = new MediaServicesCredentials(
                _mediaServicesAccountName,
                _mediaServicesAccountKey);
            // Used the cached credentials to create CloudMediaContext.
            _context = new CloudMediaContext(_cachedCredentials);

            bool   tokenRestriction    = true;
            string tokenTemplateString = null;


            IContentKey key = CreateCommonTypeContentKey();

            // Print out the key ID and Key in base64 string format
            Console.WriteLine("Created key {0} with key value {1} ",
                              key.Id, System.Convert.ToBase64String(key.GetClearKeyValue()));

            Console.WriteLine("PlayReady License Key delivery URL: {0}",
                              key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense));

            Console.WriteLine("Widevine License Key delivery URL: {0}",
                              key.GetKeyDeliveryUrl(ContentKeyDeliveryType.Widevine));

            if (tokenRestriction)
            {
                tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key);
            }
            else
            {
                AddOpenAuthorizationPolicy(key);
            }

            Console.WriteLine("Added authorization policy: {0}",
                              key.AuthorizationPolicyId);
            Console.WriteLine();
            Console.ReadLine();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Decrypts the configuration string.
        /// </summary>
        /// <param name="cloudMediaContext">The cloud media context.</param>
        /// <param name="encryptionKeyId">The encryption key id.</param>
        /// <param name="initializationVector">The initialization vector.</param>
        /// <param name="encryptedConfiguration">The encrypted configuration.</param>
        /// <returns>The decrypted configuration.</returns>
        internal static string DecryptConfigurationString(CloudMediaContext cloudMediaContext, string encryptionKeyId, string initializationVector, string encryptedConfiguration)
        {
            if (cloudMediaContext == null)
            {
                throw new ArgumentNullException("cloudMediaContext");
            }

            if (string.IsNullOrEmpty(encryptionKeyId))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, StringTable.ErrorArgCannotBeNullOrEmpty, "encryption key identifier"), "encryptionKeyId");
            }

            if (string.IsNullOrEmpty(initializationVector))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, StringTable.ErrorArgCannotBeNullOrEmpty, "initialization vector"), "initializationVector");
            }

            if (string.IsNullOrEmpty(encryptedConfiguration))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, StringTable.ErrorArgCannotBeNullOrEmpty, "encrypted configuration"), "encryptedConfiguration");
            }

            string returnValue;
            Guid   keyId = EncryptionUtils.GetKeyIdAsGuid(encryptionKeyId);

            byte[] iv = Convert.FromBase64String(initializationVector);

            IContentKey configKey = cloudMediaContext.ContentKeys.Where(c => c.Id == encryptionKeyId).Single();

            byte[] contentKey = configKey.GetClearKeyValue();

            using (ConfigurationEncryption configEnc = new ConfigurationEncryption(keyId, contentKey, iv))
            {
                returnValue = configEnc.Decrypt(encryptedConfiguration);
            }

            return(returnValue);
        }
Ejemplo n.º 7
0
        public override Task <IAssetFile> CreateAsync(string name, CancellationToken cancelation)
        {
            if (_parentAsset == null)
            {
                throw new InvalidOperationException(StringTable.AssetFileCreateParentAssetIsNull);
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, StringTable.ErrorCreatingAssetFileEmptyFileName));
            }

            cancelation.ThrowIfCancellationRequested();
            IMediaDataServiceContext dataContext = null;
            AssetFileData            assetFile   = null;

            return(Task.Factory.StartNew(() =>
            {
                cancelation.ThrowIfCancellationRequested();
                dataContext = MediaContext.MediaServicesClassFactory.CreateDataServiceContext();

                FileEncryption fileEncryption = null;

                // Set a MIME type based on the extension of the file name
                string mimeType = AssetFileData.GetMimeType(name);
                assetFile = new AssetFileData
                {
                    Name = name,
                    ParentAssetId = _parentAsset.Id,
                    MimeType = mimeType,
                };
                try
                {
                    // Update the files associated with the asset with the encryption related metadata.
                    if (_parentAsset.Options.HasFlag(AssetCreationOptions.StorageEncrypted))
                    {
                        IContentKey storageEncryptionKey = _parentAsset.ContentKeys.Where(c => c.ContentKeyType == ContentKeyType.StorageEncryption).FirstOrDefault();
                        cancelation.ThrowIfCancellationRequested();
                        if (storageEncryptionKey == null)
                        {
                            throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, StringTable.StorageEncryptionContentKeyIsMissing, _parentAsset.Id));
                        }
                        fileEncryption = new FileEncryption(storageEncryptionKey.GetClearKeyValue(), EncryptionUtils.GetKeyIdAsGuid(storageEncryptionKey.Id));
                        AssetBaseCollection.AddEncryptionMetadataToAssetFile(assetFile, fileEncryption);
                    }
                    else if (_parentAsset.Options.HasFlag(AssetCreationOptions.CommonEncryptionProtected))
                    {
                        AssetBaseCollection.SetAssetFileForCommonEncryption(assetFile);
                    }
                    else if (_parentAsset.Options.HasFlag(AssetCreationOptions.EnvelopeEncryptionProtected))
                    {
                        AssetBaseCollection.SetAssetFileForEnvelopeEncryption(assetFile);
                    }
                }
                finally
                {
                    if (fileEncryption != null)
                    {
                        fileEncryption.Dispose();
                    }
                }
                dataContext.AddObject(FileSet, assetFile);
                cancelation.ThrowIfCancellationRequested();
                cancelation.ThrowIfCancellationRequested();
                MediaRetryPolicy retryPolicy = this.MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);
                return retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() =>
                {
                    cancelation.ThrowIfCancellationRequested();
                    return dataContext.SaveChangesAsync(assetFile);
                }, cancelation).Result;
            }, cancelation)
                   .ContinueWith <IAssetFile>(t =>
            {
                t.ThrowIfFaulted();
                AssetFileData data = (AssetFileData)t.Result.AsyncState;
                return data;
            }, cancelation));
        }
        private void AssetEncryptAction(string outputPath, bool overwriteExistingEncryptedFiles, CancellationToken cancellationToken, ConcurrentDictionary <string, IContentKey> keys, IIngestManifestAsset asset)
        {
            cancellationToken.ThrowIfCancellationRequested();

            List <Task> encryptTasks = new List <Task>();

            AssetCreationOptions assetCreationOptions = asset.Asset.Options;

            if (assetCreationOptions.HasFlag(AssetCreationOptions.StorageEncrypted))
            {
                IContentKey contentKeyData = keys[asset.Id];
                var         fileEncryption = new FileEncryption(contentKeyData.GetClearKeyValue(), EncryptionUtils.GetKeyIdAsGuid(contentKeyData.Id));


                foreach (IngestManifestFileData file in asset.IngestManifestFiles)
                {
                    ulong iv = Convert.ToUInt64(file.InitializationVector, CultureInfo.InvariantCulture);
                    fileEncryption.SetInitializationVectorForFile(file.Name, iv);

                    FileInfo fileInfo = null;
                    fileInfo = TrackedFilesPaths.ContainsKey(file.Id) ? new FileInfo(TrackedFilesPaths[file.Id]) : new FileInfo(file.Name);

                    string destinationPath = Path.Combine(outputPath, fileInfo.Name);
                    if (File.Exists(destinationPath))
                    {
                        if (overwriteExistingEncryptedFiles)
                        {
                            File.Delete(destinationPath);
                        }
                        else
                        {
                            throw new IOException(string.Format(CultureInfo.InvariantCulture, StringTable.BulkIngestFileExists, destinationPath));
                        }
                    }

                    long fileSize     = fileInfo.Length;
                    int  maxBlockSize = GetBlockSize(fileSize);

                    int numThreads = MaxNumberOfEncryptionThreadsForFilePerCore * Environment.ProcessorCount;
                    ConcurrentQueue <Tuple <int, int> > queue = PrepareUploadQueue(maxBlockSize, fileSize);
                    if (queue.Count < numThreads)
                    {
                        numThreads = queue.Count;
                    }


                    File.Create(destinationPath).Dispose();

                    Action action = GetEncryptionAction(cancellationToken, fileEncryption, file, destinationPath, fileInfo, queue, maxBlockSize);
                    for (int i = 0; i < numThreads; i++)
                    {
                        encryptTasks.Add(Task.Factory.StartNew((action), cancellationToken));
                    }
                }
                try
                {
                    Task.WaitAll(encryptTasks.ToArray());
                }
                finally
                {
                    fileEncryption.Dispose();
                }
            }
        }
        /// <summary>
        /// Uploads the stream asynchronously
        /// </summary>
        /// <param name="stream">The stream to upload</param>
        /// <param name="blobTransferClient">The <see cref="BlobTransferClient"/> which is used to upload files.</param>
        /// <param name="locator">An locator <see cref="ILocator"/> which defines permissions associated with the Asset.</param>
        /// <param name="token">A <see cref="CancellationToken"/> to use for canceling upload operation.</param>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task UploadAsync(Stream stream, BlobTransferClient blobTransferClient, ILocator locator, CancellationToken token)
        {
            if (this.IsFragmented())
            {
                throw new NotSupportedException(StringTable.NotSupportedFragblobUpload);
            }

            if (blobTransferClient == null)
            {
                throw new ArgumentNullException("blobTransferClient");
            }

            if (locator == null)
            {
                throw new ArgumentNullException("locator");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            IContentKey          contentKeyData       = null;
            FileEncryption       fileEncryption       = null;
            AssetCreationOptions assetCreationOptions = this.Asset.Options;

            if (assetCreationOptions.HasFlag(AssetCreationOptions.StorageEncrypted))
            {
                contentKeyData = this.Asset.ContentKeys.FirstOrDefault(c => c.ContentKeyType == ContentKeyType.StorageEncryption);
                if (contentKeyData == null)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, StringTable.StorageEncryptionContentKeyIsMissing, this.Asset.Id));
                }

                fileEncryption = new FileEncryption(contentKeyData.GetClearKeyValue(), EncryptionUtils.GetKeyIdAsGuid(contentKeyData.Id));
                ulong iv = Convert.ToUInt64(this.InitializationVector, CultureInfo.InvariantCulture);
                fileEncryption.SetInitializationVectorForFile(this.Name, iv);
            }

            EventHandler <BlobTransferProgressChangedEventArgs> handler = (s, e) => OnUploadProgressChanged(this.Name, e);

            blobTransferClient.TransferProgressChanged += handler;

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetBlobStorageClientRetryPolicy();

            var streamLength = stream.Length;

            return(blobTransferClient.UploadBlob(
                       new Uri(locator.BaseUri),
                       this.Name,
                       stream,
                       null,
                       fileEncryption,
                       token,
                       retryPolicy.AsAzureStorageClientRetryPolicy(),
                       () => locator.ContentAccessComponent)
                   .ContinueWith(
                       ts =>
            {
                blobTransferClient.TransferProgressChanged -= handler;
                this.PostUploadAction(ts, streamLength, token);
            }));
        }