簽署檔

[CAPICOM 是 32 位的僅限元件,可用於下列作業系統:Windows Server 2008、Windows Vista 和 Windows XP。 請改用.NET Framework來實作安全性功能。 如需詳細資訊,請參閱 使用 CAPICOM 的替代方案。]

簽章的標準用法是簽署文字,並將該簽署的文字儲存至檔案。 簽署的文字也可以透過網際網路傳送。 簽署的訊息格式為 PKCS #7。

在此範例中,當簽章不包含在簽章) 時,就會為卸離內容建立簽章 (簽章。 如果簽章的收件者具有確切簽署文字的複本,最常使用中斷連結的簽章。 在下列範例中,原始訊息和中斷連結的簽章會寫入個別檔案。

在任何 CAPICOM 錯誤上,會傳回負數十進位值為 Err.Number 。 如需詳細資訊,請參閱 CAPICOM_ERROR_CODE。 如需 Err.Number的正十進位值相關資訊,請參閱 Winerror.h。

建立簽章會使用簽署者的 私密金鑰。 只有在具有相關聯私密金鑰的簽署者憑證可供使用時,才能建立簽章。 Sign方法的這個範例未指定簽署者。 如果未指定簽署者,且 CAPICOM_MY_STORE 中沒有憑證具有相關聯的私密金鑰, 則 Sign 方法會失敗。 如果 CAPICOM_MY_STORE 中只有一個憑證具有相關聯的私密金鑰,則會使用該憑證及其私密金鑰來建立簽章。 如果 CAPICOM_MY_STORE 存放區中有一個以上的憑證具有相關聯的私密金鑰,則會出現一個對話方塊,而且使用者可以選擇用來建立簽章的憑證。

當 Web 型應用程式使用 Sign 方法時,一律會顯示提示,而且必須在使用該簽署者私密金鑰的簽章建立之前,先顯示使用者的許可權。

Sub Signfile(ByVal InputFileName As String, _
    ByVal OutputFileName As String)
    
    On Error GoTo ErrorHandler
    Dim c As String
    Dim s As String
    Dim MyStore As New Store
    Dim Signobj As New SignedData
    Dim Signer As New Signer

    ' NOTE: the name 'Attribute' is not a unique name
    ' and must be preceded by 'CAPICOM.'
    Dim SigningTime As New CAPICOM.Attribute

    ' Open the MY store and retrieve the first certificate from the
    ' Store. The signing operation will only work if this
    ' certificate is valid and has access to the signer's private key.
    MyStore.Open CAPICOM_CURRENT_USER_STORE, "MY", _
        CAPICOM_STORE_OPEN_READ_ONLY
    Signer.Certificate = MyStore.Certificates.Item(1)

    ' Open the input file and read the content to be signed from
    ' the file.
    Open App.Path & "\" & InputFileName For Input As #1
    Input #1, c
    Close #1
    
    ' Set the content to be signed.
    Signobj.Content = c

    ' Save the time the data was signed as a signer attribute.
    SigningTime.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME
    SigningTime.Value = Now
    Signer.AuthenticatedAttributes.Add SigningTime

    ' Sign the content using the signer's private key.
    ' The 'True' parameter indicates that the content signed is not
    ' included in the signature string.
    s = Signobj.Sign(Signer, True)

    Open App.Path & "\" & OutputFileName For Output As #2
    Write #2, s
    Close #2

    MsgBox ("Signature done - Saved to file" & OutputFileName)
    Set Signobj = Nothing
    Set MyStore = Nothing
    Set Signer = Nothing
    Set SigningTime = Nothing

    Exit Sub

ErrorHandler:
    If Err.Number > 0 Then
        MsgBox ("Visual Basic error found:" & Err.Description)
    Else
        MsgBox ("CAPICOM error found : " & Err.Number)
    End If
End Sub

Store.Open

Signer.Certificate

屬性

SignedData