Example #1
0
        /**
         * Returns a string representation of this CRL.
         *
         * @return a string representation of this CRL.
         */
        public override string ToString()
        {
            StringBuilder buf = new StringBuilder();
            string        nl  = Platform.NewLine;

            buf.Append("              Version: ").Append(this.Version).Append(nl);
            buf.Append("             IssuerDN: ").Append(this.IssuerDN).Append(nl);
            buf.Append("          This update: ").Append(this.ThisUpdate).Append(nl);
            buf.Append("          Next update: ").Append(this.NextUpdate).Append(nl);
            buf.Append("  Signature Algorithm: ").Append(this.SigAlgName).Append(nl);

            byte[] sig = this.GetSignature();

            buf.Append("            Signature: ");
            buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl);

            for (int i = 20; i < sig.Length; i += 20)
            {
                int count = System.Math.Min(20, sig.Length - i);
                buf.Append("                       ");
                buf.Append(Hex.ToHexString(sig, i, count)).Append(nl);
            }

            X509Extensions extensions = c.TbsCertList.Extensions;

            if (extensions != null)
            {
                IEnumerator e = extensions.ExtensionOids.GetEnumerator();

                if (e.MoveNext())
                {
                    buf.Append("           Extensions: ").Append(nl);
                }

                do
                {
                    DerObjectIdentifier oid = (DerObjectIdentifier)e.Current;
                    X509Extension       ext = extensions.GetExtension(oid);

                    if (ext.Value != null)
                    {
                        Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                        buf.Append("                       critical(").Append(ext.IsCritical).Append(") ");
                        try
                        {
                            if (oid.Equals(X509Extensions.CrlNumber))
                            {
                                buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.DeltaCrlIndicator))
                            {
                                buf.Append(
                                    "Base CRL: "
                                    + new CrlNumber(DerInteger.GetInstance(
                                                        asn1Value).PositiveValue))
                                .Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.IssuingDistributionPoint))
                            {
                                buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.CrlDistributionPoints))
                            {
                                buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.FreshestCrl))
                            {
                                buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else
                            {
                                buf.Append(oid.Id);
                                buf.Append(" value = ").Append(
                                    Asn1Dump.DumpAsString(asn1Value))
                                .Append(nl);
                            }
                        }
                        catch (Exception)
                        {
                            buf.Append(oid.Id);
                            buf.Append(" value = ").Append("*****").Append(nl);
                        }
                    }
                    else
                    {
                        buf.Append(nl);
                    }
                }while (e.MoveNext());
            }

            ISet certSet = GetRevokedCertificates();

            if (certSet != null)
            {
                foreach (X509CrlEntry entry in certSet)
                {
                    buf.Append(entry);
                    buf.Append(nl);
                }
            }

            return(buf.ToString());
        }
Example #2
0
//		public void setBagAttribute(
//			DERObjectIdentifier oid,
//			DEREncodable        attribute)
//		{
//			pkcs12Attributes.put(oid, attribute);
//			pkcs12Ordering.addElement(oid);
//		}
//
//		public DEREncodable getBagAttribute(
//			DERObjectIdentifier oid)
//		{
//			return (DEREncodable)pkcs12Attributes.get(oid);
//		}
//
//		public Enumeration getBagAttributeKeys()
//		{
//			return pkcs12Ordering.elements();
//		}

        public override string ToString()
        {
            StringBuilder buf = new StringBuilder();
            string        nl  = Platform.NewLine;

            buf.Append("  [0]         Version: ").Append(this.Version).Append(nl);
            buf.Append("         SerialNumber: ").Append(this.SerialNumber).Append(nl);
            buf.Append("             IssuerDN: ").Append(this.IssuerDN).Append(nl);
            buf.Append("           Start Date: ").Append(this.NotBefore).Append(nl);
            buf.Append("           Final Date: ").Append(this.NotAfter).Append(nl);
            buf.Append("            SubjectDN: ").Append(this.SubjectDN).Append(nl);
            buf.Append("           Public Key: ").Append(this.GetPublicKey()).Append(nl);
            buf.Append("  Signature Algorithm: ").Append(this.SigAlgName).Append(nl);

            byte[] sig = this.GetSignature();
            buf.Append("            Signature: ").Append(Hex.ToHexString(sig, 0, 20)).Append(nl);

            for (int i = 20; i < sig.Length; i += 20)
            {
                int len = System.Math.Min(20, sig.Length - i);
                buf.Append("                       ").Append(Hex.ToHexString(sig, i, len)).Append(nl);
            }

            X509Extensions extensions = c.TbsCertificate.Extensions;

            if (extensions != null)
            {
                IEnumerator e = extensions.ExtensionOids.GetEnumerator();

                if (e.MoveNext())
                {
                    buf.Append("       Extensions: \n");
                }

                do
                {
                    DerObjectIdentifier oid = (DerObjectIdentifier)e.Current;
                    X509Extension       ext = extensions.GetExtension(oid);

                    if (ext.Value != null)
                    {
                        byte[]     octs = ext.Value.GetOctets();
                        Asn1Object obj  = Asn1Object.FromByteArray(octs);
                        buf.Append("                       critical(").Append(ext.IsCritical).Append(") ");
                        try
                        {
                            if (oid.Equals(X509Extensions.BasicConstraints))
                            {
                                buf.Append(BasicConstraints.GetInstance(obj));
                            }
                            else if (oid.Equals(X509Extensions.KeyUsage))
                            {
                                buf.Append(KeyUsage.GetInstance(obj));
                            }
                            else if (oid.Equals(MiscObjectIdentifiers.NetscapeCertType))
                            {
                                buf.Append(new NetscapeCertType((DerBitString)obj));
                            }
                            else if (oid.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl))
                            {
                                buf.Append(new NetscapeRevocationUrl((DerIA5String)obj));
                            }
                            else if (oid.Equals(MiscObjectIdentifiers.VerisignCzagExtension))
                            {
                                buf.Append(new VerisignCzagExtension((DerIA5String)obj));
                            }
                            else
                            {
                                buf.Append(oid.Id);
                                buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj));
                                //buf.Append(" value = ").Append("*****").Append(nl);
                            }
                        }
                        catch (Exception)
                        {
                            buf.Append(oid.Id);
                            //buf.Append(" value = ").Append(new string(Hex.encode(ext.getValue().getOctets()))).Append(nl);
                            buf.Append(" value = ").Append("*****");
                        }
                    }

                    buf.Append(nl);
                }while (e.MoveNext());
            }

            return(buf.ToString());
        }
        public override string ToString()
        {
            StringBuilder buf = new StringBuilder();
            string        nl  = Platform.NewLine;

            buf.Append("        userCertificate: ").Append(this.SerialNumber).Append(nl);
            buf.Append("         revocationDate: ").Append(this.RevocationDate).Append(nl);
            buf.Append("      certificateIssuer: ").Append(this.GetCertificateIssuer()).Append(nl);

            X509Extensions extensions = c.Extensions;

            if (extensions != null)
            {
                IEnumerator e = extensions.ExtensionOids.GetEnumerator();
                if (e.MoveNext())
                {
                    buf.Append("   crlEntryExtensions:").Append(nl);

                    do
                    {
                        DerObjectIdentifier oid = (DerObjectIdentifier)e.Current;
                        X509Extension       ext = extensions.GetExtension(oid);

                        if (ext.Value != null)
                        {
                            Asn1Object obj = Asn1Object.FromByteArray(ext.Value.GetOctets());

                            buf.Append("                       critical(")
                            .Append(ext.IsCritical)
                            .Append(") ");
                            try
                            {
                                if (oid.Equals(X509Extensions.ReasonCode))
                                {
                                    buf.Append(new CrlReason(DerEnumerated.GetInstance(obj)));
                                }
                                else if (oid.Equals(X509Extensions.CertificateIssuer))
                                {
                                    buf.Append("Certificate issuer: ").Append(
                                        GeneralNames.GetInstance((Asn1Sequence)obj));
                                }
                                else
                                {
                                    buf.Append(oid.Id);
                                    buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj));
                                }
                                buf.Append(nl);
                            }
                            catch (Exception)
                            {
                                buf.Append(oid.Id);
                                buf.Append(" value = ").Append("*****").Append(nl);
                            }
                        }
                        else
                        {
                            buf.Append(nl);
                        }
                    }while (e.MoveNext());
                }
            }

            return(buf.ToString());
        }
Example #4
0
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            string        newLine       = Platform.NewLine;

            stringBuilder.Append("              Version: ").Append(Version).Append(newLine);
            stringBuilder.Append("             IssuerDN: ").Append(IssuerDN).Append(newLine);
            stringBuilder.Append("          This update: ").Append(ThisUpdate).Append(newLine);
            stringBuilder.Append("          Next update: ").Append(NextUpdate).Append(newLine);
            stringBuilder.Append("  Signature Algorithm: ").Append(SigAlgName).Append(newLine);
            byte[] signature = GetSignature();
            stringBuilder.Append("            Signature: ");
            stringBuilder.Append(Hex.ToHexString(signature, 0, 20)).Append(newLine);
            for (int i = 20; i < signature.Length; i += 20)
            {
                int length = System.Math.Min(20, signature.Length - i);
                stringBuilder.Append("                       ");
                stringBuilder.Append(Hex.ToHexString(signature, i, length)).Append(newLine);
            }
            X509Extensions extensions = c.TbsCertList.Extensions;

            if (extensions != null)
            {
                IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    stringBuilder.Append("           Extensions: ").Append(newLine);
                }
                do
                {
                    DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.Current;
                    X509Extension       extension           = extensions.GetExtension(derObjectIdentifier);
                    if (extension.Value != null)
                    {
                        Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(extension.Value);
                        stringBuilder.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                        try
                        {
                            if (derObjectIdentifier.Equals(X509Extensions.CrlNumber))
                            {
                                stringBuilder.Append(new CrlNumber(DerInteger.GetInstance(asn1Object).PositiveValue)).Append(newLine);
                            }
                            else if (derObjectIdentifier.Equals(X509Extensions.DeltaCrlIndicator))
                            {
                                stringBuilder.Append("Base CRL: " + new CrlNumber(DerInteger.GetInstance(asn1Object).PositiveValue)).Append(newLine);
                            }
                            else if (derObjectIdentifier.Equals(X509Extensions.IssuingDistributionPoint))
                            {
                                stringBuilder.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                            }
                            else if (derObjectIdentifier.Equals(X509Extensions.CrlDistributionPoints))
                            {
                                stringBuilder.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                            }
                            else if (derObjectIdentifier.Equals(X509Extensions.FreshestCrl))
                            {
                                stringBuilder.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Object)).Append(newLine);
                            }
                            else
                            {
                                stringBuilder.Append(derObjectIdentifier.Id);
                                stringBuilder.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object)).Append(newLine);
                            }
                        }
                        catch (Exception)
                        {
                            stringBuilder.Append(derObjectIdentifier.Id);
                            stringBuilder.Append(" value = ").Append("*****").Append(newLine);
                        }
                    }
                    else
                    {
                        stringBuilder.Append(newLine);
                    }
                }while (enumerator.MoveNext());
            }
            ISet revokedCertificates = GetRevokedCertificates();

            if (revokedCertificates != null)
            {
                foreach (X509CrlEntry item in revokedCertificates)
                {
                    stringBuilder.Append(item);
                    stringBuilder.Append(newLine);
                }
            }
            return(stringBuilder.ToString());
        }
