Click to See Complete Forum and Search --> : Need help with DSA signatures


Matt Kendall
04-24-2002, 02:07 PM
Below is some C# code which:
- generates a key
- persists the XML representation of the key in a file
- recreates the key using the XML
- signs some data

It seems to work with RSA, but it doesn't work with DSA. Each time I run
the program I get a different signature.

Does anybody have any ideas?

thanks
matt

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class sigtest {
static void Main(String[] args) {
try {
Boolean gen = false ;
Boolean rsa = true ;

for( int i = 0 ; i<args.Length ; i++ ) {
if( args[i].Equals( "-gen" ) ) {
gen = true ;
}
if( args[i].Equals( "-dsa" ) ) {
rsa = false ;
}
}

if( gen ) {
AsymmetricAlgorithm key ;
FileStream fs = new FileStream( "key.xml", FileMode.Create, FileAccess.Write,
FileShare.Write ) ;
if( rsa ) {
key = RSA.Create();
} else {
key = DSA.Create() ;
}
byte[] xmlData = Encoding.ASCII.GetBytes( key.ToXmlString(true) ) ;
fs.Write( xmlData, 0, xmlData.Length ) ;
fs.Close() ;
} else {
FileStream fs = new FileStream( "key.xml", FileMode.Open, FileAccess.Read,
FileShare.Read ) ;
byte[] xmlData = new byte[ fs.Length ] ;
fs.Read( xmlData, 0, xmlData.Length ) ;
String xmlString = Encoding.ASCII.GetString( xmlData ) ;

byte[] payload = Encoding.ASCII.GetBytes( "craphead" ) ;
byte[] encryptedData ;

if( rsa ) {
RSACryptoServiceProvider key = new RSACryptoServiceProvider() ;
key.FromXmlString( xmlString ) ;
SHA1 sha = new SHA1CryptoServiceProvider();
encryptedData = key.SignData( payload, sha ) ;
} else {
DSACryptoServiceProvider key = new DSACryptoServiceProvider() ;
key.FromXmlString( xmlString ) ;
encryptedData = key.SignData( payload ) ;
}

Console.WriteLine( Convert.ToBase64String( encryptedData ) ) ;
}
} catch( Exception e ) {
Console.WriteLine( e.Message ) ;
}
}
}