PackageDigitalSignatureManager.Sign Метод

Определение

Подписывает список частей пакета с помощью указанного сертификата X.509.

Перегрузки

Sign(IEnumerable<Uri>)

Запрашивает у пользователя сертификат X.509, который затем используется для цифровой подписи указанного списка частей пакета.

Sign(IEnumerable<Uri>, X509Certificate)

Подписывает список частей пакета с указанным сертификатом X.509.

Sign(IEnumerable<Uri>, X509Certificate, IEnumerable<PackageRelationshipSelector>)

Подписывает список частей пакета и взаимоотношений пакета заданным сертификатом X.509.

Sign(IEnumerable<Uri>, X509Certificate, IEnumerable<PackageRelationshipSelector>, String)

Подписывает список частей пакета и связей пакетов с помощью заданного сертификата ИД X.509.

Sign(IEnumerable<Uri>, X509Certificate, IEnumerable<PackageRelationshipSelector>, String, IEnumerable<DataObject>, IEnumerable<Reference>)

Подписывает список частей пакета, связей пакетов или пользовательских объектов с помощью указанного сертификата X.509 и идентификатора подписи.

Примеры

В следующем примере показаны шаги по цифровой подписи списка частей в Package. Полный пример см. в разделе Создание пакета с помощью примера цифровой подписи.

private static void SignAllParts(Package package)
{
    if (package == null)
        throw new ArgumentNullException("SignAllParts(package)");

    // Create the DigitalSignature Manager
    PackageDigitalSignatureManager dsm =
        new PackageDigitalSignatureManager(package);
    dsm.CertificateOption =
        CertificateEmbeddingOption.InSignaturePart;

    // Create a list of all the part URIs in the package to sign
    // (GetParts() also includes PackageRelationship parts).
    System.Collections.Generic.List<Uri> toSign =
        new System.Collections.Generic.List<Uri>();
    foreach (PackagePart packagePart in package.GetParts())
    {
        // Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri);
    }

    // Add the URI for SignatureOrigin PackageRelationship part.
    // The SignatureOrigin relationship is created when Sign() is called.
    // Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

    // Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin);

    // Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

    // Sign() will prompt the user to select a Certificate to sign with.
    try
    {
        dsm.Sign(toSign);
    }

    // If there are no certificates or the SmartCard manager is
    // not running, catch the exception and show an error message.
    catch (CryptographicException ex)
    {
        MessageBox.Show(
            "Cannot Sign\n" + ex.Message,
            "No Digital Certificates Available",
            MessageBoxButton.OK,
            MessageBoxImage.Exclamation);
    }
}// end:SignAllParts()
Private Shared Sub SignAllParts(ByVal package As Package)
    If package Is Nothing Then
        Throw New ArgumentNullException("SignAllParts(package)")
    End If

    ' Create the DigitalSignature Manager
    Dim dsm As New PackageDigitalSignatureManager(package)
    dsm.CertificateOption = CertificateEmbeddingOption.InSignaturePart

    ' Create a list of all the part URIs in the package to sign
    ' (GetParts() also includes PackageRelationship parts).
    Dim toSign As New System.Collections.Generic.List(Of Uri)()
    For Each packagePart As PackagePart In package.GetParts()
        ' Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri)
    Next

    ' Add the URI for SignatureOrigin PackageRelationship part.
    ' The SignatureOrigin relationship is created when Sign() is called.
    ' Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin))

    ' Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin)

    ' Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(New Uri("/", UriKind.RelativeOrAbsolute)))

    ' Sign() will prompt the user to select a Certificate to sign with.
    Try
        dsm.Sign(toSign)
    Catch ex As CryptographicException

        ' If there are no certificates or the SmartCard manager is
        ' not running, catch the exception and show an error message.
        MessageBox.Show("Cannot Sign" & vbLf & ex.Message, "No Digital Certificates Available", MessageBoxButton.OK, MessageBoxImage.Exclamation)

    End Try
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
    target = value
    Return value
End Function
' end:SignAllParts()

Sign(IEnumerable<Uri>)

Запрашивает у пользователя сертификат X.509, который затем используется для цифровой подписи указанного списка частей пакета.

public:
 System::IO::Packaging::PackageDigitalSignature ^ Sign(System::Collections::Generic::IEnumerable<Uri ^> ^ parts);
public System.IO.Packaging.PackageDigitalSignature Sign (System.Collections.Generic.IEnumerable<Uri> parts);
member this.Sign : seq<Uri> -> System.IO.Packaging.PackageDigitalSignature
Public Function Sign (parts As IEnumerable(Of Uri)) As PackageDigitalSignature

Параметры

parts
IEnumerable<Uri>

Список универсальных идентификаторов ресурсов (URI) элементов PackagePart для подписи.

Возвращаемое значение

Цифровая подпись для подписи списка parts.

Примеры

В следующем примере показано, как подписать список частей пакета цифровой подписью. Полный пример см. в статье Создание пакета с помощью цифровой подписи.

private static void SignAllParts(Package package)
{
    if (package == null)
        throw new ArgumentNullException("SignAllParts(package)");

    // Create the DigitalSignature Manager
    PackageDigitalSignatureManager dsm =
        new PackageDigitalSignatureManager(package);
    dsm.CertificateOption =
        CertificateEmbeddingOption.InSignaturePart;

    // Create a list of all the part URIs in the package to sign
    // (GetParts() also includes PackageRelationship parts).
    System.Collections.Generic.List<Uri> toSign =
        new System.Collections.Generic.List<Uri>();
    foreach (PackagePart packagePart in package.GetParts())
    {
        // Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri);
    }

    // Add the URI for SignatureOrigin PackageRelationship part.
    // The SignatureOrigin relationship is created when Sign() is called.
    // Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

    // Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin);

    // Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

    // Sign() will prompt the user to select a Certificate to sign with.
    try
    {
        dsm.Sign(toSign);
    }

    // If there are no certificates or the SmartCard manager is
    // not running, catch the exception and show an error message.
    catch (CryptographicException ex)
    {
        MessageBox.Show(
            "Cannot Sign\n" + ex.Message,
            "No Digital Certificates Available",
            MessageBoxButton.OK,
            MessageBoxImage.Exclamation);
    }
}// end:SignAllParts()
Private Shared Sub SignAllParts(ByVal package As Package)
    If package Is Nothing Then
        Throw New ArgumentNullException("SignAllParts(package)")
    End If

    ' Create the DigitalSignature Manager
    Dim dsm As New PackageDigitalSignatureManager(package)
    dsm.CertificateOption = CertificateEmbeddingOption.InSignaturePart

    ' Create a list of all the part URIs in the package to sign
    ' (GetParts() also includes PackageRelationship parts).
    Dim toSign As New System.Collections.Generic.List(Of Uri)()
    For Each packagePart As PackagePart In package.GetParts()
        ' Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri)
    Next

    ' Add the URI for SignatureOrigin PackageRelationship part.
    ' The SignatureOrigin relationship is created when Sign() is called.
    ' Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin))

    ' Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin)

    ' Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(New Uri("/", UriKind.RelativeOrAbsolute)))

    ' Sign() will prompt the user to select a Certificate to sign with.
    Try
        dsm.Sign(toSign)
    Catch ex As CryptographicException

        ' If there are no certificates or the SmartCard manager is
        ' not running, catch the exception and show an error message.
        MessageBox.Show("Cannot Sign" & vbLf & ex.Message, "No Digital Certificates Available", MessageBoxButton.OK, MessageBoxImage.Exclamation)

    End Try
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
    target = value
    Return value
End Function
' end:SignAllParts()

Комментарии

Чтобы диалоговое окно выбора сертификата было модальным для определенного окна, задайте свойство перед вызовом ParentWindowSign.

Sign не будет запрашивать сертификаты, если их нет в хранилище сертификатов по умолчанию.

Применяется к

Sign(IEnumerable<Uri>, X509Certificate)

Подписывает список частей пакета с указанным сертификатом X.509.

public:
 System::IO::Packaging::PackageDigitalSignature ^ Sign(System::Collections::Generic::IEnumerable<Uri ^> ^ parts, System::Security::Cryptography::X509Certificates::X509Certificate ^ certificate);
public System.IO.Packaging.PackageDigitalSignature Sign (System.Collections.Generic.IEnumerable<Uri> parts, System.Security.Cryptography.X509Certificates.X509Certificate certificate);
member this.Sign : seq<Uri> * System.Security.Cryptography.X509Certificates.X509Certificate -> System.IO.Packaging.PackageDigitalSignature
Public Function Sign (parts As IEnumerable(Of Uri), certificate As X509Certificate) As PackageDigitalSignature

Параметры

parts
IEnumerable<Uri>

Список универсальных идентификаторов ресурсов (URI) элементов PackagePart для подписи.

certificate
X509Certificate

Сертификат X.509, используемый для цифровой подписи каждого указанного parts.

Возвращаемое значение

Цифровая подпись используется для подписи указанного списка parts; или null, если не удалось найти сертификат либо пользователь щелкнул "Отмена" в диалоговом окне выбора сертификатов.

Примеры

В следующем примере показано, как цифровое подписание списка частей в Package. Полный пример см. в разделе Создание пакета с помощью цифровой подписи.

private static void SignAllParts(Package package)
{
    if (package == null)
        throw new ArgumentNullException("SignAllParts(package)");

    // Create the DigitalSignature Manager
    PackageDigitalSignatureManager dsm =
        new PackageDigitalSignatureManager(package);
    dsm.CertificateOption =
        CertificateEmbeddingOption.InSignaturePart;

    // Create a list of all the part URIs in the package to sign
    // (GetParts() also includes PackageRelationship parts).
    System.Collections.Generic.List<Uri> toSign =
        new System.Collections.Generic.List<Uri>();
    foreach (PackagePart packagePart in package.GetParts())
    {
        // Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri);
    }

    // Add the URI for SignatureOrigin PackageRelationship part.
    // The SignatureOrigin relationship is created when Sign() is called.
    // Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

    // Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin);

    // Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

    // Sign() will prompt the user to select a Certificate to sign with.
    try
    {
        dsm.Sign(toSign);
    }

    // If there are no certificates or the SmartCard manager is
    // not running, catch the exception and show an error message.
    catch (CryptographicException ex)
    {
        MessageBox.Show(
            "Cannot Sign\n" + ex.Message,
            "No Digital Certificates Available",
            MessageBoxButton.OK,
            MessageBoxImage.Exclamation);
    }
}// end:SignAllParts()
Private Shared Sub SignAllParts(ByVal package As Package)
    If package Is Nothing Then
        Throw New ArgumentNullException("SignAllParts(package)")
    End If

    ' Create the DigitalSignature Manager
    Dim dsm As New PackageDigitalSignatureManager(package)
    dsm.CertificateOption = CertificateEmbeddingOption.InSignaturePart

    ' Create a list of all the part URIs in the package to sign
    ' (GetParts() also includes PackageRelationship parts).
    Dim toSign As New System.Collections.Generic.List(Of Uri)()
    For Each packagePart As PackagePart In package.GetParts()
        ' Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri)
    Next

    ' Add the URI for SignatureOrigin PackageRelationship part.
    ' The SignatureOrigin relationship is created when Sign() is called.
    ' Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin))

    ' Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin)

    ' Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(New Uri("/", UriKind.RelativeOrAbsolute)))

    ' Sign() will prompt the user to select a Certificate to sign with.
    Try
        dsm.Sign(toSign)
    Catch ex As CryptographicException

        ' If there are no certificates or the SmartCard manager is
        ' not running, catch the exception and show an error message.
        MessageBox.Show("Cannot Sign" & vbLf & ex.Message, "No Digital Certificates Available", MessageBoxButton.OK, MessageBoxImage.Exclamation)

    End Try
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
    target = value
    Return value
End Function
' end:SignAllParts()

Применяется к

Sign(IEnumerable<Uri>, X509Certificate, IEnumerable<PackageRelationshipSelector>)

