Skip to content

Instantly share code, notes, and snippets.

@vivmishra
Last active October 29, 2015 23:55
Show Gist options
  • Save vivmishra/c4fd919ad5fc37082dcb to your computer and use it in GitHub Desktop.
Save vivmishra/c4fd919ad5fc37082dcb to your computer and use it in GitHub Desktop.
X509certificates containing ECDSA Example
// Current approach
public class Net46Approach
{
public static byte[] SignECDsaSha512(byte[] data, X509Certificate2 cert)
{
// This would require using cert.Handle and a series of p/invokes to get at the
// underlying key, then passing that to a CngKey object, and passing that to
// new ECDsa(CngKey). It's a lot of work.
throw new Exception("That's a lot of work...");
}
public static byte[] SignECDsaSha512(byte[] data, ECDsa privateKey)
{
// This way works, but SignData probably better matches what you want.
using (SHA512 hasher = SHA512.Create())
{
byte[] signature1 = privateKey.SignHash(hasher.ComputeHash(data));
}
// This might not be the ECDSAsa you got!
ECDsaCng ecDsaCng = (ECDsaCng)privateKey;
ecDsaCng.HashAlgorithm = CngAlgorithm.Sha512;
return ecDsaCng.SignData(data);
}
}
// The new way
public class Net461Approach
{
public static byte[] SignECDsaSha512(byte[] data, X509Certificate2 cert)
{
using (ECDsa privateKey = cert.GetECDsaPrivateKey())
{
return privateKey.SignData(data, HashAlgorithmName.SHA512);
}
}
public static byte[] SignECDsaSha512(byte[] data, ECDsa privateKey)
{
return privateKey.SignData(data, HashAlgorithmName.SHA512);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment