Imports System
Imports System.Security.Cryptography
Public Class DSACSPSample
Public Shared Sub Main()
Try
Dim privateKeyInfo As DSAParameters
Dim publicKeyInfo As DSAParameters
' Create a new instance of DSACryptoServiceProvider to generate
' a new key pair.
Using DSA As New DSACryptoServiceProvider()
privateKeyInfo = DSA.ExportParameters(True)
publicKeyInfo = DSA.ExportParameters(False)
End Using
' The hash value to sign.
Dim HashValue As Byte() = _
{ 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, _
93, 25, 41, 100, 197, 213, 134, 130, 135}
'The value to hold the signed value.
Dim SignedHashValue As Byte() = DSASignHash(HashValue, privateKeyInfo, "SHA1")
' Verify the hash and display the results.
Dim verified As Boolean = DSAVerifyHash(HashValue, SignedHashValue, publicKeyInfo, "SHA1")
If verified Then
Console.WriteLine("The hash value was verified.")
Else
Console.WriteLine("The hash value was not verified.")
End If
Catch e As ArgumentNullException
Console.WriteLine(e.Message)
End Try
End Sub
Public Shared Function DSASignHash(HashToSign As Byte(), DSAKeyInfo As DSAParameters, _
HashAlg As String) As Byte()
Dim sig As Byte() = Nothing
Try
' Create a new instance of DSACryptoServiceProvider.
Using DSA As New DSACryptoServiceProvider()
'Import the key information.
DSA.ImportParameters(DSAKeyInfo)
' Create an DSASignatureFormatter object and pass it the
' DSACryptoServiceProvider to transfer the private key.
Dim DSAFormatter As New DSASignatureFormatter(DSA)
' Set the hash algorithm to the passed value.
DSAFormatter.SetHashAlgorithm(HashAlg)
' Create a signature for HashValue and return it.
sig = DSAFormatter.CreateSignature(HashToSign)
End Using
Catch e As CryptographicException
Console.WriteLine(e.Message)
End Try
Return sig
End Function
Public Shared Function DSAVerifyHash(HashValue As Byte(), SignedHashValue As Byte(), _
DSAKeyInfo As DSAParameters, HashAlg As String) As Boolean
Dim verified As Boolean = False
Try
' Create a new instance of DSACryptoServiceProvider.
Using DSA As New DSACryptoServiceProvider()
' Import the key information.
DSA.ImportParameters(DSAKeyInfo)
' Create an DSASignatureDeformatter object and pass it the
' DSACryptoServiceProvider to transfer the private key.
Dim DSADeformatter As New DSASignatureDeformatter(DSA)
' Set the hash algorithm to the passed value.
DSADeformatter.SetHashAlgorithm(HashAlg)
' Verify signature and return the result.
verified = DSADeformatter.VerifySignature(HashValue, SignedHashValue)
End Using
Catch e As CryptographicException
Console.WriteLine(e.Message)
End Try
Return verified
End Function
End Class