Example #5
0
        public void Load(
            Stream input,
            char[]  password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         unmarkedKey     = false;
            bool         wrongPkcs12Zero = false;

            if (bag.MacData != null)             // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = ((Asn1OctetString)info.Content).GetOctets();

                byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.ConstantTimeAreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data);

                    if (!Arrays.ConstantTimeAreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();

            IList chain = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        byte[]       octets = ((Asn1OctetString)ci.Content).GetOctets();
                        Asn1Sequence seq    = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                if (b.BagAttributes != null)
                                {
                                    foreach (Asn1Sequence sq in b.BagAttributes)
                                    {
                                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                        Asn1Set             attrSet = (Asn1Set)sq[1];
                                        Asn1Encodable       attr    = null;

                                        if (attrSet.Count > 0)
                                        {
                                            // TODO We should be adding all attributes in the set
                                            attr = attrSet[0];

                                            // TODO We might want to "merge" attribute sets with
                                            // the same OID - currently, differing values give an error
                                            if (attributes.Contains(aOid.Id))
                                            {
                                                // OK, but the value has to be the same
                                                if (!attributes[aOid.Id].Equals(attr))
                                                {
                                                    throw new IOException("attempt to add existing attribute with different value");
                                                }
                                            }
                                            else
                                            {
                                                attributes.Add(aOid.Id, attr);
                                            }

                                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                            {
                                                alias = ((DerBmpString)attr).GetString();
                                                // TODO Do these in a separate loop, just collect aliases here
                                                keys[alias] = pkcs12Key;
                                            }
                                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                            {
                                                localId = (Asn1OctetString)attr;
                                            }
                                        }
                                    }
                                }

                                if (localId != null)
                                {
                                    string name = Hex.ToHexString(localId.GetOctets());

                                    if (alias == null)
                                    {
                                        keys[name] = pkcs12Key;
                                    }
                                    else
                                    {
                                        // TODO There may have been more than one alias
                                        localIds[alias] = name;
                                    }
                                }
                                else
                                {
                                    unmarkedKey      = true;
                                    keys["unmarked"] = pkcs12Key;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
                            }
                        }
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        EncryptedData d      = EncryptedData.GetInstance(ci.Content);
                        byte[]        octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                            password, wrongPkcs12Zero, d.Content.GetOctets());
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.Contains(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                string name = Hex.ToHexString(localId.GetOctets());

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                PrivateKeyInfo         privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue);
                                AsymmetricKeyParameter privKey     = PrivateKeyFactory.CreateKey(privKeyInfo);

                                //
                                // set the attributes on the key
                                //
                                string             alias      = null;
                                Asn1OctetString    localId    = null;
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.Contains(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                string name = Hex.ToHexString(localId.GetOctets());

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("extra " + oid);
                        Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content));
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in chain)
            {
                CertBag         cb     = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets = ((Asn1OctetString)cb.CertValue).GetOctets();
                X509Certificate cert   = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                IDictionary     attributes = Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                        Asn1Set             attrSet = (Asn1Set)sq[1];

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.Contains(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = pkcs12Cert;

                if (unmarkedKey)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Hex.ToHexString(certId.Id);

                        keyCerts[name] = pkcs12Cert;

                        object temp = keys["unmarked"];
                        keys.Remove("unmarked");
                        keys[name] = temp;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = pkcs12Cert;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = pkcs12Cert;
                    }
                }
            }
        }
