SerializeCert() public static method

Returns serialized certificate - Base64 encoded based on the content type
public static SerializeCert ( X509Certificate2 cert, X509ContentType contentType ) : string
cert System.Security.Cryptography.X509Certificates.X509Certificate2 The certificate provided
contentType X509ContentType Cert content type
return string
Esempio n. 1
0
 /// <summary>
 /// Generates vault creds file
 /// </summary>
 /// <param name="cert">management certificate</param>
 /// <param name="subscriptionId">subscription Id</param>
 /// <param name="acsNamespace">acs namespace</param>
 /// <returns>xml file in string format</returns>
 private string GenerateVaultCreds(X509Certificate2 cert, string subscriptionId, VaultCertificateResponse vaultCertificateResponse)
 {
     try
     {
         var certString = CertUtils.SerializeCert(cert, X509ContentType.Pfx);
         return(GenerateVaultCredsForBackup(certString, subscriptionId, vaultCertificateResponse));
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
        /// <summary>
        /// Generates vault creds file content for backup Vault
        /// </summary>
        /// <param name="cert">management certificate</param>
        /// <param name="subscriptionId">subscription Id</param>
        /// <param name="acsNamespace">acs namespace</param>
        /// <returns>xml file in string format</returns>
        private string GenerateVaultCredsForBackup(X509Certificate2 cert, string subscriptionId,
                                                   AcsNamespace acsNamespace)
        {
            using (var output = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(output, GetXmlWriterSettings()))
                {
                    BackupVaultCreds backupVaultCreds =
                        new BackupVaultCreds(subscriptionId,
                                             this.Vault.Name,
                                             CertUtils.SerializeCert(cert, X509ContentType.Pfx),
                                             acsNamespace,
                                             GetAgentLinks());
                    DataContractSerializer serializer = new DataContractSerializer(typeof(BackupVaultCreds));
                    serializer.WriteObject(writer, backupVaultCreds);

                    WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.BackupVaultSerialized));
                }

                return(Encoding.UTF8.GetString(output.ToArray()));
            }
        }
        /// <summary>
        /// Generates vault creds file content for backup Vault
        /// </summary>
        /// <param name="cert">management certificate</param>
        /// <param name="subscriptionId">subscription Id</param>
        /// <param name="acsNamespace">acs namespace</param>
        /// <returns>xml file in string format</returns>
        private string GenerateVaultCredsForBackup(X509Certificate2 cert, string subscriptionId,
                                                   VaultCertificateResponse vaultCertificateResponse)
        {
            using (var output = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(output, GetXmlWriterSettings()))
                {
                    ResourceCertificateAndAadDetails aadDetails = vaultCertificateResponse.Properties as ResourceCertificateAndAadDetails;

                    RSBackupVaultAADCreds vaultCreds = new RSBackupVaultAADCreds()
                    {
                        SubscriptionId           = subscriptionId,
                        ResourceName             = Vault.Name,
                        ManagementCert           = CertUtils.SerializeCert(cert, X509ContentType.Pfx),
                        ResourceId               = aadDetails.ResourceId.Value,
                        AadAuthority             = aadDetails.AadAuthority,
                        AadTenantId              = aadDetails.AadTenantId,
                        ServicePrincipalClientId = aadDetails.ServicePrincipalClientId,
                        IdMgmtRestEndpoint       = aadDetails.AzureManagementEndpointAudience,
                        ProviderNamespace        = PSRecoveryServicesClient.ProductionRpNamespace,
                        ResourceGroup            = Vault.ResourceGroupName,
                        Location     = Vault.Location,
                        Version      = VaultCredentialVersionAad,
                        ResourceType = RecoveryServicesVaultType,
                        AgentLinks   = GetAgentLinks()
                    };

                    DataContractSerializer serializer = new DataContractSerializer(typeof(RSBackupVaultAADCreds));
                    serializer.WriteObject(writer, vaultCreds);

                    WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.BackupVaultSerialized));
                }

                return(Encoding.UTF8.GetString(output.ToArray()));
            }
        }
        /// <summary>
        /// Generates vault creds file content for Site Recovery Vault
        /// </summary>
        /// <param name="cert">management certificate</param>
        /// <param name="subscriptionId">subscription Id</param>
        /// <param name="vaultCertificateResponse">vaultCertificate Response</param>
        /// <param name="asrSite">asrSite Info</param>
        /// <returns>xml file in string format</returns>
        private string GenerateVaultCredsForSiteRecovery(X509Certificate2 cert, string subscriptionId,
                                                         VaultCertificateResponse vaultCertificateResponse, ASRSite asrSite)
        {
            using (var output = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(output, GetXmlWriterSettings()))
                {
                    ResourceCertificateAndAadDetails aadDetails = vaultCertificateResponse.Properties as ResourceCertificateAndAadDetails;
                    string resourceProviderNamespace            = string.Empty;
                    string resourceType = string.Empty;

                    Utilities.GetResourceProviderNamespaceAndType(this.Vault.ID, out resourceProviderNamespace, out resourceType);

                    Logger.Instance.WriteDebug(string.Format(
                                                   "GenerateVaultCredential resourceProviderNamespace = {0}, resourceType = {1}",
                                                   resourceProviderNamespace,
                                                   resourceType));

                    // Update vault settings with the working vault to generate file
                    Utilities.UpdateCurrentVaultContext(new ASRVaultCreds()
                    {
                        ResourceGroupName = this.Vault.ResourceGroupName,
                        ResourceName      = this.Vault.Name,
                        ResourceNamespace = resourceProviderNamespace,
                        ARMResourceType   = resourceType
                    });

                    //Code taken from Ibiza code
                    string aadAudience = string.Format(CultureInfo.InvariantCulture,
                                                       @"https://RecoveryServiceVault/{0}/{1}/{2}",
                                                       Vault.Location,
                                                       Vault.Name,
                                                       aadDetails.ResourceId);

                    RSVaultAsrCreds vaultCreds = new RSVaultAsrCreds()
                    {
                        VaultDetails = new ASRVaultDetails
                        {
                            SubscriptionId    = subscriptionId,
                            ResourceGroup     = this.Vault.ResourceGroupName,
                            ResourceName      = this.Vault.Name,
                            ResourceId        = aadDetails.ResourceId.Value,
                            Location          = Vault.Location,
                            ResourceType      = RecoveryServicesVaultType,
                            ProviderNamespace = PSRecoveryServicesClient.ProductionRpNamespace
                        },
                        ManagementCert = CertUtils.SerializeCert(cert, X509ContentType.Pfx),
                        Version        = VaultCredentialVersionAad,
                        AadDetails     = new ASRVaultAadDetails
                        {
                            AadAuthority             = aadDetails.AadAuthority,
                            AadTenantId              = aadDetails.AadTenantId,
                            ServicePrincipalClientId = aadDetails.ServicePrincipalClientId,
                            AadVaultAudience         = aadAudience,
                            ArmManagementEndpoint    = aadDetails.AzureManagementEndpointAudience
                        },
                        ChannelIntegrityKey = this.RecoveryServicesClient.GetCurrentVaultChannelIntegrityKey(),
                        SiteId   = asrSite.ID == null ? String.Empty : asrSite.ID,
                        SiteName = asrSite.Name == null ? String.Empty : asrSite.Name
                    };

                    DataContractSerializer serializer = new DataContractSerializer(typeof(RSVaultAsrCreds));
                    serializer.WriteObject(writer, vaultCreds);
                }

                return(Encoding.UTF8.GetString(output.ToArray()));
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Method to execute the command
        /// </summary>
        private void GetSiteRecoveryCredentials()
        {
            var subscription = DefaultProfile.DefaultContext.Subscription;

            // Generate certificate
            var cert = CertUtils.CreateSelfSignedCertificate(
                VaultCertificateExpiryInHoursForHRM,
                subscription.Id,
                Vault.Name);

            var site = new ASRSite();

            if (!string.IsNullOrEmpty(SiteIdentifier) &&
                !string.IsNullOrEmpty(SiteFriendlyName))
            {
                site.ID   = SiteIdentifier;
                site.Name = SiteFriendlyName;
            }

            var fileName = GenerateFileName();

            var filePath = string.IsNullOrEmpty(Path) ? Utilities.GetDefaultPath() : Path;

            // Generate file.
            if (RecoveryServicesClient.getVaultAuthType(Vault.ResourceGroupName, Vault.Name) == 0)
            {
                var vaultCreds = RecoveryServicesClient.GenerateVaultCredential(
                    cert,
                    Vault,
                    site,
                    AuthType.ACS);

                // write the content to a file.
                var output = new VaultSettingsFilePath
                {
                    FilePath = Utilities.WriteToFile(vaultCreds, filePath, fileName)
                };

                // print the path to the user.
                WriteObject(output, true);
            }
            else
            {
                var fullFilePath = System.IO.Path.Combine(filePath, fileName);
                WriteDebug(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.ExecutingGetVaultCredCmdlet,
                        subscription.Id,
                        Vault.ResourceGroupName,
                        Vault.Name,
                        fullFilePath));

                VaultCertificateResponse vaultCertificateResponse;
                try
                {
                    // Upload cert into ID Mgmt
                    WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadingCertToIdmgmt));
                    vaultCertificateResponse = UploadCert(cert);
                    WriteDebug(string.Format(CultureInfo.InvariantCulture, Resources.UploadedCertToIdmgmt));

                    var managementCert = CertUtils.SerializeCert(cert, X509ContentType.Pfx);
                    // generate vault credentials
                    var vaultCredsFileContent = GenerateVaultCredsForSiteRecovery(
                        managementCert,
                        subscription.Id,
                        vaultCertificateResponse,
                        site);

                    WriteDebug(string.Format(Resources.SavingVaultCred, fullFilePath));

                    AzureSession.Instance.DataStore.WriteFile(fullFilePath, Encoding.UTF8.GetBytes(vaultCredsFileContent));

                    var output = new VaultSettingsFilePath
                    {
                        FilePath = fullFilePath,
                    };

                    // Output filename back to user
                    WriteObject(output, true);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
        }