private string GetSubjectKeyIdentifier(BCX509Certificate2 certificate) { //SubjectKeyIdentifier ski = (certificate.Extensions["2.5.29.14"] as SubjectKeyIdentifier); SubjectKeyIdentifier ski = SubjectKeyIdentifier.GetInstance(certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(X509Extensions.SubjectKeyIdentifier)); return((ski == null) ? String.Empty : Hex.ToHexString(ski.GetKeyIdentifier())); }
private AsymmetricKeyParameter GetSenderPublicKey( AsymmetricKeyParameter receiverPrivateKey, OriginatorIdentifierOrKey originator) { OriginatorPublicKey opk = originator.OriginatorPublicKey; if (opk != null) { return(GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, opk)); } OriginatorID origID = new OriginatorID(); Asn1.Cms.IssuerAndSerialNumber iAndSN = originator.IssuerAndSerialNumber; if (iAndSN != null) { origID.Issuer = iAndSN.Name; origID.SerialNumber = iAndSN.SerialNumber.Value; } else { SubjectKeyIdentifier ski = originator.SubjectKeyIdentifier; origID.SubjectKeyIdentifier = ski.GetKeyIdentifier(); } return(GetPublicKeyFromOriginatorID(origID)); }
private static void AddSubjectKeyIdentifier(X509V3CertificateGenerator certificateGenerator, AsymmetricCipherKeyPair subjectKeyPair) { var subjectKeyIdentifierExtension = new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)); certificateGenerator.AddExtension( X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension); }
static void SetSubjectPublicKey(X509V3CertificateGenerator generator, AsymmetricKeyParameter subjectPublic) { //Subject Key Identifier var subjectKeyIdentifier = new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectPublic)); generator.AddExtension( X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier); }
/// <summary> /// Determines whether [is the same] [the specified keyto test]. /// </summary> /// <param name="KeytoTest">The keyto test.</param> /// <returns></returns> public bool IsTheSame(SubjectPublicKeyInfo KeytoTest) { SubjectKeyIdentifier key = SubjectKeyIdentifier.CreateSha1KeyIdentifier(KeytoTest); if (keyIdentifier.SequenceEqual(key.GetKeyIdentifier())) { return(true); } return(false); }
//TODO change to functors public static X509Certificate CreateX509Certificate2(AsymmetricCipherKeyPair kp, string issuer, DateTime notBefore, DateTime notAfter, KeyType keyUsage, string filename, string password) { var random = new SecureRandom(); var sf = new Asn1SignatureFactory(HashAlg.SHA256withRSA.ToString(), kp.Private, random); var gen = new X509V3CertificateGenerator(); var serial = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); gen.SetSerialNumber(serial); var subject = new X509Name(issuer); gen.SetIssuerDN(subject); gen.SetSubjectDN(subject); gen.SetNotBefore(notBefore); gen.SetNotAfter(notAfter); gen.SetPublicKey(kp.Public); gen.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public)); gen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier); var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subject)), serial); gen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); ////gen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection)); switch (keyUsage) { case KeyType.Signature: //signature gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.NonRepudiation)); break; case KeyType.Authentication: //authentication gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature)); break; case KeyType.Encryption: //encryption gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.KeyEncipherment | X509KeyUsage.KeyAgreement)); break; default: gen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.KeyEncipherment | X509KeyUsage.DigitalSignature)); break; } var bouncyCert = gen.Generate(sf); bouncyCert.CheckValidity(); bouncyCert.Verify(kp.Public); var store = new Pkcs12Store(); var certificateEntry = new X509CertificateEntry(bouncyCert); store.SetCertificateEntry(bouncyCert.SubjectDN.ToString(), certificateEntry); store.SetKeyEntry(bouncyCert.SubjectDN.ToString(), new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry }); using (var sw = File.Create(filename)) store.Save(sw, password.ToCharArray(), random); return(bouncyCert); }
/// <summary> /// Create SKID extension from an X509Extension /// </summary> /// <param name="Extension">X509 extension</param> /// <remarks> /// The work is done in the base class /// </remarks> public subjectKeyIdentifier(X509Extension Extension) : base(Extension.IsCritical) { base.oid = X509Extensions.SubjectKeyIdentifier; base.name = "SubjectKeyIdentifier"; base.displayName = "Subject Key Identifier"; SubjectKeyIdentifier skid = SubjectKeyIdentifier.GetInstance(Extension); keyIdentifier = skid.GetKeyIdentifier(); }
/// <summary> /// Create a self signed certificate with bouncy castle. /// </summary> public static X509Certificate2 GenerateCertificate( string subjectName, Action <X509V3CertificateGenerator> modifyGenerator, string signatureAlgorithm = "SHA256WITHRSA", int publicKeyLength = 2048) { if (string.IsNullOrEmpty(subjectName)) { subjectName = "NuGetTest"; } var random = new SecureRandom(); var pairGenerator = new RsaKeyPairGenerator(); var genParams = new KeyGenerationParameters(random, publicKeyLength); pairGenerator.Init(genParams); var pair = pairGenerator.GenerateKeyPair(); // Create cert var certGen = new X509V3CertificateGenerator(); certGen.SetSubjectDN(new X509Name($"CN={subjectName}")); certGen.SetIssuerDN(new X509Name($"CN={subjectName}")); certGen.SetNotAfter(DateTime.UtcNow.Add(TimeSpan.FromHours(1))); certGen.SetNotBefore(DateTime.UtcNow.Subtract(TimeSpan.FromHours(1))); certGen.SetPublicKey(pair.Public); var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certGen.SetSerialNumber(serialNumber); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public)); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.KeyCertSign)); certGen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); // Allow changes modifyGenerator?.Invoke(certGen); var issuerPrivateKey = pair.Private; var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerPrivateKey, random); var certificate = certGen.Generate(signatureFactory); var certResult = new X509Certificate2(certificate.GetEncoded()); #if IS_DESKTOP certResult.PrivateKey = DotNetUtilities.ToRSA(pair.Private as RsaPrivateCrtKeyParameters); #endif return(certResult); }
protected void AddSubjectKeyIdentifier(X509V3CertificateGenerator certificateGenerator, AsymmetricCipherKeyPair subjectKeyPair) { // Subject Key Identifier, usado para facilitar a validação de certificados. // Em CA são gerados, em geral, a partir da sua chave pública. // Secção 4.2.1.2 do http://www.ietf.org/rfc/rfc3280.txt var subjectKeyIdentifierExtension = new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)); certificateGenerator.AddExtension( X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension); }
public X509Certificate2 CreateCertificate() { X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); var subjectDN = new X509Name(String.Format("CN={0}", SubjectName)); var issuerDN = subjectDN; AsymmetricKeyParameter privateKey; AsymmetricKeyParameter publicKey; RsaKeysGenerator(out privateKey, out publicKey); var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey), new GeneralNames(new GeneralName(issuerDN)), SerialNumber); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); certificateGenerator.SetSerialNumber(SerialNumber); certificateGenerator.SetNotBefore(ValidFrom); certificateGenerator.SetNotAfter(ValidTill); certificateGenerator.SetSignatureAlgorithm(SignatureAlgorithm); certificateGenerator.SetPublicKey(publicKey); certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier); certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); var certificate = certificateGenerator.Generate(privateKey, Random); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); var x509 = new X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters 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); }
/// <summary> /// Create a self signed certificate. /// </summary> public static X509Certificate2 GenerateCertificate( string subjectName, AsymmetricCipherKeyPair keyPair) { if (string.IsNullOrEmpty(subjectName)) { subjectName = "NuGetTest"; } var certGen = new X509V3CertificateGenerator(); certGen.SetSubjectDN(new X509Name($"CN={subjectName}")); certGen.SetIssuerDN(new X509Name($"CN={subjectName}")); certGen.SetNotAfter(DateTime.UtcNow.Add(TimeSpan.FromHours(1))); certGen.SetNotBefore(DateTime.UtcNow.Subtract(TimeSpan.FromHours(1))); certGen.SetPublicKey(keyPair.Public); var random = new SecureRandom(); var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certGen.SetSerialNumber(serialNumber); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public)); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.KeyCertSign)); certGen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); var usages = new[] { KeyPurposeID.IdKPCodeSigning }; certGen.AddExtension( X509Extensions.ExtendedKeyUsage.Id, critical: true, extensionValue: new ExtendedKeyUsage(usages)); var issuerPrivateKey = keyPair.Private; var signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivateKey, random); var certificate = certGen.Generate(signatureFactory); var certResult = new X509Certificate2(certificate.GetEncoded()); #if IS_DESKTOP certResult.PrivateKey = DotNetUtilities.ToRSA(keyPair.Private as RsaPrivateCrtKeyParameters); #endif return(certResult); }
private bool rqstInfo() { lbSubject.Text = "Subject: " + Utility.OrderDN(parser.Subject.ToString()); if (parser.SubjectAltNames != null) { lbAltNames.Text = "Alt Names: " + parser.SubjectAltNames.ToString(); } else { lbAltNames.Text = "Alt Names: none"; } // Key lbKeyType.Text = "Key: " + parser.SubjectPublicKeyDescription; // Tests // 1. Verify request signature if (parser.IsValid) { setStatus("Valid Signature", true); } else { setStatus("Invalid Signature", false); return(false); } // 2. Verify Request Subject matches Original Cert Subject if (!parser.Subject.Equivalent(origCert.SubjectDN)) { setStatus("Subject does not match original certificate", false); return(false); } // 3. Verify that Public Key is not same as that in Original Cert SubjectKeyIdentifier skid = new SubjectKeyIdentifier(parser.SubjectPublicKeyInfo); SubjectKeyIdentifier okid = new SubjectKeyIdentifier(origCert.CertificateStructure.SubjectPublicKeyInfo); if (skid.Equals(okid)) { setStatus("Public key is the same as original certificate", false); return(false); } return(true); }
public override void PerformTest() { SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.GetInstance( Asn1Object.FromByteArray(pubKeyInfo)); SubjectKeyIdentifier ski = SubjectKeyIdentifier.CreateSha1KeyIdentifier(pubInfo); if (!Arrays.AreEqual(shaID, ski.GetKeyIdentifier())) { Fail("SHA-1 ID does not match"); } ski = SubjectKeyIdentifier.CreateTruncatedSha1KeyIdentifier(pubInfo); if (!Arrays.AreEqual(shaTruncID, ski.GetKeyIdentifier())) { Fail("truncated SHA-1 ID does not match"); } }
/// <summary> /// Returns true if a KeyID matches one in a certificate /// </summary> /// <param name="KeyId">KeyIDvalue to test</param> /// <param name="Certificate">Certificate to test</param> /// <param name="IdType">Authority or Subject KeyID</param> /// <returns> /// True for a key match /// </returns> /// <exception cref="System.ApplicationException">Authority KeyID extension not found in certificate /// or /// Subject KeyID extension not found in certificate</exception> public static bool TestKeyId(byte[] KeyId, X509Certificate Certificate, KeyIdType IdType) { X509Extensions extensions = Certificate.GetExtensions(); X509Extension ext; AuthorityKeyIdentifier akid; SubjectKeyIdentifier skid; switch (IdType) { case KeyIdType.AKID: ext = extensions.GetExtension(X509Extensions.AuthorityKeyIdentifier); if (ext == null) { throw new ApplicationException("Authority KeyID extension not found in certificate"); } else { akid = AuthorityKeyIdentifier.GetInstance(ext); if (KeyId == akid.GetKeyIdentifier()) { return(true); } } break; case KeyIdType.SKID: ext = extensions.GetExtension(X509Extensions.SubjectKeyIdentifier); if (ext == null) { throw new ApplicationException("Subject KeyID extension not found in certificate"); } else { skid = SubjectKeyIdentifier.GetInstance(ext); if (KeyId == skid.GetKeyIdentifier()) { return(true); } } break; } return(false); }
private static Org.BouncyCastle.X509.X509Certificate GenerateCertificate(SecureRandom random, string subjectDN, AsymmetricCipherKeyPair subjectKeyPair, BigInteger subjectSerialNumber, IEnumerable <string> subjectAlternativeNames, string issuerDN, AsymmetricCipherKeyPair issuerKeyPair, int keyUsages, List <KeyPurposeID> extendedKeyUsages, int yearsValid, string signatureAlgorithmName) { var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.SetSerialNumber(subjectSerialNumber); var signatureFactory = new Asn1SignatureFactory(signatureAlgorithmName, issuerKeyPair.Private, random); var issuerDN509 = new X509Name(issuerDN); certificateGenerator.SetIssuerDN(issuerDN509); var subjectDN509 = new X509Name(subjectDN); certificateGenerator.SetSubjectDN(subjectDN509); var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(yearsValid); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); certificateGenerator.SetPublicKey(subjectKeyPair.Public); var subjectKeyIdentifierExtension = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)); certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifierExtension); certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); // http://tools.ietf.org/html/rfc5280#section-4.2.1.3 if (keyUsages > 0) { certificateGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(keyUsages)); } certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedKeyUsages.ToArray())); AddSubjectAlternativeNames(certificateGenerator, subjectAlternativeNames); var certificate = certificateGenerator.Generate(signatureFactory); return(certificate); }
// TODO generalize public virtual X509Certificate BuildAuthorizedOCSPResponderCert() { X509Name subjectDnName = new X509Name(subjectDN); BigInteger certSerialNumber = new BigInteger(Convert.ToString(SystemUtil.GetTimeBasedSeed())); // Using the current timestamp as the certificate serial number ISignatureFactory contentSigner = new Asn1SignatureFactory(signatureAlgorithm, (AsymmetricKeyParameter)signingKey); X509V3CertificateGenerator certBuilder = new X509V3CertificateGenerator(); certBuilder.SetIssuerDN(signingCert.SubjectDN); certBuilder.SetSerialNumber(certSerialNumber); certBuilder.SetNotBefore(startDate); certBuilder.SetNotAfter(endDate); certBuilder.SetSubjectDN(subjectDnName); certBuilder.SetPublicKey(publicKey); // TODO generalize extensions setting // Extensions -------------------------- bool ca = true; AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(ca), certBuilder); AddExtension(OcspObjectIdentifiers.PkixOcspNocheck, false, Org.BouncyCastle.Asn1.DerNull.Instance, certBuilder); AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.NonRepudiation), certBuilder); AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPOcspSigning), certBuilder); SubjectPublicKeyInfo issuerPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(signingCert.GetPublicKey()); AuthorityKeyIdentifier authKeyIdentifier = new AuthorityKeyIdentifier(issuerPublicKeyInfo); AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authKeyIdentifier, certBuilder); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifier(subjectPublicKeyInfo); AddExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier, certBuilder); // ------------------------------------- return(certBuilder.Generate(contentSigner)); }
/// <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 <string>(string.Empty); return; } SubjectKeyIdentifier keyId = SubjectKeyIdentifier.GetInstance(exValue); PolicyValue = new PolicyValue <string>(PolicyUtils.CreateByteStringRep(keyId.GetKeyIdentifier())); }
public static X509Certificate2 CreateX509Certificate2(AsymmetricCipherKeyPair kp) { var random = new SecureRandom(); var sf = new Asn1SignatureFactory(HashAlg.SHA256withRSA.ToString(), kp.Private, random); var gen = new X509V3CertificateGenerator(); gen.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random)); var subject = new X509Name("CN=" + "ebics.org"); gen.SetSubjectDN(subject); gen.SetIssuerDN(subject); var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(10); gen.SetNotBefore(notBefore); gen.SetNotAfter(notAfter); gen.SetPublicKey(kp.Public); var bouncyCert = gen.Generate(sf); var authorityKeyIdentifier = new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subject)), bouncyCert.SerialNumber); gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier); var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public)); gen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); gen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); var store = new Pkcs12Store(); var certificateEntry = new X509CertificateEntry(bouncyCert); store.SetCertificateEntry(bouncyCert.SubjectDN.ToString(), certificateEntry); store.SetKeyEntry(bouncyCert.SubjectDN.ToString(), new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry }); const string pwd = "password"; var stream = new MemoryStream(); store.Save(stream, pwd.ToCharArray(), random); var msCert = new X509Certificate2(stream.ToArray(), pwd, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return(msCert); }
public static SubjectKeyIdentifier retrieveSubjectKeyIdentifier(X509Certificate x509Certificate) { SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifier(); X509Extension x509Extension = x509Certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(new DerObjectIdentifier(OIDS.OID_SUBJECT_KEY_IDENTIFIER_EXTENSION)); if (x509Extension != null) { Org.BouncyCastle.Asn1.X509.SubjectKeyIdentifier subjectKeyIdentifierExtension = Org.BouncyCastle.Asn1.X509.SubjectKeyIdentifier.GetInstance(x509Extension); subjectKeyIdentifier.HasSubjectKeyIdentifierExtension = true; subjectKeyIdentifier.IsCritical = x509Extension.IsCritical; subjectKeyIdentifier.keyIdentifier = subjectKeyIdentifierExtension.GetKeyIdentifier(); //todo: add issuer and serial fields. } else { subjectKeyIdentifier.HasSubjectKeyIdentifierExtension = false; } return(subjectKeyIdentifier); }
private CertificateUrlTemplateBindModel BuildUrlTemplateBindModel( string name, string subject, string issuer, SubjectKeyIdentifier keyId, AuthorityKeyIdentifier issuerId, BigInteger serialNumber, DateTime notBefore, DateTime notAfter) { string idSubject = Hex.ToHexString(new BigInteger(keyId.GetKeyIdentifier()).ToByteArray()); string idIssuer = Hex.ToHexString(new BigInteger(issuerId.GetKeyIdentifier()).ToByteArray()); return(new CertificateUrlTemplateBindModel( name, subject, issuer, idSubject, idIssuer, serialNumber.ToString(), notBefore, notAfter)); }
private AsymmetricKeyParameter GetSenderPublicKey(AsymmetricKeyParameter receiverPrivateKey, OriginatorIdentifierOrKey originator) { OriginatorPublicKey originatorPublicKey = originator.OriginatorPublicKey; if (originatorPublicKey != null) { return(this.GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, originatorPublicKey)); } OriginatorID originatorID = new OriginatorID(); Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerAndSerialNumber = originator.IssuerAndSerialNumber; if (issuerAndSerialNumber != null) { originatorID.Issuer = issuerAndSerialNumber.Name; originatorID.SerialNumber = issuerAndSerialNumber.SerialNumber.Value; } else { SubjectKeyIdentifier subjectKeyIdentifier = originator.SubjectKeyIdentifier; originatorID.SubjectKeyIdentifier = subjectKeyIdentifier.GetKeyIdentifier(); } return(this.GetPublicKeyFromOriginatorID(originatorID)); }
///// <summary> ///// Create a new certificate ///// </summary> ///// <param name="issuer">Issuer certificate, if null then self-sign</param> ///// <param name="subjectName">Subject name</param> ///// <param name="serialNumber">Serial number of certificate, if null then will generate a new one</param> ///// <param name="keySize">Size of RSA key</param> ///// <param name="notBefore">Start date of certificate</param> ///// <param name="notAfter">End date of certificate</param> ///// <param name="extensions">Array of extensions, if null then no extensions</param> ///// <param name="hashAlgorithm">Specify the signature hash algorithm</param> ///// <returns>The created X509 certificate</returns> public static SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 issuer, SystemX509.X500DistinguishedName subjectName, byte[] serialNumber, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore, DateTime notAfter, SystemX509.X509ExtensionCollection extensions) { SecureRandom random = new SecureRandom(); X509V3CertificateGenerator builder = new X509V3CertificateGenerator(); AsymmetricCipherKeyPair bcSubjectKey = CreateRSAKey(keySize, random); AsymmetricCipherKeyPair bcSignKey = issuer == null ? bcSubjectKey : issuer.GetBCPrivateKey(); if (bcSignKey == null) { throw new ArgumentException("issuer"); } X509Name issuerNameObj = issuer == null?X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData)) : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData)); X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData)); BigInteger subjectSerial = new BigInteger(1, serialNumber != null ? serialNumber : Guid.NewGuid().ToByteArray()); BigInteger issuerSerial = issuer == null ? subjectSerial : new BigInteger(1, issuer.GetSerialNumber()); builder.SetIssuerDN(issuerNameObj); builder.SetSubjectDN(subjectNameObj); builder.SetSerialNumber(subjectSerial); builder.SetNotBefore(notBefore.ToUniversalTime()); builder.SetNotAfter(notAfter.ToUniversalTime()); builder.SetPublicKey(bcSubjectKey.Public); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSignKey.Public); AuthorityKeyIdentifier authKeyId = new AuthorityKeyIdentifier(info, new GeneralNames(new GeneralName(issuerNameObj)), issuerSerial); SubjectKeyIdentifier subjectKeyid = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSubjectKey.Public)); builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authKeyId); builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, true, subjectKeyid); if (extensions != null) { foreach (SystemX509.X509Extension ext in extensions) { if (!ext.Oid.Value.Equals(X509Extensions.AuthorityKeyIdentifier.Id) && !ext.Oid.Value.Equals(X509Extensions.SubjectKeyIdentifier.Id) && !ext.Oid.Value.Equals(szOID_AUTHORITY_KEY_IDENTIFIER2)) { Asn1InputStream istm = new Asn1InputStream(ext.RawData); Asn1Object obj = istm.ReadObject(); builder.AddExtension(ext.Oid.Value, ext.Critical, obj); } } } X509Certificate cert = builder.Generate(CreateSignatureFactory(hashAlgorithm, bcSignKey, random)); Pkcs12StoreBuilder pkcs = new Pkcs12StoreBuilder(); Pkcs12Store store = pkcs.Build(); X509CertificateEntry entry = new X509CertificateEntry(cert); store.SetCertificateEntry("main", entry); AsymmetricKeyEntry key_entry = new AsymmetricKeyEntry(bcSubjectKey.Private); store.SetKeyEntry("main", key_entry, new[] { entry }); MemoryStream stm = new MemoryStream(); store.Save(stm, new char[0], new SecureRandom()); return(new SystemX509.X509Certificate2(stm.ToArray(), String.Empty, SystemX509.X509KeyStorageFlags.Exportable)); }
public static X509Certificate2 IssueCertificate( string basename, string password, DistinguishedName dn, CertificateType certtype, DateTime notBefore, DateTime notAfter) { var certificateGenerator = new X509V3CertificateGenerator(); var privateOutputPath = ""; var publicOutputPath = ""; /* Prepare output directories */ if (certtype == CertificateType.AuthorityCertificate) { privateOutputPath = AuthorityPrivateCertificatesPath; publicOutputPath = AuthorityPublicCertificatesPath; } else if (certtype == CertificateType.ServerCertificate) { privateOutputPath = ServerPrivateCertificatesPath; publicOutputPath = ServerPublicCertificatesPath; } else { privateOutputPath = UserPrivateCertificatesPath; publicOutputPath = UserPublicCertificatesPath; } /* Certificate Asymmetric Keys */ CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048); RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); /* Certificate Serial Number */ BigInteger serialNumber = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); /* Certificate Date Constrains */ certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); /* Certificate Issuer and Subject DN */ string issuerName = IssuerDN.ToString(); if (certtype == CertificateType.AuthorityCertificate) { /* A Certification Authority is a self signed certificate */ issuerName = dn.ToString(); } certificateGenerator.SetSubjectDN(new X509Name(dn.ToString())); certificateGenerator.SetIssuerDN(new X509Name(issuerName)); /* Certificate Alternative Names */ if (dn.AlternativeNames != null && dn.AlternativeNames.Any()) { var subjectAlternativeNamesExtension = new DerSequence( dn.AlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name)) .ToArray <Asn1Encodable> ()); certificateGenerator.AddExtension( X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension); } /* Certificate Keys Usage */ var keyUsageFlags = KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment | KeyUsage.DataEncipherment | KeyUsage.DigitalSignature; if (certtype == CertificateType.AuthorityCertificate || certtype == CertificateType.ServerCertificate) { keyUsageFlags |= KeyUsage.CrlSign | KeyUsage.NonRepudiation; } certificateGenerator.AddExtension( X509Extensions.KeyUsage.Id, false, new KeyUsage(keyUsageFlags)); /* Certificate Extended Key Usages */ if (certtype != CertificateType.AuthorityCertificate) { KeyPurposeID[] extendedUsages = null; if (certtype == CertificateType.ServerCertificate) { extendedUsages = new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth, }; } else { extendedUsages = new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPEmailProtection, }; } certificateGenerator.AddExtension( X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(extendedUsages)); } /* Certificate Authority Key Identifier */ /* A Certification Authority is a self signed certificate */ AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;; if (certtype != CertificateType.AuthorityCertificate) { issuerKeyPair = DotNetUtilities.GetKeyPair(IssuerCertificate.PrivateKey); } var issuerPKIFactory = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public); var generalNames = new GeneralNames( new GeneralName(new X509Name(issuerName))); /* A Certification Authority is a self signed certificate */ BigInteger issuerSerialNumber = serialNumber; if (certtype != CertificateType.AuthorityCertificate) { issuerSerialNumber = new BigInteger(IssuerCertificate.GetSerialNumber()); } var authorityKIExtension = new AuthorityKeyIdentifier( issuerPKIFactory, generalNames, issuerSerialNumber); certificateGenerator.AddExtension( X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKIExtension); /* Certificate Subject Key Identifier */ var subjectPKIFactory = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public); var subjectKIExtension = new SubjectKeyIdentifier(subjectPKIFactory); certificateGenerator.AddExtension( X509Extensions.SubjectKeyIdentifier.Id, false, subjectKIExtension); /* Certificate Basic constrains */ bool isCertificateAuthority = false; if (certtype == CertificateType.AuthorityCertificate) { isCertificateAuthority = true; } var basicConstrains = new BasicConstraints(isCertificateAuthority); certificateGenerator.AddExtension( X509Extensions.BasicConstraints.Id, true, basicConstrains); /* Generate BouncyCastle Certificate */ ISignatureFactory signatureFactory = new Asn1SignatureFactory( "SHA512WITHRSA", issuerKeyPair.Private, random ); /* Generate P12 Certificate Store and write to disk*/ var store = new Pkcs12Store(); var certificate = certificateGenerator.Generate(signatureFactory); var certificateEntry = new X509CertificateEntry(certificate); var stream = new MemoryStream(); store.SetCertificateEntry(dn.ToString(), certificateEntry); store.SetKeyEntry(dn.ToString(), new AsymmetricKeyEntry(subjectKeyPair.Private), new [] { certificateEntry }); store.Save(stream, password.ToCharArray(), random); File.WriteAllBytes(privateOutputPath + basename + ".p12", stream.ToArray()); /* Convert to Microsoft X509Certificate2 and write to disk pfx and der files */ var convertedCertificate = new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); File.WriteAllBytes(privateOutputPath + basename + ".pfx", convertedCertificate.Export(X509ContentType.Pfx, password)); File.WriteAllBytes(publicOutputPath + basename + ".crt", convertedCertificate.Export(X509ContentType.Cert, password)); return(convertedCertificate); }
public void Save( Stream stream, char[] password, SecureRandom random) { if (stream == null) { throw new ArgumentNullException("stream"); } if (password == null) { throw new ArgumentNullException("password"); } if (random == null) { throw new ArgumentNullException("random"); } // // handle the key // Asn1EncodableVector keyS = new Asn1EncodableVector(); foreach (string name in keys.Keys) { byte[] kSalt = new byte[SaltSize]; random.NextBytes(kSalt); AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name]; EncryptedPrivateKeyInfo kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( keyAlgorithm, password, kSalt, MinIterations, privKey.Key); Asn1EncodableVector kName = new Asn1EncodableVector(); foreach (string oid in privKey.BagAttributeKeys) { Asn1Encodable entry = privKey[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } kName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry ct = GetCertificate(name); IAsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); keyS.Add(kBag); } byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded(); BerOctetString keyString = new BerOctetString(derEncodedBytes); // // certificate processing // byte[] cSalt = new byte[SaltSize]; random.NextBytes(cSalt); Asn1EncodableVector certSeq = new Asn1EncodableVector(); Pkcs12PbeParams cParams = new Pkcs12PbeParams(cSalt, MinIterations); AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object()); ISet doneCerts = new HashSet(); foreach (string name in keys.Keys) { X509CertificateEntry certEntry = GetCertificate(name); CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(certEntry.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in certEntry.BagAttributeKeys) { Asn1Encodable entry = certEntry[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { IAsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag sBag = new SafeBag( PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(certEntry.Certificate); } foreach (string certId in certs.Keys) { X509CertificateEntry cert = (X509CertificateEntry)certs[certId]; if (keys[certId] != null) { continue; } CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } Asn1Encodable entry = cert[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'certId' //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(certId)))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(cert.Certificate); } foreach (CertId certId in chainCerts.Keys) { X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId]; if (doneCerts.Contains(cert.Certificate)) { continue; } CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); } derEncodedBytes = new DerSequence(certSeq).GetDerEncoded(); byte[] certBytes = CryptPbeData(true, cAlgId, password, false, derEncodedBytes); EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes)); ContentInfo[] info = new ContentInfo[] { new ContentInfo(PkcsObjectIdentifiers.Data, keyString), new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object()) }; byte[] data = new AuthenticatedSafe(info).GetEncoded( useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber); ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data)); // // create the mac // byte[] mSalt = new byte[20]; random.NextBytes(mSalt); byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1, mSalt, MinIterations, password, false, data); AlgorithmIdentifier algId = new AlgorithmIdentifier( OiwObjectIdentifiers.IdSha1, DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, mac); MacData mData = new MacData(dInfo, mSalt, MinIterations); // // output the Pfx // Pfx pfx = new Pfx(mainInfo, mData); DerOutputStream derOut; if (useDerEncoding) { derOut = new DerOutputStream(stream); } else { derOut = new BerOutputStream(stream); } derOut.WriteObject(pfx); }
public static CertificateStr deserializeCertData(byte[] raw) { int length = raw.Length; int idx = 0; CertificateStr cert = new CertificateStr(); cert.Version = readInt(raw, idx); idx += 4; DeserializationFieldResult serialNumber = readByteArray(raw, idx); cert.SerialNumber = (byte[])serialNumber.value; idx += serialNumber.size; DeserializationFieldResult issuer = deserializeName(raw, idx); cert.issuer = (NameStr)issuer.value; idx += issuer.size; DeserializationFieldResult subject = deserializeName(raw, idx); cert.subject = (NameStr)subject.value; idx += subject.size; Validity validity = new Validity(); validity.NotBefore = readLong(raw, idx); //check idx += 8; validity.NotAfter = readLong(raw, idx); //check idx += 8; cert.Validity = validity; NativeExtendedKeyUsage extendedKeyUsage = new NativeExtendedKeyUsage(); extendedKeyUsage.Count = readInt(raw, idx); idx += 4; DeserializationFieldResult extendedKeyUsageOIDs = readStringArray(raw, idx); extendedKeyUsage.Oids = (CMap <int, string>)extendedKeyUsageOIDs.value; idx += extendedKeyUsageOIDs.size; cert.ExtendedKeyUsage = extendedKeyUsage; NativeKeyUsage keyUsage = new NativeKeyUsage(); keyUsage.Value = readInt(raw, idx); idx += 4; cert.KeyUsage = keyUsage; BasicConstraints basicConstraints = new BasicConstraints(); basicConstraints.HasBasicConstraints = readBool(raw, idx); idx += 1; basicConstraints.IsCa = readBool(raw, idx); idx += 1; basicConstraints.MaxPathLen = readInt(raw, idx); //check FF FF FF FF becomes FF FF FE FE idx += 4; cert.BasicConstraints = basicConstraints; AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifier(); DeserializationFieldResult authorityKeyId = readByteArray(raw, idx); authorityKeyIdentifier.keyIdentifier = (byte[])authorityKeyId.value; if (authorityKeyId.size > 2) { authorityKeyIdentifier.HasAuthorityKeyIdentifier = true; } idx += authorityKeyId.size; cert.AuthorityKeyIdentifier = authorityKeyIdentifier; SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifier(); DeserializationFieldResult subjectKeyId = readByteArray(raw, idx); subjectKeyIdentifier.keyIdentifier = (byte[])subjectKeyId.value; if (subjectKeyId.size > 2) { subjectKeyIdentifier.HasSubjectKeyIdentifierExtension = true; } idx += subjectKeyId.size; cert.SubjectKeyIdentifier = subjectKeyIdentifier; DeserializationFieldResult dnsNames = readStringArray(raw, idx); cert.DnsNames = (CMap <int, string>)dnsNames.value; idx += dnsNames.size; DeserializationFieldResult emailAddresses = readStringArray(raw, idx); cert.EmailAddresses = (CMap <int, string>)emailAddresses.value; idx += emailAddresses.size; DeserializationFieldResult ipAddresses = readStringArray(raw, idx); cert.IpAddresses = (CMap <int, string>)ipAddresses.value; idx += ipAddresses.size; DeserializationFieldResult urls = readStringArray(raw, idx); cert.Urls = (CMap <int, string>)urls.value; idx += urls.size; DeserializationFieldResult tbsCertificate = readByteArray(raw, idx); cert.TbsCertificate = (byte[])tbsCertificate.value; idx += tbsCertificate.size; DeserializationFieldResult signatureAlgorithm = readByteArray(raw, idx); cert.SignatureAlgorithm = (byte[])signatureAlgorithm.value; idx += signatureAlgorithm.size; DeserializationFieldResult signatureValue = readByteArray(raw, idx); cert.Signature = (byte[])signatureValue.value; idx += signatureValue.size; DeserializationFieldResult subjectPublicKeyInfo = readByteArray(raw, idx); cert.SubjectPublicKeyInfo = (byte[])subjectPublicKeyInfo.value; idx += subjectPublicKeyInfo.size; DeserializationFieldResult publicKeySignatureAlgorithm = readByteArray(raw, idx); cert.PublicKeyAlgName = (byte[])publicKeySignatureAlgorithm.value; idx += publicKeySignatureAlgorithm.size; DeserializationFieldResult tbsCertificateSignatureAlgorithm = readByteArray(raw, idx); cert.TBSSignatureAlgorithm = (byte[])tbsCertificateSignatureAlgorithm.value; idx += tbsCertificateSignatureAlgorithm.size; // todo return byte[] ? return(cert); }
/// <summary> /// Generate and return a new X509 certificate. /// </summary> /// <returns></returns> public X509Certificate2 Generate() { var generator = new X509V3CertificateGenerator(); // RFC 5280 section 4.1.2.2. Serial Number generator.SetSerialNumber(SerialNumber); // RFC 5280 section 4.1.2.4. Issuer generator.SetIssuerDN(IssuerDN); // RFC 5280 section 4.1.2.5. Validity if (!IsSelfSigned && NotBefore < Issuer.NotBefore) { NotBefore = Issuer.NotBefore; } if (!IsSelfSigned && Issuer.NotAfter < NotAfter) { NotAfter = Issuer.NotAfter; } generator.SetNotBefore(NotBefore); generator.SetNotAfter(NotAfter); // RFC 5280 section 4.1.2.6. Subject; also see Direct Project 1.2 section 4.1.1.2. generator.SetSubjectDN(SubjectDN); // RFC 5280 section 4.1.2.7. Subject Public Key Info generator.SetPublicKey(SubjectKeyPair.Public); // RFC 5280 section 4.2.1.1. Authority Key Identifier if (IsSelfSigned) { var authorityKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(SubjectKeyPair.Public), new GeneralNames(new GeneralName(SubjectDN)), SerialNumber); generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); } else { generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(Issuer)); } // RFC 5280 section 4.2.1.2. Subject Key Identifier var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(SubjectKeyPair.Public)); generator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier); // RFC 5280 section 4.2.1.3. Key Usage generator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage((int)KeyUsage)); // RFC 5280 section 4.2.1.4. Certificate Policies if (Policies.Any()) { var policies = Policies.Select(x => new PolicyInformation(new DerObjectIdentifier(x))).ToArray(); generator.AddExtension(X509Extensions.CertificatePolicies, false, new CertificatePolicies(policies)); } // RFC 5280 section 4.2.1.6. Subject Alternative Name; also see Direct Project 1.2 section 4.1.1.1. generator.AddExtension(X509Extensions.SubjectAlternativeName, false, SubjectAlternativeName); // RFC 5280 section 4.2.1.9. Basic Constraints generator.AddExtension(X509Extensions.BasicConstraints, true, BasicConstraints); // RFC 5280 section 4.2.1.12. Extended Key Usage generator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPEmailProtection)); // RFC 5280 section 4.2.1.13. CRL Distribution Points var crlDistPoint = GetCrlDistributionPoints(); if (crlDistPoint != null) { generator.AddExtension(X509Extensions.CrlDistributionPoints, false, crlDistPoint); } // RFC 5280 section 4.2.2.1. Authority Information Access var authorityInfoAccess = GetAuthorityInfoAccessEncoded(); if (authorityInfoAccess != null) { generator.AddExtension(X509Extensions.AuthorityInfoAccess, false, authorityInfoAccess); } // Generate a new certificate. var certificate = generator.Generate(new Asn1SignatureFactory(SignatureAlgorithmName, (IssuerKeyPair ?? SubjectKeyPair).Private, SecureRandom)); // Create a PKCS12 store (a.PFX file) in memory, and add the public and private key to that. var store = new Pkcs12Store(); var certificateEntry = new X509CertificateEntry(certificate); string friendlyName = certificate.SubjectDN.ToString(); store.SetCertificateEntry(friendlyName, certificateEntry); store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(SubjectKeyPair.Private), new[] { certificateEntry }); using (var stream = new MemoryStream()) { // The password is required by the API, but will not be used beyond this scope. const string password = "******"; store.Save(stream, password.ToCharArray(), SecureRandom); return(new X509Certificate2( stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable)); } }
public OriginatorIdentifierOrKey( SubjectKeyIdentifier id) { this.id = new DerTaggedObject(false, 0, id); }
public static X509Certificate2 GenerateCACertificate( 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 certificateGenerator.SetSubjectAndIssuer(subjectName); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // Generate KeyPair var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var keyPair = keyPairGenerator.GenerateKeyPair(); // Generate Signature Factory ISignatureFactory sigFact = new Asn1SignatureFactory( SignatureAlgorithm, keyPair.Private); // Set extensions certificateGenerator.AddExtension( X509Extensions.BasicConstraints, true, new BasicConstraints(true)); var ski = new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( keyPair.Public)); certificateGenerator.AddExtension( X509Extensions.SubjectKeyIdentifier, false, ski); // Add Public Key certificateGenerator.SetPublicKey(keyPair.Public); // Generating the BC Certificate var certificate = certificateGenerator.Generate(sigFact); // Add Private key (and convert to X509Certificate2) var x509 = GenerateX509WithPrivateKey( keyPair, certificate); return(x509); }
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(); } }
/// <summary> /// Encode the extension /// </summary> private new void encode() { base.encValue = SubjectKeyIdentifier.GetInstance(keyIdentifier); }