Example #6
0
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            string        newLine       = Platform.NewLine;

            stringBuilder.Append("  [0]         Version: ").Append(this.Version).Append(newLine);
            stringBuilder.Append("         SerialNumber: ").Append(this.SerialNumber).Append(newLine);
            stringBuilder.Append("             IssuerDN: ").Append(this.IssuerDN).Append(newLine);
            stringBuilder.Append("           Start Date: ").Append(this.NotBefore).Append(newLine);
            stringBuilder.Append("           Final Date: ").Append(this.NotAfter).Append(newLine);
            stringBuilder.Append("            SubjectDN: ").Append(this.SubjectDN).Append(newLine);
            stringBuilder.Append("           Public Key: ").Append(this.GetPublicKey()).Append(newLine);
            stringBuilder.Append("  Signature Algorithm: ").Append(this.SigAlgName).Append(newLine);
            byte[] signature = this.GetSignature();
            stringBuilder.Append("            Signature: ").Append(Hex.ToHexString(signature, 0, 20)).Append(newLine);
            for (int i = 20; i < signature.Length; i += 20)
            {
                int length = Math.Min(20, signature.Length - i);
                stringBuilder.Append("                       ").Append(Hex.ToHexString(signature, i, length)).Append(newLine);
            }
            X509Extensions extensions = this.c.TbsCertificate.Extensions;

            if (extensions != null)
            {
                IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    stringBuilder.Append("       Extensions: \n");
                }
                do
                {
                    DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.Current;
                    X509Extension       extension           = extensions.GetExtension(derObjectIdentifier);
                    if (extension.Value != null)
                    {
                        byte[]     octets     = extension.Value.GetOctets();
                        Asn1Object asn1Object = Asn1Object.FromByteArray(octets);
                        stringBuilder.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                        try
                        {
                            if (derObjectIdentifier.Equals(X509Extensions.BasicConstraints))
                            {
                                stringBuilder.Append(BasicConstraints.GetInstance(asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(X509Extensions.KeyUsage))
                            {
                                stringBuilder.Append(KeyUsage.GetInstance(asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.NetscapeCertType))
                            {
                                stringBuilder.Append(new NetscapeCertType((DerBitString)asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl))
                            {
                                stringBuilder.Append(new NetscapeRevocationUrl((DerIA5String)asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.VerisignCzagExtension))
                            {
                                stringBuilder.Append(new VerisignCzagExtension((DerIA5String)asn1Object));
                            }
                            else
                            {
                                stringBuilder.Append(derObjectIdentifier.Id);
                                stringBuilder.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object));
                            }
                        }
                        catch (Exception)
                        {
                            stringBuilder.Append(derObjectIdentifier.Id);
                            stringBuilder.Append(" value = ").Append("*****");
                        }
                    }
                    stringBuilder.Append(newLine);
                }while (enumerator.MoveNext());
            }
            return(stringBuilder.ToString());
        }
Example #7
0
        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();
            string        newLine = Platform.NewLine;

            builder.Append("              Version: ").Append(this.Version).Append(newLine);
            builder.Append("             IssuerDN: ").Append(this.IssuerDN).Append(newLine);
            builder.Append("          This update: ").Append(this.ThisUpdate).Append(newLine);
            builder.Append("          Next update: ").Append(this.NextUpdate).Append(newLine);
            builder.Append("  Signature Algorithm: ").Append(this.SigAlgName).Append(newLine);
            byte[] signature = this.GetSignature();
            builder.Append("            Signature: ");
            builder.Append(Hex.ToHexString(signature, 0, 20)).Append(newLine);
            for (int i = 20; i < signature.Length; i += 20)
            {
                int length = Math.Min(20, signature.Length - i);
                builder.Append("                       ");
                builder.Append(Hex.ToHexString(signature, i, length)).Append(newLine);
            }
            X509Extensions extensions = this.c.TbsCertList.Extensions;

            if (extensions != null)
            {
                IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    builder.Append("           Extensions: ").Append(newLine);
                }
                do
                {
                    DerObjectIdentifier current   = (DerObjectIdentifier)enumerator.Current;
                    X509Extension       extension = extensions.GetExtension(current);
                    if (extension.Value != null)
                    {
                        Asn1Object obj2 = X509ExtensionUtilities.FromExtensionValue(extension.Value);
                        builder.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                        try
                        {
                            if (current.Equals(X509Extensions.CrlNumber))
                            {
                                builder.Append(new CrlNumber(DerInteger.GetInstance(obj2).PositiveValue)).Append(newLine);
                            }
                            else if (current.Equals(X509Extensions.DeltaCrlIndicator))
                            {
                                builder.Append("Base CRL: " + new CrlNumber(DerInteger.GetInstance(obj2).PositiveValue)).Append(newLine);
                            }
                            else if (current.Equals(X509Extensions.IssuingDistributionPoint))
                            {
                                builder.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)obj2)).Append(newLine);
                            }
                            else if (current.Equals(X509Extensions.CrlDistributionPoints))
                            {
                                builder.Append(CrlDistPoint.GetInstance((Asn1Sequence)obj2)).Append(newLine);
                            }
                            else if (current.Equals(X509Extensions.FreshestCrl))
                            {
                                builder.Append(CrlDistPoint.GetInstance((Asn1Sequence)obj2)).Append(newLine);
                            }
                            else
                            {
                                builder.Append(current.Id);
                                builder.Append(" value = ").Append(Asn1Dump.DumpAsString((Asn1Encodable)obj2)).Append(newLine);
                            }
                        }
                        catch (Exception)
                        {
                            builder.Append(current.Id);
                            builder.Append(" value = ").Append("*****").Append(newLine);
                        }
                    }
                    else
                    {
                        builder.Append(newLine);
                    }
                }while (enumerator.MoveNext());
            }
            ISet revokedCertificates = this.GetRevokedCertificates();

            if (revokedCertificates != null)
            {
                IEnumerator enumerator = revokedCertificates.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        X509CrlEntry current = (X509CrlEntry)enumerator.Current;
                        builder.Append(current);
                        builder.Append(newLine);
                    }
                }
                finally
                {
                    if (enumerator is IDisposable disposable)
                    {
                        IDisposable disposable;
                        disposable.Dispose();
                    }
                }
            }
            return(builder.ToString());
        }
