You will get ValidationStatus.WrongUsage
when the certificate is used in a way it was not issued for.
For example:
One of possible uses is KeyUses.KeyCertSign
(Certificate signing).
If you use a certificate without KeyCertSign
usage to issue another certificate, correct validation routine would report ValidationStatus.WrongUsage
when validating issued certificate.
Here is sample code to get ValidationStatus.WrongUsage
:
// we will need two certificates
Certificate rootCert, invalidCert;
// prepare info for root certificate
var rootInfo = new CertificateInfo();
rootInfo.Subject = new DistinguishedName("CN=Sample root");
rootInfo.SetSerialNumber(Guid.NewGuid().ToByteArray());
// specify very limited usage
rootInfo.Usage = KeyUses.KeyAgreement;
using (var alg = new AsymmetricKeyAlgorithm())
{
// generate a 2048-bit RSA key for the certificate
alg.GenerateKey(AsymmetricKeyAlgorithmId.RSA, 2048);
var privateKey = alg.GetPrivateKey();
// create the self-signed (root) certificate
rootCert = CertificateIssuer.Issue(rootInfo, privateKey);
rootCert.Associate(privateKey);
}
// prepare info for certificate with invalid usage
var invalidCertInfo = new CertificateInfo();
invalidCertInfo.Subject = new DistinguishedName("CN=This should not be never issued");
invalidCertInfo.SetSerialNumber(Guid.NewGuid().ToByteArray());
invalidCertInfo.Usage = KeyUses.KeyAgreement;
using (var alg = new AsymmetricKeyAlgorithm())
{
// generate a 2048-bit RSA key for the certificate
alg.GenerateKey(AsymmetricKeyAlgorithmId.RSA, 2048);
var publicKey = alg.GetPublicKey();
// issue invalid certificate
invalidCert = CertificateIssuer.Issue(rootCert, invalidCertInfo, publicKey);
}
// check usage of invalid certificate
// Note: Because root cert is not in Certificate Store,
// we need to use certificate chain to link the two certs.
var chain = new CertificateChain() { invalidCert, rootCert };
var result = chain.Validate();
Console.WriteLine(result.Status);
You can try for yourself, that when you give the root certificate correct usage, validation result will not contain ValidationStatus.WrongUsage
. To do this, change line rootInfo.Usage = KeyUses.KeyAgreement
to:
rootInfo.Usage = KeyUses.KeyCertSign;