Подписывает список частей пакета и взаимоотношений пакета заданным сертификатом X.509.

public:
 System::IO::Packaging::PackageDigitalSignature ^ Sign(System::Collections::Generic::IEnumerable<Uri ^> ^ parts, System::Security::Cryptography::X509Certificates::X509Certificate ^ certificate, System::Collections::Generic::IEnumerable<System::IO::Packaging::PackageRelationshipSelector ^> ^ relationshipSelectors);
public System.IO.Packaging.PackageDigitalSignature Sign (System.Collections.Generic.IEnumerable<Uri> parts, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Collections.Generic.IEnumerable<System.IO.Packaging.PackageRelationshipSelector> relationshipSelectors);
member this.Sign : seq<Uri> * System.Security.Cryptography.X509Certificates.X509Certificate * seq<System.IO.Packaging.PackageRelationshipSelector> -> System.IO.Packaging.PackageDigitalSignature
Public Function Sign (parts As IEnumerable(Of Uri), certificate As X509Certificate, relationshipSelectors As IEnumerable(Of PackageRelationshipSelector)) As PackageDigitalSignature

Параметры

parts
IEnumerable<Uri>

Список универсальных идентификаторов ресурсов (URI) объектов PackagePart для подписи.

certificate
X509Certificate

Сертификат X.509, используемый для создания цифровой подписи для каждой из указанных частей и связей.

relationshipSelectors
IEnumerable<PackageRelationshipSelector>

Список подписываемых объектов PackageRelationship.

Возвращаемое значение

Цифровая подпись, которая используется для подписывания элементов, указанных в списках parts и relationshipSelectors.

Исключения

Ни parts, ни relationshipSelectors не указывают объекты для подписи.

Примеры

В следующем примере показано, как подписать список частей пакета цифровой подписью. Полный пример см. в статье Создание пакета с помощью цифровой подписи.

private static void SignAllParts(Package package)
{
    if (package == null)
        throw new ArgumentNullException("SignAllParts(package)");

    // Create the DigitalSignature Manager
    PackageDigitalSignatureManager dsm =
        new PackageDigitalSignatureManager(package);
    dsm.CertificateOption =
        CertificateEmbeddingOption.InSignaturePart;

    // Create a list of all the part URIs in the package to sign
    // (GetParts() also includes PackageRelationship parts).
    System.Collections.Generic.List<Uri> toSign =
        new System.Collections.Generic.List<Uri>();
    foreach (PackagePart packagePart in package.GetParts())
    {
        // Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri);
    }

    // Add the URI for SignatureOrigin PackageRelationship part.
    // The SignatureOrigin relationship is created when Sign() is called.
    // Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

    // Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin);

    // Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

    // Sign() will prompt the user to select a Certificate to sign with.
    try
    {
        dsm.Sign(toSign);
    }

    // If there are no certificates or the SmartCard manager is
    // not running, catch the exception and show an error message.
    catch (CryptographicException ex)
    {
        MessageBox.Show(
            "Cannot Sign\n" + ex.Message,
            "No Digital Certificates Available",
            MessageBoxButton.OK,
            MessageBoxImage.Exclamation);
    }
}// end:SignAllParts()
Private Shared Sub SignAllParts(ByVal package As Package)
    If package Is Nothing Then
        Throw New ArgumentNullException("SignAllParts(package)")
    End If

    ' Create the DigitalSignature Manager
    Dim dsm As New PackageDigitalSignatureManager(package)
    dsm.CertificateOption = CertificateEmbeddingOption.InSignaturePart

    ' Create a list of all the part URIs in the package to sign
    ' (GetParts() also includes PackageRelationship parts).
    Dim toSign As New System.Collections.Generic.List(Of Uri)()
    For Each packagePart As PackagePart In package.GetParts()
        ' Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri)
    Next

    ' Add the URI for SignatureOrigin PackageRelationship part.
    ' The SignatureOrigin relationship is created when Sign() is called.
    ' Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin))

    ' Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin)

    ' Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(New Uri("/", UriKind.RelativeOrAbsolute)))

    ' Sign() will prompt the user to select a Certificate to sign with.
    Try
        dsm.Sign(toSign)
    Catch ex As CryptographicException

        ' If there are no certificates or the SmartCard manager is
        ' not running, catch the exception and show an error message.
        MessageBox.Show("Cannot Sign" & vbLf & ex.Message, "No Digital Certificates Available", MessageBoxButton.OK, MessageBoxImage.Exclamation)

    End Try
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
    target = value
    Return value
