Can someone give me an example of using BouncyCastle to import .pem public DSA key in C #?

I am trying to co import a .pem key in C # and I found a library that does this: BouncyCastle

I created code that loads the public key and should load the data into DSACryptoServiceProvider:

DSA dsa; using (StreamReader rdr = new StreamReader(@"pubkey.pem")) { PemReader pr = new PemReader(rdr); DsaPublicKeyParameters o = pr.ReadObject() as DsaPublicKeyParameters; CspParameters prm = new CspParameters(13); prm.Flags = System.Security.Cryptography.CspProviderFlags.UseMachineKeyStore; //o.Parameters. dsa = new DSACryptoServiceProvider(prm); DSAParameters dp = new DSAParameters(); dp.G = o.Parameters.G.ToByteArray(); dp.P = o.Parameters.P.ToByteArray(); dp.Q = o.Parameters.Q.ToByteArray(); dp.Y = oYToByteArray(); if (o.Parameters.ValidationParameters != null) { dp.Counter = o.Parameters.ValidationParameters.Counter; dp.Seed = o.Parameters.ValidationParameters.GetSeed(); } //todo: missing: J, X? dsa.ImportParameters(dp); } 

it falls on dsa.ImportParameters (dp); with the following exception: cryptographic exception: bad data.

What should I change for this?

+4
source share
1 answer

You need to use the ToByteArrayUnsigned method instead of the plain ToByteArray one, since otherwise there are times when the representation of the byte array ends with a leading null byte that breaks everything :)

+2
source

All Articles