public static void ValidateCertificate(X509Certificate cert) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (cert.Version != 3) { throw new ArgumentException("Certificate must have an ExtendedKeyUsage extension."); } Asn1OctetString extensionValue = cert.GetExtensionValue(X509Extensions.ExtendedKeyUsage); if (extensionValue == null) { throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension."); } if (!cert.GetCriticalExtensionOids().Contains(X509Extensions.ExtendedKeyUsage.Id)) { throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical."); } try { ExtendedKeyUsage instance = ExtendedKeyUsage.GetInstance(Asn1Object.FromByteArray(extensionValue.GetOctets())); if (!instance.HasKeyPurposeId(KeyPurposeID.IdKPTimeStamping) || instance.Count != 1) { throw new TspValidationException("ExtendedKeyUsage not solely time stamping."); } } catch (IOException) { throw new TspValidationException("cannot process ExtendedKeyUsage extension"); } }
/// <summary> /// The Alias Certificate is a certificate over the Alias Public key (+ the RIoT attestation extension) signed by the /// DeviceID key. /// </summary> /// <param name="deviceID">The cert siging key</param> /// <param name="aliasKey">The key being certified</param> /// <param name="fwid">The (simulated) hash of the upper-level firmware</param> /// <param name="signingSeed">Seed for the signing BRBG</param> /// <returns>The alias certificate</returns> private static X509Certificate CreateAliasCert(AsymmetricCipherKeyPair deviceID, AsymmetricCipherKeyPair aliasKey, byte[] fwid, byte[] signingSeed) { var random = GetDrbg(signingSeed, SeedUsage.Signing); // set standard fields in TBS structure X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(GetSerialNumber(random)); certGen.SetIssuerDN(rDeviceCertSubject); certGen.SetSubjectDN(rAliasCertSubject); certGen.SetNotBefore(startTime); certGen.SetNotAfter(endTime); certGen.SetPublicKey(aliasKey.Public); // add extensions certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true, ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPClientAuth))); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature)); var riotExtension = CreateRIoTExtension(fwid, deviceID.Public); certGen.AddExtension(new DerObjectIdentifier(rExtensionOID), false, riotExtension); certGen.AddExtension( X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(deviceID.Public))); certGen.AddExtension( X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aliasKey.Public))); // sign and return ISignatureFactory signatureFactory = new Asn1SignatureFactory(rSigSch, deviceID.Private, random); var certificate = certGen.Generate(signatureFactory); return(certificate); }
/// <inheritdoc /> public override void InjectReferenceValue(X509Certificate2 value) { Certificate = value; Asn1Object exValue = GetExtensionValue(value); if (exValue == null) { if (IsRequired()) { throw new PolicyRequiredException("Extention " + ExtentionIdentifier.Display + " is marked as required by is not present."); } PolicyValue = new PolicyValue <IList <string> >(new List <string>()); return; } ExtendedKeyUsage usages = ExtendedKeyUsage.GetInstance(exValue); IList purposeList = usages.GetAllUsages(); var usageList = new List <string>(); foreach (DerObjectIdentifier purpose in purposeList) { usageList.Add(purpose.Id); } PolicyValue = new PolicyValue <IList <string> >(usageList); }
/** * Validate the passed in certificate as being of the correct type to be used * for time stamping. To be valid it must have an ExtendedKeyUsage extension * which has a key purpose identifier of id-kp-timeStamping. * * @param cert the certificate of interest. * @throws TspValidationException if the certicate fails on one of the check points. */ public static void ValidateCertificate( X509Certificate cert) { if (cert.Version != 3) { throw new ArgumentException("Certificate must have an ExtendedKeyUsage extension."); } Asn1OctetString ext = cert.GetExtensionValue(X509Extensions.ExtendedKeyUsage); if (ext == null) { throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension."); } if (!cert.GetCriticalExtensionOids().Contains(X509Extensions.ExtendedKeyUsage.Id)) { throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical."); } try { ExtendedKeyUsage extKey = ExtendedKeyUsage.GetInstance( Asn1Object.FromByteArray(ext.GetOctets())); if (!extKey.HasKeyPurposeId(KeyPurposeID.IdKPTimeStamping) || extKey.Count != 1) { throw new TspValidationException("ExtendedKeyUsage not solely time stamping."); } } catch (IOException) { throw new TspValidationException("cannot process ExtendedKeyUsage extension"); } }
public static TimestampService Create( CertificateAuthority certificateAuthority, TimestampServiceOptions serviceOptions = null) { if (certificateAuthority == null) { throw new ArgumentNullException(nameof(certificateAuthority)); } serviceOptions = serviceOptions ?? new TimestampServiceOptions(); var keyPair = CertificateUtilities.CreateKeyPair(); var id = Guid.NewGuid().ToString(); var subjectName = new X509Name($"C=US,ST=WA,L=Redmond,O=NuGet,CN=NuGet Test Timestamp Service ({id})"); Action <X509V3CertificateGenerator> customizeCertificate = generator => { generator.AddExtension( X509Extensions.AuthorityInfoAccess, critical: false, extensionValue: new DerSequence( new AccessDescription(AccessDescription.IdADOcsp, new GeneralName(GeneralName.UniformResourceIdentifier, certificateAuthority.OcspResponderUri.OriginalString)), new AccessDescription(AccessDescription.IdADCAIssuers, new GeneralName(GeneralName.UniformResourceIdentifier, certificateAuthority.CertificateUri.OriginalString)))); generator.AddExtension( X509Extensions.AuthorityKeyIdentifier, critical: false, extensionValue: new AuthorityKeyIdentifierStructure(certificateAuthority.Certificate)); generator.AddExtension( X509Extensions.SubjectKeyIdentifier, critical: false, extensionValue: new SubjectKeyIdentifierStructure(keyPair.Public)); generator.AddExtension( X509Extensions.BasicConstraints, critical: true, extensionValue: new BasicConstraints(cA: false)); generator.AddExtension( X509Extensions.KeyUsage, critical: true, extensionValue: new KeyUsage(KeyUsage.DigitalSignature)); generator.AddExtension( X509Extensions.ExtendedKeyUsage, critical: true, extensionValue: ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping))); }; var issueOptions = new IssueCertificateOptions() { KeyPair = keyPair, SubjectName = subjectName, CustomizeCertificate = customizeCertificate }; var certificate = certificateAuthority.IssueCertificate(issueOptions); var uri = certificateAuthority.GenerateRandomUri(); return(new TimestampService(certificateAuthority, certificate, keyPair, uri, serviceOptions)); }
/// <summary> /// Create ExtendedKeyUsage from an X509Extension /// </summary> /// <param name="Extension">X509 extension</param> /// <remarks> /// Sub classses must provide an implementation to decode their values /// </remarks> public extendedKeyUsage(X509Extension Extension) : base(Extension) { base.oid = X509Extensions.ExtendedKeyUsage; base.name = "ExtendedKeyUsage"; base.displayName = "Extended Key Usage"; ExtendedKeyUsage eku = ExtendedKeyUsage.GetInstance(Extension); // Lookup each OID in the extension and add to usage List by name foreach (var e in eku.GetAllUsages()) { usage.Add(ekuNames[e.ToString()]); } }
private bool ValidateAlternateSigner(X509Certificate certificate, X509Certificate issuer) { byte[] bytes = certificate.GetExtensionValue(new DerObjectIdentifier(X509Extensions.ExtendedKeyUsage.Id)).GetOctets(); Asn1InputStream aIn = new Asn1InputStream(bytes); var As1 = aIn.ReadObject(); ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.GetInstance(As1); var extendedKey = extendedKeyUsage.GetAllUsages().Cast <DerObjectIdentifier>().ToList(); if (extendedKey.Any(x => x.Id == "1.3.6.1.5.5.7.3.9")) { certificate.Verify(issuer.GetPublicKey()); return(true); } return(false); }
private static X509Certificate2 GenerateAndSignCertificate( X509Name subjectName, X509Name issuerName, AsymmetricKeyParameter privateSigningKey) { var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var certGenerator = new X509V3CertificateGenerator(); var keyGenerationParameters = new KeyGenerationParameters(random, 256); var keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair certKeyPair = keyPairGenerator.GenerateKeyPair(); certGenerator.SetPublicKey(certKeyPair.Public); var serialNumber = new BigInteger(64, random); certGenerator.SetSerialNumber(serialNumber); certGenerator.SetSubjectDN(subjectName); certGenerator.SetIssuerDN(issuerName); DateTime notBefore = DateTime.UtcNow - TimeSpan.FromDays(3); DateTime notAfter = DateTime.UtcNow + TimeSpan.FromDays(3); certGenerator.SetNotBefore(notBefore); certGenerator.SetNotAfter(notAfter); certGenerator.AddExtension( X509Extensions.ExtendedKeyUsage, true, ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPClientAuth))); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHECDSA", privateSigningKey, random); var certificate = certGenerator.Generate(signatureFactory); return(new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate))); }
public static X509Certificate MakeCertificate(AsymmetricCipherKeyPair _subKP, string _subDN, AsymmetricCipherKeyPair _issKP, string _issDN, bool _ca) { AsymmetricKeyParameter _subPub = _subKP.Public; AsymmetricKeyParameter _issPriv = _issKP.Private; AsymmetricKeyParameter _issPub = _issKP.Public; X509V3CertificateGenerator _v3CertGen = new X509V3CertificateGenerator(); _v3CertGen.Reset(); _v3CertGen.SetSerialNumber(allocateSerialNumber()); _v3CertGen.SetIssuerDN(new X509Name(_issDN)); _v3CertGen.SetNotBefore(DateTime.UtcNow); _v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100)); _v3CertGen.SetSubjectDN(new X509Name(_subDN)); _v3CertGen.SetPublicKey(_subPub); _v3CertGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); _v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(_subPub)); _v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(_issPub)); if (_ca) { _v3CertGen.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(_ca)); } else { _v3CertGen.AddExtension(X509Extensions.ExtendedKeyUsage, true, ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping))); } X509Certificate _cert = _v3CertGen.Generate(_issPriv); _cert.CheckValidity(DateTime.UtcNow); _cert.Verify(_issPub); return(_cert); }
public static TimestampService Create( CertificateAuthority certificateAuthority, TimestampServiceOptions serviceOptions = null, IssueCertificateOptions issueCertificateOptions = null) { if (certificateAuthority == null) { throw new ArgumentNullException(nameof(certificateAuthority)); } serviceOptions = serviceOptions ?? new TimestampServiceOptions(); if (issueCertificateOptions == null) { issueCertificateOptions = IssueCertificateOptions.CreateDefaultForTimestampService(); } void customizeCertificate(X509V3CertificateGenerator generator) { generator.AddExtension( X509Extensions.AuthorityInfoAccess, critical: false, extensionValue: new DerSequence( new AccessDescription(AccessDescription.IdADOcsp, new GeneralName(GeneralName.UniformResourceIdentifier, certificateAuthority.OcspResponderUri.OriginalString)), new AccessDescription(AccessDescription.IdADCAIssuers, new GeneralName(GeneralName.UniformResourceIdentifier, certificateAuthority.CertificateUri.OriginalString)))); generator.AddExtension( X509Extensions.AuthorityKeyIdentifier, critical: false, extensionValue: new AuthorityKeyIdentifierStructure(certificateAuthority.Certificate)); generator.AddExtension( X509Extensions.SubjectKeyIdentifier, critical: false, extensionValue: new SubjectKeyIdentifierStructure(issueCertificateOptions.KeyPair.Public)); generator.AddExtension( X509Extensions.BasicConstraints, critical: true, extensionValue: new BasicConstraints(cA: false)); generator.AddExtension( X509Extensions.KeyUsage, critical: true, extensionValue: new KeyUsage(KeyUsage.DigitalSignature)); generator.AddExtension( X509Extensions.ExtendedKeyUsage, critical: true, extensionValue: ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping))); } if (issueCertificateOptions.CustomizeCertificate == null) { issueCertificateOptions.CustomizeCertificate = customizeCertificate; } if (serviceOptions.IssuedCertificateNotBefore.HasValue) { issueCertificateOptions.NotBefore = serviceOptions.IssuedCertificateNotBefore.Value; } if (serviceOptions.IssuedCertificateNotAfter.HasValue) { issueCertificateOptions.NotAfter = serviceOptions.IssuedCertificateNotAfter.Value; } var certificate = certificateAuthority.IssueCertificate(issueCertificateOptions); var uri = certificateAuthority.GenerateRandomUri(); return(new TimestampService(certificateAuthority, certificate, issueCertificateOptions.KeyPair, uri, serviceOptions)); }
static void Main(string[] args) { foreach (string s in args) { if (s.StartsWith("-out:")) { outputfile = s.Replace("-out:", ""); } if (s.StartsWith("-in:")) { certfile = s.Replace("-in:", ""); } } if (outputfile != "stdout") { str = new StreamWriter(outputfile, false); } System.Security.Cryptography.X509Certificates.X509Certificate2 cer = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certfile)); Al.Security.X509.X509Certificate CERT = Al.Security.Security.DotNetUtilities.FromX509Certificate(cer); Print("Certificate"); Print(" Data"); Print(" Version : " + cer.Version.ToString()); Print(" Valid : " + cer.Verify().ToString()); Print(" Serial Number:"); Print(" " + cer.SerialNumber); Print(" Signature Algorithm : "); Print(" " + cer.SignatureAlgorithm.FriendlyName); Print(" Issuer : " + cer.Issuer); Print(" Validity : "); Print(" Not Before : " + GetRFC822Date(cer.NotBefore)); Print(" Not After : " + GetRFC822Date(cer.NotAfter)); Print(" Subject : " + cer.Subject); Print(" Subject Public Key Info:"); Print(" Public Key Exchange Algorithm: " + cer.PublicKey.Key.KeyExchangeAlgorithm); Print(" Public Key: " + cer.PublicKey.Key.KeySize.ToString() + " bit"); Print(" Modulus:"); Print(cer.GetPublicKey(), " "); if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.RsaKeyParameters) { RsaKeyParameters rsa = (RsaKeyParameters)CERT.GetPublicKey(); Print(" Exponent:" + rsa.Exponent); } else if (CERT.GetPublicKey() is Al.Security.Crypto.Parameters.DsaKeyParameters) { DsaKeyParameters dsa = (DsaKeyParameters)CERT.GetPublicKey(); Print(" DSA Parameters:"); Print(" G:"); Print(" " + dsa.Parameters.G.ToString()); Print(" P:"); Print(" " + dsa.Parameters.P.ToString()); Print(" Q:"); Print(" " + dsa.Parameters.Q.ToString()); } // Extensions Print(" X509 Extensions"); string extab = " "; bool critical = true; foreach (string oid in CERT.GetCriticalExtensionOids()) { Print(" "); X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid)); if (oid == X509Extensions.BasicConstraints.Id) { BasicConstraints bc = BasicConstraints.GetInstance(ext); Print(extab + "Basic Constraints Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " CA:" + bc.IsCA().ToString()); if (bc.PathLenConstraint != null) { Print(extab + " Path Length:" + bc.PathLenConstraint.ToString()); } else { Print(extab + " Path Length:Null"); } } else if (oid == X509Extensions.KeyUsage.Id) { KeyUsage keyu = KeyUsage.GetInstance(ext); Print(extab + "Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Usages:" + keyu.ToString()); } else if (oid == X509Extensions.ExtendedKeyUsage.Id) { ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext); Print(extab + "Extended Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Extended Key Usages:"); foreach (DerObjectIdentifier id in keyu.GetAllUsages()) { Print(extab + " " + id.Id); } } else if (oid == X509Extensions.SubjectKeyIdentifier.Id) { SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext); Print(extab + "Subject Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.AuthorityKeyIdentifier.Id) { AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext); Print(extab + "Authority Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.SubjectAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Subject Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.IssuerAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Issuer Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.AuthorityInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Authority Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.SubjectInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Subject Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.CrlDistributionPoints.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); CrlDistPoint keyu = CrlDistPoint.GetInstance(asn1Object); Print(extab + "Crl Distribution Points Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Distribution Points:"); foreach (DistributionPoint acc in keyu.GetDistributionPoints()) { if (acc.Reasons != null) { Print(extab + " Reasons:" + acc.Reasons.GetString()); } else { Print(extab + " Reasons:Null"); } if (acc.CrlIssuer != null) { Print(extab + " Crl Issuer:"); foreach (GeneralName gen in acc.CrlIssuer.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + ": " + gen.Name); } } else { Print(extab + " Crl Issuer:Null"); } Print(extab + " Distribution Point Name:"); if (acc.DistributionPointName.PointType == DistributionPointName.FullName) { GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name); foreach (GeneralName gen in sgen.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else { Print(extab + " Not Supported by OCT"); } } } } critical = false; foreach (string oid in CERT.GetNonCriticalExtensionOids()) { Print(" "); X509Extension ext = new X509Extension(true, CERT.GetExtensionValue(oid)); if (oid == X509Extensions.BasicConstraints.Id) { BasicConstraints bc = BasicConstraints.GetInstance(ext); Print(extab + "Basic Constraints Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " CA:" + bc.IsCA().ToString()); if (bc.PathLenConstraint != null) { Print(extab + " Path Length:" + bc.PathLenConstraint.ToString()); } else { Print(extab + " Path Length:Null"); } } else if (oid == X509Extensions.KeyUsage.Id) { KeyUsage keyu = KeyUsage.GetInstance(ext); Print(extab + "Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Usages:" + keyu.ToString()); } else if (oid == X509Extensions.ExtendedKeyUsage.Id) { ExtendedKeyUsage keyu = ExtendedKeyUsage.GetInstance(ext); Print(extab + "Extended Key Usage Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Extended Key Usages:"); foreach (DerObjectIdentifier id in keyu.GetAllUsages()) { Print(extab + " " + id.Id); } } else if (oid == X509Extensions.SubjectKeyIdentifier.Id) { SubjectKeyIdentifier keyu = SubjectKeyIdentifier.GetInstance(ext); Print(extab + "Subject Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.AuthorityKeyIdentifier.Id) { AuthorityKeyIdentifier keyu = AuthorityKeyIdentifier.GetInstance(ext); Print(extab + "Authority Key Identifier Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Key Identifier:"); Print(keyu.GetKeyIdentifier(), extab + " "); } else if (oid == X509Extensions.SubjectAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Subject Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.IssuerAlternativeName.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); GeneralNames keyu = GeneralNames.GetInstance(asn1Object); Print(extab + "Issuer Alternative Name Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " General Names:"); foreach (GeneralName gen in keyu.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else if (oid == X509Extensions.AuthorityInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Authority Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.SubjectInfoAccess.Id) { AuthorityInformationAccess keyu = AuthorityInformationAccess.GetInstance(ext); Print(extab + "Subject Information Access Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Access Descriptions:"); foreach (AccessDescription acc in keyu.GetAccessDescriptions()) { Print(extab + " Method:" + acc.AccessMethod.Id); GeneralName gen = acc.AccessLocation; string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " Access Location:" + tagname + "=" + gen.Name); } } else if (oid == X509Extensions.CrlDistributionPoints.Id) { Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(ext.Value); CrlDistPoint keyu = CrlDistPoint.GetInstance(asn1Object); Print(extab + "Crl Distribution Points Extension"); Print(extab + " Critical:" + critical.ToString()); Print(extab + " Distribution Points:"); foreach (DistributionPoint acc in keyu.GetDistributionPoints()) { if (acc.Reasons != null) { Print(extab + " Reasons:" + acc.Reasons.GetString()); } else { Print(extab + " Reasons:Null"); } if (acc.CrlIssuer != null) { Print(extab + " Crl Issuer:"); foreach (GeneralName gen in acc.CrlIssuer.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + ": " + gen.Name); } } else { Print(extab + " Crl Issuer:Null"); } Print(extab + " Distribution Point Name:"); if (acc.DistributionPointName.PointType == DistributionPointName.FullName) { GeneralNames sgen = GeneralNames.GetInstance(acc.DistributionPointName.Name); foreach (GeneralName gen in sgen.GetNames()) { string tagname = "Dns Name:"; if (gen.TagNo == GeneralName.EdiPartyName) { tagname = "Edi Party Name:"; } else if (gen.TagNo == GeneralName.IPAddress) { tagname = "IP Address:"; } else if (gen.TagNo == GeneralName.OtherName) { tagname = "Other Name:"; } else if (gen.TagNo == GeneralName.RegisteredID) { tagname = "Registered ID:"; } else if (gen.TagNo == GeneralName.Rfc822Name) { tagname = "Rfc822 Name:"; } else if (gen.TagNo == GeneralName.UniformResourceIdentifier) { tagname = "URI:"; } else if (gen.TagNo == GeneralName.X400Address) { tagname = "X400 Address:"; } else if (gen.TagNo == GeneralName.DirectoryName) { tagname = "Directory Name:"; } Print(extab + " " + tagname + " " + gen.Name); } } else { Print(extab + " Not Supported by OCT"); } } } } // Signature Print(" Signature Algorithm: " + cer.SignatureAlgorithm.FriendlyName + " " + (CERT.GetSignature().Length * 8) + " bit"); Print(CERT.GetSignature(), " "); Print(" SHA1 Fingerprint : "); Print(Sha1(CERT.GetEncoded()), " "); Print(" SHA224 Fingerprint : "); Print(Sha224(CERT.GetEncoded()), " "); Print(" SHA256 Fingerprint : "); Print(Sha256(CERT.GetEncoded()), " "); Print(" SHA384 Fingerprint : "); Print(Sha384(CERT.GetEncoded()), " "); Print(" SHA512 Fingerprint : "); Print(Sha512(CERT.GetEncoded()), " "); Print(" MD5 Fingerprint : "); Print(MD5(CERT.GetEncoded()), " "); Print("Issuer Base64:" + Convert.ToBase64String(CERT.IssuerDN.GetDerEncoded())); Print("Subject Base64:" + Convert.ToBase64String(CERT.SubjectDN.GetDerEncoded())); Print("Serial Base64:" + Convert.ToBase64String(CERT.SerialNumber.ToByteArray())); if (outputfile == "stdout") { Console.Read(); } else { str.Close(); } }
private byte[] MakeCertificateFromCSR(string CSR, AsymmetricCipherKeyPair rootKeyPair, X509Name rootSubject) { byte[] encoded; try { Pkcs10CertificationRequest pkcs10CertificationRequest = (Pkcs10CertificationRequest)(new PemReader(new StringReader(CSR))).ReadObject(); AsymmetricKeyParameter @private = rootKeyPair.Private; AsymmetricKeyParameter @public = rootKeyPair.Public; X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator(); x509V3CertificateGenerator.Reset(); if (this.SerialNumber != -9223372036854775808L) { x509V3CertificateGenerator.SetSerialNumber(new BigInteger(this.SerialNumber.ToString())); } else { DateTime now = DateTime.Now; x509V3CertificateGenerator.SetSerialNumber(new BigInteger(128, new Random(now.Millisecond + Environment.TickCount))); } x509V3CertificateGenerator.SetIssuerDN(rootSubject); x509V3CertificateGenerator.SetNotBefore(this.ValidFrom.ToUniversalTime()); x509V3CertificateGenerator.SetNotAfter(this.ValidTo.ToUniversalTime()); x509V3CertificateGenerator.SetSubjectDN(pkcs10CertificationRequest.GetCertificationRequestInfo().Subject); x509V3CertificateGenerator.SetPublicKey(pkcs10CertificationRequest.GetPublicKey()); x509V3CertificateGenerator.SetSignatureAlgorithm(string.Concat(this.SignatureAlgorithm.ToString(), "Encryption")); x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pkcs10CertificationRequest.GetPublicKey()))); x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(@public))); int extensionType = 0; Asn1EncodableVector asn1EncodableVectors = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (ExtensionInfo extension in this.Extensions.extensionInfo) { if (!extension.ExtendedKeyUsage) { extensionType |= (int)extension.ExtensionType; } if (!extension.ExtendedKeyUsage) { continue; } asn1EncodableVectors.Add(new Asn1Encodable[] { (Asn1Encodable)extension.ExtensionType }); } if (extensionType != 0) { x509V3CertificateGenerator.AddExtension(X509Extensions.KeyUsage, this.Extensions.KeyUsageIsCritical, new KeyUsage(extensionType)); } if (asn1EncodableVectors.Count > 0) { x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, this.Extensions.EnhancedKeyUsageIsCritical, ExtendedKeyUsage.GetInstance(new DerSequence(asn1EncodableVectors))); } X509Certificate x509Certificate = x509V3CertificateGenerator.Generate(@private, this.GetSecureRandom()); x509Certificate.Verify(@public); encoded = x509Certificate.GetEncoded(); } catch { throw; } return(encoded); }
private X509Certificate MakeCertificate(AsymmetricCipherKeyPair subjectKeyPair, X509Name certificateSubject, AsymmetricCipherKeyPair rootKeyPair, X509Name rootSubject, bool isRootCertificate, bool addAuthorityKeyIdentifier) { X509Certificate x509Certificate; try { AsymmetricKeyParameter @public = subjectKeyPair.Public; AsymmetricKeyParameter @private = rootKeyPair.Private; AsymmetricKeyParameter asymmetricKeyParameter = rootKeyPair.Public; X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator(); x509V3CertificateGenerator.Reset(); if (this.SerialNumber != -9223372036854775808L) { x509V3CertificateGenerator.SetSerialNumber(new BigInteger(this.SerialNumber.ToString())); } else { DateTime now = DateTime.Now; x509V3CertificateGenerator.SetSerialNumber(new BigInteger(128, new Random(now.Millisecond + Environment.TickCount))); } x509V3CertificateGenerator.SetIssuerDN(rootSubject); x509V3CertificateGenerator.SetNotBefore(this.ValidFrom.ToUniversalTime()); x509V3CertificateGenerator.SetNotAfter(this.ValidTo.ToUniversalTime()); x509V3CertificateGenerator.SetSubjectDN(certificateSubject); x509V3CertificateGenerator.SetPublicKey(@public); x509V3CertificateGenerator.SetSignatureAlgorithm(string.Concat(this.SignatureAlgorithm.ToString(), "Encryption")); int extensionType = 0; Asn1EncodableVector asn1EncodableVectors = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (ExtensionInfo extension in this.Extensions.extensionInfo) { if (!extension.ExtendedKeyUsage) { extensionType |= (int)extension.ExtensionType; } if (!extension.ExtendedKeyUsage) { continue; } asn1EncodableVectors.Add(new Asn1Encodable[] { (Asn1Encodable)extension.ExtensionType }); } bool keyUsageIsCritical = this.Extensions.KeyUsageIsCritical; if (isRootCertificate) { x509V3CertificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); extensionType |= 6; keyUsageIsCritical = true; } if (extensionType != 0) { x509V3CertificateGenerator.AddExtension(X509Extensions.KeyUsage, keyUsageIsCritical, new KeyUsage(extensionType)); } if (asn1EncodableVectors.Count > 0) { x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, this.Extensions.EnhancedKeyUsageIsCritical, ExtendedKeyUsage.GetInstance(new DerSequence(asn1EncodableVectors))); } x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(@public))); if (addAuthorityKeyIdentifier) { x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricKeyParameter))); } X509Certificate x509Certificate1 = x509V3CertificateGenerator.Generate(@private, this.GetSecureRandom()); x509Certificate1.Verify(asymmetricKeyParameter); x509Certificate = x509Certificate1; } catch { throw; } return(x509Certificate); }
public void CheckCertificate( int id, byte[] cert) { Asn1Object seq = Asn1Object.FromByteArray(cert); string dump = Asn1Dump.DumpAsString(seq); X509CertificateStructure obj = X509CertificateStructure.GetInstance(seq); TbsCertificateStructure tbsCert = obj.TbsCertificate; if (!tbsCert.Subject.ToString().Equals(subjects[id - 1])) { Fail("failed subject test for certificate id " + id + " got " + tbsCert.Subject.ToString()); } if (tbsCert.Version >= 3) { X509Extensions ext = tbsCert.Extensions; if (ext != null) { foreach (DerObjectIdentifier oid in ext.ExtensionOids) { X509Extension extVal = ext.GetExtension(oid); Asn1Object extObj = Asn1Object.FromByteArray(extVal.Value.GetOctets()); if (oid.Equals(X509Extensions.SubjectKeyIdentifier)) { SubjectKeyIdentifier.GetInstance(extObj); } else if (oid.Equals(X509Extensions.KeyUsage)) { KeyUsage.GetInstance(extObj); } else if (oid.Equals(X509Extensions.ExtendedKeyUsage)) { ExtendedKeyUsage ku = ExtendedKeyUsage.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)ku.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { KeyPurposeID.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.SubjectAlternativeName)) { GeneralNames gn = GeneralNames.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { GeneralName.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.IssuerAlternativeName)) { GeneralNames gn = GeneralNames.GetInstance(extObj); Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object(); for (int i = 0; i != sq.Count; i++) { GeneralName.GetInstance(sq[i]); } } else if (oid.Equals(X509Extensions.CrlDistributionPoints)) { CrlDistPoint p = CrlDistPoint.GetInstance(extObj); DistributionPoint[] points = p.GetDistributionPoints(); for (int i = 0; i != points.Length; i++) { // do nothing } } else if (oid.Equals(X509Extensions.CertificatePolicies)) { Asn1Sequence cp = (Asn1Sequence)extObj; for (int i = 0; i != cp.Count; i++) { PolicyInformation.GetInstance(cp[i]); } } else if (oid.Equals(X509Extensions.AuthorityKeyIdentifier)) { AuthorityKeyIdentifier.GetInstance(extObj); } else if (oid.Equals(X509Extensions.BasicConstraints)) { BasicConstraints.GetInstance(extObj); } else { //Console.WriteLine(oid.Id); } } } } }
private static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, int keyStrength = 2048) { // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); // Serial Number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name var x500DistinguishedName = new X509Name("CN=" + subjectName); certificateGenerator.SetIssuerDN(x500DistinguishedName); certificateGenerator.SetSubjectDN(x500DistinguishedName); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // Subject Public Key var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Generating the Certificate var issuerKeyPair = subjectKeyPair; ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random); certificateGenerator.AddExtension( X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certificateGenerator.AddExtension( X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment)); certificateGenerator.AddExtension( X509Extensions.ExtendedKeyUsage, false, ExtendedKeyUsage.GetInstance(new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth))); // selfsign certificate var certificate = certificateGenerator.Generate(signatureFactory); // correcponding private key var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new X509Certificate2(certificate.GetEncoded()) { FriendlyName = $"{subjectName} self-signed" }; var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } var rsa = RsaPrivateKeyStructure.GetInstance(seq); var rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); return(x509); }
private static CertBundle MakeCertInternal( string issuerName, string subjectName, bool isCA, AsymmetricCipherKeyPair signerKey = null, AsymmetricCipherKeyPair certKey = null, int pathLengthConstraint = 0) { const int keyStrength = 256; CryptoApiRandomGenerator rg = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(rg); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // make a new ECC key pair. The pubKey will go in the cert. The private key may or may // not be used for signing, depending on whether the caller provides a signing key. KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair newKey = keyPairGenerator.GenerateKeyPair(); if (certKey != null) { newKey = certKey; } certGen.SetPublicKey(newKey.Public); BigInteger serialNumber = new BigInteger(new byte[] { 2, 3, 4 }); certGen.SetSerialNumber(serialNumber); certGen.SetIssuerDN(new X509Name(issuerName)); certGen.SetSubjectDN(new X509Name(subjectName)); DateTime notBefore = DateTime.UtcNow.Date; DateTime notAfter = notBefore + new TimeSpan(365, 0, 0, 0); certGen.SetNotBefore(notBefore); certGen.SetNotAfter(notAfter); if (pathLengthConstraint != 0) { // then we want it to be a CA. Using this constructor sets CA true AND sets the path length certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(pathLengthConstraint)); } else { certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true, ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPServerAuth))); }; // Sign the cert var signingKey = (signerKey != null) ? signerKey : newKey; ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHECDSA", signingKey.Private, random); var certificate = certGen.Generate(signatureFactory); // and return the bundle var bundle = new CertBundle() { Certificate = certificate, KeyPair = newKey }; return(bundle); }
/// <summary> /// Make a new Alias Cert. If refresh=false, a new DevID and Alias are created. If refresh=true /// then just the Alias is created and re-certified using the stored DevID key. /// </summary> /// <param name="refresh"></param> /// <returns></returns> internal DeviceBundle MakeAliasCert(bool refresh, int fwidSeed) { DateTime now = DateTime.Now; byte[] fwid = Helpers.HashData(new byte[1] { (byte)fwidSeed }, 0, 1); const int keyStrength = 256; CryptoApiRandomGenerator rg = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(rg); KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair devIdKey = null; if (refresh) { devIdKey = (AsymmetricCipherKeyPair)Helpers.ReadPemObject(ToPath(Program.DeviceIDPrivate)); } else { devIdKey = keyPairGenerator.GenerateKeyPair(); } // test - remove var oids = new List <Object>() { X509Name.UnstructuredName }; var values = new List <Object>() { "ljkljljklkjlkjlkjlkjlkjlkjlkjlkjlkjljklkjlkjlkjlkjljk" }; X509Name name = new X509Name(oids, values); AsymmetricCipherKeyPair aliasKey = keyPairGenerator.GenerateKeyPair(); // make a string name based on DevID public. Note that the authoritative information // is encoded in the RIoT-extension: this is just for quick-and-dirty device identification. var pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(devIdKey.Public); byte[] pubEncoded = pubInfo.GetDerEncoded(); var pubHashed = Helpers.HashData(pubEncoded, 0, pubEncoded.Length); var shortNameBytes = Helpers.CopyArray(pubHashed, 0, 8); var shortNameString = Helpers.Hexify(shortNameBytes); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); var serialNumber = new byte[8]; rg.NextBytes(serialNumber); serialNumber[0] &= 0x7F; certGen.SetSerialNumber(new BigInteger(serialNumber)); // The important name-related stuff is encoded in the RIoT extension certGen.SetIssuerDN(new X509Name($"CN=[I]DevID:{shortNameString}, O=MSR_TEST, C=US")); // test REMOVE //certGen.SetSubjectDN(name); certGen.SetSubjectDN(new X509Name($"CN=[S]DevID:{shortNameString}, O=MSR_TEST, C=US")); certGen.SetNotBefore(now); certGen.SetNotAfter(now + new TimeSpan(365 * 10, 0, 0, 0, 0)); certGen.SetPublicKey(aliasKey.Public); // Add the extensions (todo: not sure about KeyUsage.DigitalSiganture certGen.AddExtension(X509Extensions.ExtendedKeyUsage, true, ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPClientAuth))); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature)); AddRIoTExtension(certGen, fwid, devIdKey); // sign it ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHECDSA", devIdKey.Private, random); var certificate = certGen.Generate(signatureFactory); // and return the bundle DeviceBundle bundle = new DeviceBundle { AliasCert = certificate, DeviceIDPublic = devIdKey.Public, AliasKeyPair = aliasKey }; // Just the AliasCert Helpers.WritePEMObject(ToPath(Program.AliasCert), bundle.AliasCert); // The Alias Key Pair Helpers.WritePEMObject(ToPath(Program.AliasKey), bundle.AliasKeyPair); // The encoded DevID Helpers.WritePEMObject(ToPath(Program.DeviceIDPublic), bundle.DeviceIDPublic); // DeviceIDPrivate (just for the update demo) Helpers.WritePEMObject(ToPath(Program.DeviceIDPrivate), devIdKey.Private); return(bundle); }
/// <summary> /// Qualification of extension by type /// </summary> /// <param name="asn1Encodable"></param> /// <returns></returns> private System.Security.Cryptography.X509Certificates.X509Extension QualificationExtension(Asn1Encodable asn1Encodable) { Asn1Sequence s = Asn1Sequence.GetInstance(asn1Encodable.ToAsn1Object()); if (s.Count < 2 || s.Count > 3) { throw new ArgumentException("Bad sequence size: " + s.Count); } DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(s[0].ToAsn1Object()); bool isCritical = s.Count == 3 && DerBoolean.GetInstance(s[1].ToAsn1Object()).IsTrue; Asn1OctetString octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object()); var extension = new System.Security.Cryptography.X509Certificates.X509Extension(new Oid(oid.Id), octets.GetOctets(), isCritical); var value = Asn1Object.FromByteArray(octets.GetOctets()); switch (extension.Oid.Value) { case OidExtensions.SubjectKeyIdentifier: var spki = Asn1OctetString.GetInstance(value).GetOctets(); extension = new X509SubjectKeyIdentifierExtension(spki, isCritical); break; case OidExtensions.ExtKeyUsage: var bcEKU = ExtendedKeyUsage.GetInstance(value); var collectionFlags = new OidCollection(); foreach (DerObjectIdentifier item in bcEKU.GetAllUsages()) { collectionFlags.Add(new Oid(item.Id)); } extension = new X509EnhancedKeyUsageExtension(collectionFlags, isCritical); break; case OidExtensions.KeyUsage: var bitString = DerBitString.GetInstance(value); byte[] data = bitString.GetBytes(); var keyUsage = data.Length == 1 ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff); extension = new X509KeyUsageExtension((X509KeyUsageFlags)keyUsage, isCritical); break; case OidExtensions.BasicConstraints: var bcBC = BasicConstraints.GetInstance(value); extension = new X509BasicConstraintsExtension(bcBC.IsCA(), true, bcBC.PathLenConstraint.IntValue, isCritical); break; case OidExtensions.TemplateV2: extension = new X509TemplateExtensionV2(octets.GetOctets(), isCritical); break; case OidExtensions.TemplateV1: extension = new X509TemplateExtensionV1(octets.GetOctets(), isCritical); break; default: break; } return(extension); }