End Function
' end:SignAllParts()

Комментарии

Между parts и relationshipSelectors должен быть по крайней мере один элемент для подписывания.

Применяется к

Sign(IEnumerable<Uri>, X509Certificate, IEnumerable<PackageRelationshipSelector>, String)

Подписывает список частей пакета и связей пакетов с помощью заданного сертификата ИД X.509.

public:
 System::IO::Packaging::PackageDigitalSignature ^ Sign(System::Collections::Generic::IEnumerable<Uri ^> ^ parts, System::Security::Cryptography::X509Certificates::X509Certificate ^ certificate, System::Collections::Generic::IEnumerable<System::IO::Packaging::PackageRelationshipSelector ^> ^ relationshipSelectors, System::String ^ signatureId);
public System.IO.Packaging.PackageDigitalSignature Sign (System.Collections.Generic.IEnumerable<Uri> parts, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Collections.Generic.IEnumerable<System.IO.Packaging.PackageRelationshipSelector> relationshipSelectors, string signatureId);
member this.Sign : seq<Uri> * System.Security.Cryptography.X509Certificates.X509Certificate * seq<System.IO.Packaging.PackageRelationshipSelector> * string -> System.IO.Packaging.PackageDigitalSignature
Public Function Sign (parts As IEnumerable(Of Uri), certificate As X509Certificate, relationshipSelectors As IEnumerable(Of PackageRelationshipSelector), signatureId As String) As PackageDigitalSignature

Параметры

parts
IEnumerable<Uri>

Список универсальных идентификаторов ресурсов (URI) объектов PackagePart для подписи.

certificate
X509Certificate

Сертификат X.509, используемый для создания цифровой подписи для каждой из указанных частей и связей.

relationshipSelectors
IEnumerable<PackageRelationshipSelector>

Список подписываемых объектов PackageRelationship.

signatureId
String

Идентификационная строка, которую следует связать с подписью.

Возвращаемое значение

Цифровая подпись, которая используется для подписывания элементов, указанных в списках parts и relationshipSelectors.

Исключения

В списках parts и relationshipSelectors отсутствуют элементы для подписывания.

Примеры

В следующем примере показано, как подписать список частей пакета цифровой подписью. Полный пример см. в статье Создание пакета с помощью цифровой подписи.