Example #8
0
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            string        newLine       = Platform.NewLine;

            stringBuilder.Append("        userCertificate: ").Append(this.SerialNumber).Append(newLine);
            stringBuilder.Append("         revocationDate: ").Append(this.RevocationDate).Append(newLine);
            stringBuilder.Append("      certificateIssuer: ").Append(this.GetCertificateIssuer()).Append(newLine);
            X509Extensions extensions = this.c.Extensions;

            if (extensions != null)
            {
                IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    stringBuilder.Append("   crlEntryExtensions:").Append(newLine);
                    while (true)
                    {
                        DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.Current;
                        X509Extension       extension           = extensions.GetExtension(derObjectIdentifier);
                        if (extension.Value != null)
                        {
                            Asn1Object asn1Object = Asn1Object.FromByteArray(extension.Value.GetOctets());
                            stringBuilder.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                            try
                            {
                                if (derObjectIdentifier.Equals(X509Extensions.ReasonCode))
                                {
                                    stringBuilder.Append(new CrlReason(DerEnumerated.GetInstance(asn1Object)));
                                }
                                else if (derObjectIdentifier.Equals(X509Extensions.CertificateIssuer))
                                {
                                    stringBuilder.Append("Certificate issuer: ").Append(GeneralNames.GetInstance((Asn1Sequence)asn1Object));
                                }
                                else
                                {
                                    stringBuilder.Append(derObjectIdentifier.Id);
                                    stringBuilder.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object));
                                }
                                stringBuilder.Append(newLine);
                                goto IL_1B0;
                            }
                            catch (Exception)
                            {
                                stringBuilder.Append(derObjectIdentifier.Id);
                                stringBuilder.Append(" value = ").Append("*****").Append(newLine);
                                goto IL_1B0;
                            }
                            goto IL_1A8;
                        }
                        goto IL_1A8;
IL_1B0:
                        if (!enumerator.MoveNext())
                        {
                            break;
                        }
                        continue;
