Arsen Zahray
Arsen Zahray

Reputation: 25287

Can anyone give me an example of using BouncyCastle to import .pem public DSA key into c#?

I am trying co import a .pem key into c#, and I've found a library, which does that: BouncyCastle

I've created a code, which loads public key and is supposed to 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 = o.Y.ToByteArray();

            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 crashes on dsa.ImportParameters(dp); with following exception: Cryptographic exception:bad data.

What should I change for this to work?

Upvotes: 4

Views: 1354

Answers (1)

tyranid
tyranid

Reputation: 13318

You need to use the ToByteArrayUnsigned method instead of plain ToByteArray one as otherwise there are cases where the byte array representation ends up with a leading zero byte which breaks everything :)

Upvotes: 2

Related Questions