private static void SignAllParts(Package package)
{
    if (package == null)
        throw new ArgumentNullException("SignAllParts(package)");

    // Create the DigitalSignature Manager
    PackageDigitalSignatureManager dsm =
        new PackageDigitalSignatureManager(package);
    dsm.CertificateOption =
        CertificateEmbeddingOption.InSignaturePart;

    // Create a list of all the part URIs in the package to sign
    // (GetParts() also includes PackageRelationship parts).
    System.Collections.Generic.List<Uri> toSign =
        new System.Collections.Generic.List<Uri>();
    foreach (PackagePart packagePart in package.GetParts())
    {
        // Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri);
    }

    // Add the URI for SignatureOrigin PackageRelationship part.
    // The SignatureOrigin relationship is created when Sign() is called.
    // Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

    // Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin);

    // Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

    // Sign() will prompt the user to select a Certificate to sign with.
    try
    {
        dsm.Sign(toSign);
    }

    // If there are no certificates or the SmartCard manager is
    // not running, catch the exception and show an error message.
    catch (CryptographicException ex)
    {
        MessageBox.Show(
            "Cannot Sign\n" + ex.Message,
            "No Digital Certificates Available",
            MessageBoxButton.OK,
            MessageBoxImage.Exclamation);
    }
}// end:SignAllParts()
Private Shared Sub SignAllParts(ByVal package As Package)
    If package Is Nothing Then
        Throw New ArgumentNullException("SignAllParts(package)")
    End If

    ' Create the DigitalSignature Manager
    Dim dsm As New PackageDigitalSignatureManager(package)
    dsm.CertificateOption = CertificateEmbeddingOption.InSignaturePart

    ' Create a list of all the part URIs in the package to sign
    ' (GetParts() also includes PackageRelationship parts).
    Dim toSign As New System.Collections.Generic.List(Of Uri)()
    For Each packagePart As PackagePart In package.GetParts()
        ' Add all package parts to the list for signing.
        toSign.Add(packagePart.Uri)
    Next

    ' Add the URI for SignatureOrigin PackageRelationship part.
    ' The SignatureOrigin relationship is created when Sign() is called.
    ' Signing the SignatureOrigin relationship disables counter-signatures.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin))

    ' Also sign the SignatureOrigin part.
    toSign.Add(dsm.SignatureOrigin)

    ' Add the package relationship to the signature origin to be signed.
    toSign.Add(PackUriHelper.GetRelationshipPartUri(New Uri("/", UriKind.RelativeOrAbsolute)))

    ' Sign() will prompt the user to select a Certificate to sign with.
    Try
        dsm.Sign(toSign)
    Catch ex As CryptographicException

        ' If there are no certificates or the SmartCard manager is
        ' not running, catch the exception and show an error message.
        MessageBox.Show("Cannot Sign" & vbLf & ex.Message, "No Digital Certificates Available", MessageBoxButton.OK, MessageBoxImage.Exclamation)

    End Try
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
    target = value
    Return value
End Function
' end:SignAllParts()

Комментарии

Список parts может быть пустым или nullrelationshipSelectors содержать хотя бы одну запись.

Список relationshipSelectors может быть пустым или nullparts содержать хотя бы одну запись.

Между списком parts и relationshipSelectors должен быть по крайней мере один элемент для подписи.

Применяется к

Sign(IEnumerable<Uri>, X509Certificate, IEnumerable<PackageRelationshipSelector>, String, IEnumerable<DataObject>, IEnumerable<Reference>)

Подписывает список частей пакета, связей пакетов или пользовательских объектов с помощью указанного сертификата X.509 и идентификатора подписи.

public:
 System::IO::Packaging::PackageDigitalSignature ^ Sign(System::Collections::Generic::IEnumerable<Uri ^> ^ parts, System::Security::Cryptography::X509Certificates::X509Certificate ^ certificate, System::Collections::Generic::IEnumerable<System::IO::Packaging::PackageRelationshipSelector ^> ^ relationshipSelectors, System::String ^ signatureId, System::Collections::Generic::IEnumerable<System::Security::Cryptography::Xml::DataObject ^> ^ signatureObjects, System::Collections::Generic::IEnumerable<System::Security::Cryptography::Xml::Reference ^> ^ objectReferences);
[System.Security.SecurityCritical]
public System.IO.Packaging.PackageDigitalSignature Sign (System.Collections.Generic.IEnumerable<Uri> parts, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Collections.Generic.IEnumerable<System.IO.Packaging.PackageRelationshipSelector> relationshipSelectors, string signatureId, System.Collections.Generic.IEnumerable<System.Security.Cryptography.Xml.DataObject> signatureObjects, System.Collections.Generic.IEnumerable<System.Security.Cryptography.Xml.Reference> objectReferences);
public System.IO.Packaging.PackageDigitalSignature Sign (System.Collections.Generic.IEnumerable<Uri> parts, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Collections.Generic.IEnumerable<System.IO.Packaging.PackageRelationshipSelector> relationshipSelectors, string signatureId, System.Collections.Generic.IEnumerable<System.Security.Cryptography.Xml.DataObject> signatureObjects, System.Collections.Generic.IEnumerable<System.Security.Cryptography.Xml.Reference> objectReferences);
[<System.Security.SecurityCritical>]
member this.Sign : seq<Uri> * System.Security.Cryptography.X509Certificates.X509Certificate * seq<System.IO.Packaging.PackageRelationshipSelector> * string * seq<System.Security.Cryptography.Xml.DataObject> * seq<System.Security.Cryptography.Xml.Reference> -> System.IO.Packaging.PackageDigitalSignature
member this.Sign : seq<Uri> * System.Security.Cryptography.X509Certificates.X509Certificate * seq<System.IO.Packaging.PackageRelationshipSelector> * string * seq<System.Security.Cryptography.Xml.DataObject> * seq<System.Security.Cryptography.Xml.Reference> -> System.IO.Packaging.PackageDigitalSignature
Public Function Sign (parts As IEnumerable(Of Uri), certificate As X509Certificate, relationshipSelectors As IEnumerable(Of PackageRelationshipSelector), signatureId As String, signatureObjects As IEnumerable(Of DataObject), objectReferences As IEnumerable(Of Reference)) As PackageDigitalSignature

