驗證訊息
下列範例示範要接收和驗證已簽署訊息的程式碼。 此範例會接收 SignatureBuffer 和 SignatureBufferSize 中的簽章緩衝區及其大小,以及 MessageBuffer 和 MessageBufferSize 中的訊息緩衝區及其大小。
此範例假設已初始化名為 phCoNtext 的 SecHandle 變數和名為 s 的 SOCKET 結構。 如需這些變數的宣告和初始化,請參閱 搭配 Windows Sockets Client 使用 SSPI 和 搭配 Windows Sockets Server 使用 SSPI。 此程式碼包含 Secur32.lib 中函式的呼叫,這些函式必須包含在程式庫之間。
//--------------------------------------------------------------------
// Declare and initialize local variables.
#include <windows.h>
#include <stdio.h>
#include <sspi.h>
#define SECURITY_WIN32
#define MaxMessageLength 1024
#define BUFSIZ 512
void main()
{
BYTE MessageBuffer[BUFSIZ];
BYTE SignatureBuffer[BUFSIZ];
DWORD MessageBufferSize;
DWORD SignatureBufferSize;
SECURITY_STATUS SecStatus;
SecBufferDesc InputBufferDescriptor;
SecBuffer InputSecurityToken[2];
ULONG fQOP;
//------------------------------------------------------------------
// Receive the message.
if(!(ReceiveMsg(
s,
MessageBuffer,
MaxMessageLength,
&MessageBufferSize)))
{
MyHandleError("Error. Message not received.");
}
//------------------------------------------------------------------
// Receive the signature.
if(!(ReceiveMsg(
s,
SignatureBuffer,
MaxMessageLength,
&SignatureBufferSize)))
{
MyHandleError("Error. Signature not received.");
}
//------------------------------------------------------------------
// Build the input buffer descriptor.
InputBufferDescriptor.cBuffers = 2;
InputBufferDescriptor.pBuffers = InputSecurityToken;
InputBufferDescriptor.ulVersion = SECBUFFER_VERSION;
//-------------------------------------------------------------------
// Build the security buffer for the message.
InputSecurityToken[0].BufferType = SECBUFFER_DATA;
InputSecurityToken[0].cbBuffer = MessageBufferSize;
InputSecurityToken[0].pvBuffer = MessageBuffer;
//-------------------------------------------------------------------
// Build the security buffer for the signature.
InputSecurityToken[1].BufferType = SECBUFFER_TOKEN;
InputSecurityToken[1].cbBuffer = SignatureBufferSize;
InputSecurityToken[1].pvBuffer = SignatureBuffer;
//--------------------------------------------------------------------
// Call VerifySignature.
SecStatus = VerifySignature(
&phContext,
&InputBufferDescriptor, // input message descriptor
0, // no sequence number
&fQOP // quality of protection
);
if(SecStatus == SEC_E_OK)
{
printf("The signature verified the message.\n");
}
else
if(SecStatus == SEC_E_MESSAGE_ALTERED)
{
printf("The message was altered in transit.\n");
}
else
if(SecStatus == SEC_E_OUT_OF_SEQUENCE )
{
printf("The message is out of sequence.\n");
}
else
{
printf("An unknown error occurred in VerifyMessage.\n");
}
}