IL_1A8:
                        stringBuilder.Append(newLine);
                        goto IL_1B0;
                    }
                }
            }
            return(stringBuilder.ToString());
        }
        public void CheckAttributeCertificate(
            int id,
            byte[]  cert)
        {
            Asn1Sequence seq  = (Asn1Sequence)Asn1Object.FromByteArray(cert);
            string       dump = Asn1Dump.DumpAsString(seq);

            AttributeCertificate     obj    = AttributeCertificate.GetInstance(seq);
            AttributeCertificateInfo acInfo = obj.ACInfo;

            // Version
            if (!(acInfo.Version.Equals(new DerInteger(1))) &&
                (!(acInfo.Version.Equals(new DerInteger(2)))))
            {
                Fail("failed AC Version test for id " + id);
            }

            // Holder
            Holder h = acInfo.Holder;

            if (h == null)
            {
                Fail("failed AC Holder test, it's null, for id " + id);
            }

            // Issuer
            AttCertIssuer aci = acInfo.Issuer;

            if (aci == null)
            {
                Fail("failed AC Issuer test, it's null, for id " + id);
            }

            // Signature
            AlgorithmIdentifier sig = acInfo.Signature;

            if (sig == null)
            {
                Fail("failed AC Signature test for id " + id);
            }

            // Serial
            DerInteger serial = acInfo.SerialNumber;

            // Validity
            AttCertValidityPeriod validity = acInfo.AttrCertValidityPeriod;

            if (validity == null)
            {
                Fail("failed AC AttCertValidityPeriod test for id " + id);
            }

            // Attributes
            Asn1Sequence attribSeq = acInfo.Attributes;

            AttributeX509[] att = new AttributeX509[attribSeq.Count];
            for (int i = 0; i < attribSeq.Count; i++)
            {
                att[i] = AttributeX509.GetInstance(attribSeq[i]);
            }

            // IssuerUniqueId
            // TODO, how to best test?

            // X509 Extensions
            X509Extensions ext = acInfo.Extensions;

            if (ext != null)
            {
                foreach (DerObjectIdentifier oid in ext.ExtensionOids)
                {
                    X509Extension extVal = ext.GetExtension(oid);
                }
            }
        }
        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);
                        }
                    }
                }
            }
        }
Example #11
0
        public MimeEntity DecryptEntity(byte[] encryptedBytes, X509Certificate2 decryptingCertificate)
        {
            try
            {
                if (decryptingCertificate == null)
                {
                    throw new EncryptionException(EncryptionError.NoCertificates);
                }

                // TODO: introduce buffering if you are using large files
                // CMSEnvelopeData is a PKCS# structure  rfc4134
                var envelopedData = new CmsEnvelopedData(encryptedBytes);
                var envData       = EnvelopedData.GetInstance(envelopedData.ContentInfo.Content);

                using (var session = GetSession())
                {
                    if (session == null)
                    {
                        return(null);
                    }

                    foreach (Asn1Sequence asn1Set in envData.RecipientInfos)
                    {
                        var recip = RecipientInfo.GetInstance(asn1Set);
                        var keyTransRecipientInfo = KeyTransRecipientInfo.GetInstance(recip.Info);

                        var sessionKey = Pkcs11Util.Decrypt(session, keyTransRecipientInfo, decryptingCertificate);

#if DEBUG
                        Console.WriteLine(Asn1Dump.DumpAsString(envData));
#endif
                        if (sessionKey == null)
                        {
                            continue;
                        }

                        var recipientId           = new RecipientID();
                        var issuerAndSerialNumber = (IssuerAndSerialNumber)keyTransRecipientInfo.RecipientIdentifier.ID;
                        recipientId.Issuer       = issuerAndSerialNumber.Name;
                        recipientId.SerialNumber = issuerAndSerialNumber.SerialNumber.Value;
                        var recipientInformation = envelopedData.GetRecipientInfos().GetRecipients(recipientId);
                        var recipients           = new ArrayList(recipientInformation);

                        //
                        // read the encrypted content info
                        //
                        var encInfo      = envData.EncryptedContentInfo;
                        var encAlg       = encInfo.ContentEncryptionAlgorithm;
                        var readable     = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
                        var keyParameter = ParameterUtilities.CreateKeyParameter(encAlg.Algorithm.Id, sessionKey);

                        // Todo: does this work with multi recipient?
                        foreach (RecipientInformation recipient in recipients)
                        {
                            var cmsReadable    = GetReadable(keyParameter, encAlg, readable);
                            var cmsTypedStream = new CmsTypedStream(cmsReadable.GetInputStream());
                            var contentBytes   = StreamToByteArray(cmsTypedStream.ContentStream);
                            var mimeEntity     = MimeSerializer.Default.Deserialize <MimeEntity>(contentBytes);
                            return(mimeEntity);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error.NotifyEvent(this, ex);
            }

            return(null);
        }