Параметры

parts
IEnumerable<Uri>

Список универсальных идентификаторов ресурсов (URI) объектов PackagePart для подписи.

certificate
X509Certificate

Сертификат X.509, используемый для создания цифровой подписи для каждой из указанных частей и связей.

relationshipSelectors
IEnumerable<PackageRelationshipSelector>

Список подписываемых объектов PackageRelationship.

signatureId
String

Идентификационная строка, которую следует связать с подписью.

signatureObjects
IEnumerable<DataObject>

Список пользовательских объектов данных, которые требуется подписать.

objectReferences
IEnumerable<Reference>

Список ссылок на подписываемые пользовательские объекты.

Возвращаемое значение

Цифровая подпись, которая используется для подписывания элементов, указанных в списках parts и relationshipSelectors.

Атрибуты

Исключения

В списках parts, relationshipSelectors, signatureObjects и objectReferences отсутствуют элементы для подписания.

ContentType подписываемой части ссылается на пустое, неопределенное или имеющее значение null свойство TransformMapping.

signatureId не null является и не является допустимым идентификатором схемы XML (например, начинается с начальной числовой цифры).

Комментарии

Для входа в parts, relationshipSelectors, signatureObjectsили objectReferencesдолжен быть по крайней мере один элемент .

Примечание

Термины Object, Manifest, , Reference, SignaturePropertiesи Transform в следующих двух примечаниях относятся к типам элементов и тегам, определенным в спецификации синтаксиса и обработки W3C XML-Signature, см https://www.w3.org/TR/xmldsig-core/. .

Эта и другие Sign перегрузки метода используют текущий TransformMapping словарь, определяющий Transform для применения на основе части ContentTypeпакета . Спецификация Microsoft Open Packaging Conventions (OPC) в настоящее время допускает только два допустимых Transform алгоритма: C14 и C14N. Стандарт синтаксиса и обработки W3C XML-Signature не допускает пустые Manifest теги. Кроме того, спецификация Open Packaging Conventions требует наличия Object тега Package, который содержит теги Manifest и SignatureProperties . Каждый Manifest тег дополнительно также включает по крайней мере один Reference тег. Для этих тегов требуется, чтобы каждая подпись подписыла по крайней мере одну PackagePart (непустый тег частей) или PackageRelationship (непустую relationshipSelectors), даже если подпись необходима только для подписи signatureObjects или objectReferences.

Этот Sign метод игнорирует свойство, связанное DigestMethod с каждым из них Reference , определенным в objectReferences.

Эта Sign перегрузка обеспечивает поддержку создания XML-подписей, требующих пользовательских Object тегов. Чтобы любой предоставленный Object тег был подписан, соответствующий Reference тег должен быть предоставлен с универсальным идентификатором ресурса (URI), который указывает тег в синтаксисе локального Object фрагмента. Например, Object если тег имеет идентификатор "myObject", универсальный код ресурса (URI) в теге Reference будет иметь значение "#myObject". Для неподписанных объектов не Reference требуется.

Применяется к