Example #1
0
		public X9Curve(
            X9FieldID		fieldID,
            Asn1Sequence	seq)
        {
			if (fieldID == null)
				throw new ArgumentNullException("fieldID");
			if (seq == null)
				throw new ArgumentNullException("seq");

			this.fieldIdentifier = fieldID.Identifier;

			if (fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField))
            {
                BigInteger q = ((DerInteger) fieldID.Parameters).Value;
                X9FieldElement x9A = new X9FieldElement(q, (Asn1OctetString) seq[0]);
                X9FieldElement x9B = new X9FieldElement(q, (Asn1OctetString) seq[1]);
                curve = new FpCurve(q, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
            }
            else
            {
				if (fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField)) 
				{
					// Characteristic two field
					DerSequence parameters = (DerSequence)fieldID.Parameters;
					int m = ((DerInteger)parameters[0]).Value.IntValue;
					DerObjectIdentifier representation
						= (DerObjectIdentifier)parameters[1];

					int k1 = 0;
					int k2 = 0;
					int k3 = 0;
					if (representation.Equals(X9ObjectIdentifiers.TPBasis)) 
					{
						// Trinomial basis representation
						k1 = ((DerInteger)parameters[2]).Value.IntValue;
					}
					else 
					{
						// Pentanomial basis representation
						DerSequence pentanomial = (DerSequence) parameters[2];
						k1 = ((DerInteger) pentanomial[0]).Value.IntValue;
						k2 = ((DerInteger) pentanomial[1]).Value.IntValue;
						k3 = ((DerInteger) pentanomial[2]).Value.IntValue;
					}
					X9FieldElement x9A = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[0]);
					X9FieldElement x9B = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[1]);
					// TODO Is it possible to get the order (n) and cofactor(h) too?
					curve = new F2mCurve(m, k1, k2, k3, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
				}
			}

			if (seq.Count == 3)
            {
                seed = ((DerBitString) seq[2]).GetBytes();
            }
        }
        /**
         * Apply default conversion for the given value depending on the oid
         * and the character range of the value.
         *
         * @param oid the object identifier for the DN entry
         * @param value the value associated with it
         * @return the ASN.1 equivalent for the string value.
         */
        public override Asn1Object GetConvertedValue(
            DerObjectIdentifier	oid,
            string				value)
        {
            if (value.Length != 0 && value[0] == '#')
            {
                try
                {
                    return ConvertHexEncoded(value, 1);
                }
                catch (IOException)
                {
                    throw new Exception("can't recode value for oid " + oid.Id);
                }
            }

            if (oid.Equals(X509Name.EmailAddress) || oid.Equals(X509Name.DC))
            {
                return new DerIA5String(value);
            }

            if (oid.Equals(X509Name.DateOfBirth)) // accept time string as well as # (for compatibility)
            {
                return new DerGeneralizedTime(value);
            }

            if (oid.Equals(X509Name.C)
                || oid.Equals(X509Name.SerialNumber)
                || oid.Equals(X509Name.DnQualifier))
            {
                return new DerPrintableString(value);
            }

            return new DerUtf8String(value);
        }
Example #3
0
		private void recodeCheck(
			string	oid,
			byte[]	enc)
		{
			DerObjectIdentifier o = new DerObjectIdentifier(oid);
			DerObjectIdentifier encO = (DerObjectIdentifier) Asn1Object.FromByteArray(enc);

			if (!o.Equals(encO))
			{
				Fail("oid ID didn't match", o, encO);
			}

			byte[] bytes = o.GetDerEncoded();

			if (!Arrays.AreEqual(bytes, enc))
			{
				Fail("failed comparison test", Hex.ToHexString(enc), Hex.ToHexString(bytes));
			}
		}
Example #4
0
        private bool DoVerify(
            AsymmetricKeyParameter key)
        {
            string  digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
            IDigest digest     = Helper.GetDigestInstance(digestName);

            DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.Algorithm;
            Asn1Encodable       sigParams = this.encryptionAlgorithm.Parameters;
            ISigner             sig;

            if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
            {
                // RFC 4056 2.2
                // When the id-RSASSA-PSS algorithm identifier is used for a signature,
                // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
                if (sigParams == null)
                {
                    throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");
                }

                try
                {
                    // TODO Provide abstract configuration mechanism
                    // (via alternate SignerUtilities.GetSigner method taking ASN.1 params)

                    Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
                        sigParams.ToAsn1Object());

                    if (!pss.HashAlgorithm.Algorithm.Equals(this.digestAlgorithm.Algorithm))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
                    }
                    if (!pss.MaskGenAlgorithm.Algorithm.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");
                    }

                    IDigest pssDigest    = DigestUtilities.GetDigest(pss.HashAlgorithm.Algorithm);
                    int     saltLength   = pss.SaltLength.Value.IntValue;
                    byte    trailerField = (byte)pss.TrailerField.Value.IntValue;

                    // RFC 4055 3.1
                    // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
                    if (trailerField != 1)
                    {
                        throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");
                    }

                    sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength);
                }
                catch (Exception e)
                {
                    throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
                }
            }
            else
            {
                // TODO Probably too strong a check at the moment
//				if (sigParams != null)
//					throw new CmsException("unrecognised signature parameters provided");

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

                sig = Helper.GetSignatureInstance(signatureName);

                //sig = Helper.GetSignatureInstance(this.EncryptionAlgOid);
                //sig = SignerUtilities.GetSigner(sigAlgOid);
            }

            try
            {
                if (digestCalculator != null)
                {
                    resultDigest = digestCalculator.GetDigest();
                }
                else
                {
                    if (content != null)
                    {
                        content.Write(new DigestSink(digest));
                    }
                    else if (signedAttributeSet == null)
                    {
                        // TODO Get rid of this exception and just treat content==null as empty not missing?
                        throw new CmsException("data not encapsulated in signature - use detached constructor.");
                    }

                    resultDigest = DigestUtilities.DoFinal(digest);
                }
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }

            // RFC 3852 11.1 Check the content-type attribute is correct
            {
                Asn1Object validContentType = GetSingleValuedSignedAttribute(
                    CmsAttributes.ContentType, "content-type");
                if (validContentType == null)
                {
                    if (!isCounterSignature && signedAttributeSet != null)
                    {
                        throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
                    }
                }
                else
                {
                    if (isCounterSignature)
                    {
                        throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
                    }

                    if (!(validContentType is DerObjectIdentifier))
                    {
                        throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
                    }

                    DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType;

                    if (!signedContentType.Equals(contentType))
                    {
                        throw new CmsException("content-type attribute value does not match eContentType");
                    }
                }
            }

            // RFC 3852 11.2 Check the message-digest attribute is correct
            {
                Asn1Object validMessageDigest = GetSingleValuedSignedAttribute(
                    CmsAttributes.MessageDigest, "message-digest");
                if (validMessageDigest == null)
                {
                    if (signedAttributeSet != null)
                    {
                        throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
                    }
                }
                else
                {
                    if (!(validMessageDigest is Asn1OctetString))
                    {
                        throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
                    }

                    Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest;

                    if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets()))
                    {
                        throw new CmsException("message-digest attribute value does not match calculated value");
                    }
                }
            }

            // RFC 3852 11.4 Validate countersignature attribute(s)
            {
                Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
                if (signedAttrTable != null &&
                    signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0)
                {
                    throw new CmsException("A countersignature attribute MUST NOT be a signed attribute");
                }

                Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
                if (unsignedAttrTable != null)
                {
                    foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature))
                    {
                        if (csAttr.AttrValues.Count < 1)
                        {
                            throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue");
                        }

                        // Note: We don't recursively validate the countersignature value
                    }
                }
            }

            try
            {
                sig.Init(false, key);

                if (signedAttributeSet == null)
                {
                    if (digestCalculator != null)
                    {
                        // need to decrypt signature and check message bytes
                        return(VerifyDigest(resultDigest, key, this.GetSignature()));
                    }
                    else if (content != null)
                    {
                        try
                        {
                            // TODO Use raw signature of the hash value instead
                            content.Write(new SignerSink(sig));
                        }
                        catch (SignatureException e)
                        {
                            throw new CmsStreamException("signature problem: " + e);
                        }
                    }
                }
                else
                {
                    byte[] tmp = this.GetEncodedSignedAttributes();
                    sig.BlockUpdate(tmp, 0, tmp.Length);
                }

                return(sig.VerifySignature(this.GetSignature()));
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key not appropriate to signature in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }
            catch (SignatureException e)
            {
                throw new CmsException("invalid signature format in message: " + e.Message, e);
            }
        }
Example #5
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 #6
0
        public void Load(
            Stream input,
            char[]      password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            Pfx         bag             = Pfx.GetInstance(Asn1Object.FromStream(input));
            ContentInfo info            = bag.AuthSafe;
            bool        wrongPkcs12Zero = false;

            if (bag.MacData != null) // check the mac code
            {
                if (password == null)
                {
                    throw new ArgumentNullException("password", "no password supplied when one expected");
                }

                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

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

                byte[] mac = CalculatePbeMac(algId.Algorithm, 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.Algorithm, 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;
                }
            }
            else if (password != null)
            {
                string ignoreProperty = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(IgnoreUselessPasswordProperty);
                bool   ignore         = ignoreProperty != null && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", ignoreProperty);

                if (!ignore)
                {
                    throw new IOException("password supplied for keystore that does not require one");
                }
            }

            keys.Clear();
            localIds.Clear();
            unmarkedKeyEntry = null;

            IList certBags = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                Asn1OctetString   content  = Asn1OctetString.GetInstance(info.Content);
                AuthenticatedSafe authSafe = AuthenticatedSafe.GetInstance(content.GetOctets());
                ContentInfo[]     cis      = authSafe.GetContentInfo();

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

                    byte[] octets = null;
                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        octets = Asn1OctetString.GetInstance(ci.Content).GetOctets();
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        if (password != null)
                        {
                            EncryptedData d = EncryptedData.GetInstance(ci.Content);
                            octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                  password, wrongPkcs12Zero, d.Content.GetOctets());
                        }
                    }
                    else
                    {
                        // TODO Other data types
                    }

                    if (octets != null)
                    {
                        Asn1Sequence seq = Asn1Sequence.GetInstance(octets);

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

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                certBags.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue),
                                                        b.BagAttributes, password, wrongPkcs12Zero);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes);
                            }
                            else
                            {
                                // TODO Other bag types
                            }
                        }
                    }
                }
            }

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

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

                //
                // set the attributes
                //
                IDictionary     attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = DerObjectIdentifier.GetInstance(sq[0]);
                        Asn1Set             attrSet = Asn1Set.GetInstance(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 certEntry = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = certEntry;

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

                        keyCerts[name] = certEntry;
                        keys[name]     = unmarkedKeyEntry;
                    }
                    else
                    {
                        keys["unmarked"] = unmarkedKeyEntry;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = certEntry;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = certEntry;
                    }
                }
            }
        }
Example #7
0
        public override string ToString()
        {
            StringBuilder buf = new StringBuilder();
            string        nl  = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.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());
        }
        public static AsymmetricKeyParameter CreateKey(
            PrivateKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.PrivateKeyAlgorithm;
            DerObjectIdentifier algOid = algID.Algorithm;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());

                return(new RsaPrivateCrtKeyParameters(
                           keyStructure.Modulus,
                           keyStructure.PublicExponent,
                           keyStructure.PrivateExponent,
                           keyStructure.Prime1,
                           keyStructure.Prime2,
                           keyStructure.Exponent1,
                           keyStructure.Exponent2,
                           keyStructure.Coefficient));
            }
            // TODO?
            //			else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                DHParameter para = new DHParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                BigInteger   lVal     = para.L;
                int          l        = lVal == null ? 0 : lVal.IntValue;
                DHParameters dhParams = new DHParameters(para.P, para.G, null, l);

                return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                return(new ElGamalPrivateKeyParameters(
                           derX.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
            {
                DerInteger    derX = (DerInteger)keyInfo.ParsePrivateKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPrivateKeyParameters(derX.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = X962Parameters.GetInstance(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());
                BigInteger            d  = ec.GetKey();

                if (para.IsNamedCurve)
                {
                    return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPrivateKeyParameters(d, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(
                    algID.Parameters.ToAsn1Object());

                X9ECParameters ecP = ECGost3410NamedCurves.GetByOidX9(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key");
                }

                Asn1Object            privKey = keyInfo.ParsePrivateKey();
                ECPrivateKeyStructure ec;

                if (privKey is DerInteger)
                {
                    ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue);
                }
                else
                {
                    ec = ECPrivateKeyStructure.GetInstance(privKey);
                }

                return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);

                Asn1Object privKey = keyInfo.ParsePrivateKey();
                BigInteger x;

                if (privKey is DerInteger)
                {
                    x = DerInteger.GetInstance(privKey).PositiveValue;
                }
                else
                {
                    x = new BigInteger(1, Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets()));
                }

                return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X25519))
            {
                return(new X25519PrivateKeyParameters(GetRawKey(keyInfo)));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X448))
            {
                return(new X448PrivateKeyParameters(GetRawKey(keyInfo)));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519))
            {
                return(new Ed25519PrivateKeyParameters(GetRawKey(keyInfo)));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448))
            {
                return(new Ed448PrivateKeyParameters(GetRawKey(keyInfo)));
            }
            else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) ||
                     algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters);
                ECGost3410Parameters           ecSpec;
                BigInteger d;
                Asn1Object p = keyInfo.PrivateKeyAlgorithm.Parameters.ToAsn1Object();
                if (p is Asn1Sequence && (Asn1Sequence.GetInstance(p).Count == 2 || Asn1Sequence.GetInstance(p).Count == 3))
                {
                    X9ECParameters ecP = ECGost3410NamedCurves.GetByOidX9(gostParams.PublicKeyParamSet);

                    ecSpec = new ECGost3410Parameters(
                        new ECNamedDomainParameters(
                            gostParams.PublicKeyParamSet, ecP),
                        gostParams.PublicKeyParamSet,
                        gostParams.DigestParamSet,
                        gostParams.EncryptionParamSet);

                    Asn1OctetString privEnc = keyInfo.PrivateKeyData;
                    if (privEnc.GetOctets().Length == 32 || privEnc.GetOctets().Length == 64)
                    {
                        byte[] dVal = Arrays.Reverse(privEnc.GetOctets());
                        d = new BigInteger(1, dVal);
                    }
                    else
                    {
                        Asn1Encodable privKey = keyInfo.ParsePrivateKey();
                        if (privKey is DerInteger)
                        {
                            d = DerInteger.GetInstance(privKey).PositiveValue;
                        }
                        else
                        {
                            byte[] dVal = Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets());
                            d = new BigInteger(1, dVal);
                        }
                    }
                }
                else
                {
                    X962Parameters parameters = X962Parameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters);

                    if (parameters.IsNamedCurve)
                    {
                        DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(parameters.Parameters);
                        X9ECParameters      ecP = ECNamedCurveTable.GetByOid(oid);

                        ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(oid, ecP),
                                                          gostParams.PublicKeyParamSet, gostParams.DigestParamSet,
                                                          gostParams.EncryptionParamSet);
                    }
                    else if (parameters.IsImplicitlyCA)
                    {
                        ecSpec = null;
                    }
                    else
                    {
                        X9ECParameters ecP = X9ECParameters.GetInstance(parameters.Parameters);
                        ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(algOid, ecP),
                                                          gostParams.PublicKeyParamSet, gostParams.DigestParamSet,
                                                          gostParams.EncryptionParamSet);
                    }

                    Asn1Encodable privKey = keyInfo.ParsePrivateKey();
                    if (privKey is DerInteger)
                    {
                        DerInteger derD = DerInteger.GetInstance(privKey);
                        d = derD.Value;
                    }
                    else
                    {
                        ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(privKey);
                        d = ec.GetKey();
                    }
                }

                return(new ECPrivateKeyParameters(
                           d,
                           new ECGost3410Parameters(
                               ecSpec,
                               gostParams.PublicKeyParamSet,
                               gostParams.DigestParamSet,
                               gostParams.EncryptionParamSet)));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in private key not recognised");
            }
        }
Example #9
0
            public override void PerformTest()
            {
                char[] password = "******".ToCharArray();
                PbeParametersGenerator generator = new Pkcs5S2ParametersGenerator();

                EncryptedPrivateKeyInfo info = null;

                try
                {
                    info = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(sample));
                }
                catch (System.Exception e)
                {
                    Fail("failed construction - exception " + e.ToString(), e);
                }

                PbeS2Parameters  alg    = PbeS2Parameters.GetInstance(info.EncryptionAlgorithm.Parameters);
                Pbkdf2Params     func   = Pbkdf2Params.GetInstance(alg.KeyDerivationFunc.Parameters);
                EncryptionScheme scheme = alg.EncryptionScheme;

                if (func.KeyLength != null)
                {
                    keySize = func.KeyLength.IntValue * 8;
                }

                int iterationCount = func.IterationCount.IntValue;

                byte[] salt = func.GetSalt();

                generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iterationCount);

                DerObjectIdentifier algOid = scheme.Algorithm;

                byte[] iv;
                if (algOid.Equals(PkcsObjectIdentifiers.RC2Cbc))
                {
                    RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(scheme.Asn1Object);
                    iv = rc2Params.GetIV();
                }
                else
                {
                    iv = ((Asn1OctetString)scheme.Asn1Object).GetOctets();
                }

                ICipherParameters param = new ParametersWithIV(
                    generator.GenerateDerivedParameters(algOid.Id, keySize), iv);

                cipher.Init(false, param);

                byte[] data     = info.GetEncryptedData();
                byte[] outBytes = new byte[cipher.GetOutputSize(data.Length)];
                int    len      = cipher.ProcessBytes(data, 0, data.Length, outBytes, 0);

                try
                {
                    len += cipher.DoFinal(outBytes, len);
                }
                catch (Exception e)
                {
                    Fail("failed DoFinal - exception " + e.ToString());
                }

                if (result.Length != len)
                {
                    Fail("failed length");
                }

                for (int i = 0; i != len; i++)
                {
                    if (outBytes[i] != result[i])
                    {
                        Fail("failed comparison");
                    }
                }
            }
Example #10
0
        public static AsymmetricKeyParameter CreateKey(SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algorithmID = keyInfo.AlgorithmID;
            DerObjectIdentifier objectID    = algorithmID.ObjectID;

            if (objectID.Equals(PkcsObjectIdentifiers.RsaEncryption) || objectID.Equals(X509ObjectIdentifiers.IdEARsa) || objectID.Equals(PkcsObjectIdentifiers.IdRsassaPss) || objectID.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure instance = RsaPublicKeyStructure.GetInstance(keyInfo.GetPublicKey());
                return(new RsaKeyParameters(isPrivate: false, instance.Modulus, instance.PublicExponent));
            }
            if (objectID.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                Asn1Sequence instance2 = Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object());
                DHPublicKey  instance3 = DHPublicKey.GetInstance(keyInfo.GetPublicKey());
                BigInteger   value     = instance3.Y.Value;
                if (IsPkcsDHParam(instance2))
                {
                    return(ReadPkcsDHParam(objectID, value, instance2));
                }
                DHDomainParameters instance4 = DHDomainParameters.GetInstance(instance2);
                BigInteger         value2    = instance4.P.Value;
                BigInteger         value3    = instance4.G.Value;
                BigInteger         value4    = instance4.Q.Value;
                BigInteger         j         = null;
                if (instance4.J != null)
                {
                    j = instance4.J.Value;
                }
                DHValidationParameters validation      = null;
                DHValidationParms      validationParms = instance4.ValidationParms;
                if (validationParms != null)
                {
                    byte[]     bytes  = validationParms.Seed.GetBytes();
                    BigInteger value5 = validationParms.PgenCounter.Value;
                    validation = new DHValidationParameters(bytes, value5.IntValue);
                }
                return(new DHPublicKeyParameters(value, new DHParameters(value2, value3, value4, j, validation)));
            }
            if (objectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                Asn1Sequence instance5  = Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object());
                DerInteger   derInteger = (DerInteger)keyInfo.GetPublicKey();
                return(ReadPkcsDHParam(objectID, derInteger.Value, instance5));
            }
            if (objectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object()));
                DerInteger       derInteger2      = (DerInteger)keyInfo.GetPublicKey();
                return(new ElGamalPublicKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G)));
            }
            if (objectID.Equals(X9ObjectIdentifiers.IdDsa) || objectID.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger    derInteger3 = (DerInteger)keyInfo.GetPublicKey();
                Asn1Encodable parameters  = algorithmID.Parameters;
                DsaParameters parameters2 = null;
                if (parameters != null)
                {
                    DsaParameter instance6 = DsaParameter.GetInstance(parameters.ToAsn1Object());
                    parameters2 = new DsaParameters(instance6.P, instance6.Q, instance6.G);
                }
                return(new DsaPublicKeyParameters(derInteger3.Value, parameters2));
            }
            if (objectID.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters  x962Parameters = new X962Parameters(algorithmID.Parameters.ToAsn1Object());
                X9ECParameters  x9ECParameters = (!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters);
                Asn1OctetString s         = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
                X9ECPoint       x9ECPoint = new X9ECPoint(x9ECParameters.Curve, s);
                ECPoint         point     = x9ECPoint.Point;
                if (x962Parameters.IsNamedCurve)
                {
                    return(new ECPublicKeyParameters("EC", point, (DerObjectIdentifier)x962Parameters.Parameters));
                }
                ECDomainParameters parameters3 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed());
                return(new ECPublicKeyParameters(point, parameters3));
            }
            if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters((Asn1Sequence)algorithmID.Parameters);
                Asn1OctetString asn1OctetString;
                try
                {
                    asn1OctetString = (Asn1OctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                    IL_038b :;
                }
                byte[] octets = asn1OctetString.GetOctets();
                byte[] array  = new byte[32];
                byte[] array2 = new byte[32];
                for (int i = 0; i != array2.Length; i++)
                {
                    array[i] = octets[31 - i];
                }
                for (int k = 0; k != array.Length; k++)
                {
                    array2[k] = octets[63 - k];
                }
                ECDomainParameters byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet);
                if (byOid == null)
                {
                    return(null);
                }
                ECPoint q = byOid.Curve.CreatePoint(new BigInteger(1, array), new BigInteger(1, array2));
                return(new ECPublicKeyParameters("ECGOST3410", q, gost3410PublicKeyAlgParameters.PublicKeyParamSet));
            }
            if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters((Asn1Sequence)algorithmID.Parameters);
                DerOctetString derOctetString;
                try
                {
                    derOctetString = (DerOctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                    IL_0480 :;
                }
                byte[] octets2 = derOctetString.GetOctets();
                byte[] array3  = new byte[octets2.Length];
                for (int l = 0; l != octets2.Length; l++)
                {
                    array3[l] = octets2[octets2.Length - 1 - l];
                }
                BigInteger y = new BigInteger(1, array3);
                return(new Gost3410PublicKeyParameters(y, gost3410PublicKeyAlgParameters2.PublicKeyParamSet));
            }
            throw new SecurityUtilityException("algorithm identifier in key not recognised: " + objectID);
        }
        public virtual bool Match(
            object obj)
        {
            X509Certificate c = obj as X509Certificate;

            if (c == null)
            {
                return(false);
            }

            if (!MatchExtension(authorityKeyIdentifier, c, X509Extensions.AuthorityKeyIdentifier))
            {
                return(false);
            }

            if (basicConstraints != -1)
            {
                int bc = c.GetBasicConstraints();

                if (basicConstraints == -2)
                {
                    if (bc != -1)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (bc < basicConstraints)
                    {
                        return(false);
                    }
                }
            }

            if (certificate != null && !certificate.Equals(c))
            {
                return(false);
            }

            if (certificateValid != null && !c.IsValid(certificateValid.Value))
            {
                return(false);
            }

            if (extendedKeyUsage != null)
            {
                IList eku = c.GetExtendedKeyUsage();

                // Note: if no extended key usage set, all key purposes are implicitly allowed

                if (eku != null)
                {
                    foreach (DerObjectIdentifier oid in extendedKeyUsage)
                    {
                        if (!eku.Contains(oid.Id))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (issuer != null && !issuer.Equivalent(c.IssuerDN, true))
            {
                return(false);
            }

            if (keyUsage != null)
            {
                bool[] ku = c.GetKeyUsage();

                // Note: if no key usage set, all key purposes are implicitly allowed

                if (ku != null)
                {
                    for (int i = 0; i < 9; ++i)
                    {
                        if (keyUsage[i] && !ku[i])
                        {
                            return(false);
                        }
                    }
                }
            }

            if (policy != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CertificatePolicies);
                if (extVal == null)
                {
                    return(false);
                }

                Asn1Sequence certPolicies = Asn1Sequence.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal));

                if (policy.Count < 1 && certPolicies.Count < 1)
                {
                    return(false);
                }

                bool found = false;
                foreach (PolicyInformation pi in certPolicies)
                {
                    if (policy.Contains(pi.PolicyIdentifier))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }

            if (privateKeyValid != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
                if (extVal == null)
                {
                    return(false);
                }

                PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal));

                DateTime dt        = privateKeyValid.Value;
                DateTime notAfter  = pkup.NotAfter.ToDateTime();
                DateTime notBefore = pkup.NotBefore.ToDateTime();

                if (dt.CompareTo(notAfter) > 0 || dt.CompareTo(notBefore) < 0)
                {
                    return(false);
                }
            }

            if (serialNumber != null && !serialNumber.Equals(c.SerialNumber))
            {
                return(false);
            }

            if (subject != null && !subject.Equivalent(c.SubjectDN, true))
            {
                return(false);
            }

            if (!MatchExtension(subjectKeyIdentifier, c, X509Extensions.SubjectKeyIdentifier))
            {
                return(false);
            }

            if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(c)))
            {
                return(false);
            }

            if (subjectPublicKeyAlgID != null &&
                !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(c).AlgorithmID))
            {
                return(false);
            }

            return(true);
        }
    public static ICipherParameters GenerateCipherParameters(string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters)
    {
        string text = (string)algorithms[Platform.ToUpperInvariant(algorithm)];

        byte[] array          = null;
        byte[] salt           = null;
        int    iterationCount = 0;

        if (IsPkcs12(text))
        {
            Pkcs12PbeParams instance = Pkcs12PbeParams.GetInstance(pbeParameters);
            salt           = instance.GetIV();
            iterationCount = instance.Iterations.IntValue;
            array          = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
        }
        else if (!IsPkcs5Scheme2(text))
        {
            PbeParameter instance2 = PbeParameter.GetInstance(pbeParameters);
            salt           = instance2.GetSalt();
            iterationCount = instance2.IterationCount.IntValue;
            array          = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
        }
        ICipherParameters parameters = null;

        if (IsPkcs5Scheme2(text))
        {
            PbeS2Parameters     instance3        = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
            AlgorithmIdentifier encryptionScheme = instance3.EncryptionScheme;
            DerObjectIdentifier algorithm2       = encryptionScheme.Algorithm;
            Asn1Object          obj       = encryptionScheme.Parameters.ToAsn1Object();
            Pbkdf2Params        instance4 = Pbkdf2Params.GetInstance(instance3.KeyDerivationFunc.Parameters.ToAsn1Object());
            byte[] array2;
            if (algorithm2.Equals(PkcsObjectIdentifiers.RC2Cbc))
            {
                RC2CbcParameter instance5 = RC2CbcParameter.GetInstance(obj);
                array2 = instance5.GetIV();
            }
            else
            {
                array2 = Asn1OctetString.GetInstance(obj).GetOctets();
            }
            salt           = instance4.GetSalt();
            iterationCount = instance4.IterationCount.IntValue;
            array          = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            int keySize = (instance4.KeyLength != null) ? (instance4.KeyLength.IntValue * 8) : GeneratorUtilities.GetDefaultKeySize(algorithm2);
            PbeParametersGenerator pbeParametersGenerator = MakePbeGenerator((string)algorithmType[text], null, array, salt, iterationCount);
            parameters = pbeParametersGenerator.GenerateDerivedParameters(algorithm2.Id, keySize);
            if (array2 != null && !Arrays.AreEqual(array2, new byte[array2.Length]))
            {
                parameters = new ParametersWithIV(parameters, array2);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithSHA-1"))
        {
            PbeParametersGenerator pbeParametersGenerator2 = MakePbeGenerator((string)algorithmType[text], new Sha1Digest(), array, salt, iterationCount);
            if (text.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 128, 128);
            }
            else if (text.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 192, 128);
            }
            else if (text.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 256, 128);
            }
            else if (text.Equals("PBEwithSHA-1and128bitRC4"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 128);
            }
            else if (text.Equals("PBEwithSHA-1and40bitRC4"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 40);
            }
            else if (text.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 192, 64);
            }
            else if (text.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 128, 64);
            }
            else if (text.Equals("PBEwithSHA-1and128bitRC2-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 128, 64);
            }
            else if (text.Equals("PBEwithSHA-1and40bitRC2-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 40, 64);
            }
            else if (text.Equals("PBEwithSHA-1andDES-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("DES", 64, 64);
            }
            else if (text.Equals("PBEwithSHA-1andRC2-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 64, 64);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithSHA-256"))
        {
            PbeParametersGenerator pbeParametersGenerator3 = MakePbeGenerator((string)algorithmType[text], new Sha256Digest(), array, salt, iterationCount);
            if (text.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 128, 128);
            }
            else if (text.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 192, 128);
            }
            else if (text.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 256, 128);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithMD5"))
        {
            PbeParametersGenerator pbeParametersGenerator4 = MakePbeGenerator((string)algorithmType[text], new MD5Digest(), array, salt, iterationCount);
            if (text.Equals("PBEwithMD5andDES-CBC"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("DES", 64, 64);
            }
            else if (text.Equals("PBEwithMD5andRC2-CBC"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("RC2", 64, 64);
            }
            else if (text.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 128, 128);
            }
            else if (text.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 192, 128);
            }
            else if (text.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 256, 128);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithMD2"))
        {
            PbeParametersGenerator pbeParametersGenerator5 = MakePbeGenerator((string)algorithmType[text], new MD2Digest(), array, salt, iterationCount);
            if (text.Equals("PBEwithMD2andDES-CBC"))
            {
                parameters = pbeParametersGenerator5.GenerateDerivedParameters("DES", 64, 64);
            }
            else if (text.Equals("PBEwithMD2andRC2-CBC"))
            {
                parameters = pbeParametersGenerator5.GenerateDerivedParameters("RC2", 64, 64);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithHmac"))
        {
            string  algorithm3 = text.Substring("PBEwithHmac".Length);
            IDigest digest     = DigestUtilities.GetDigest(algorithm3);
            PbeParametersGenerator pbeParametersGenerator6 = MakePbeGenerator((string)algorithmType[text], digest, array, salt, iterationCount);
            int keySize2 = digest.GetDigestSize() * 8;
            parameters = pbeParametersGenerator6.GenerateDerivedMacParameters(keySize2);
        }
        Array.Clear(array, 0, array.Length);
        return(FixDesParity(text, parameters));
    }
        public static AsymmetricKeyParameter CreateKey(
            PrivateKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.PrivateKeyAlgorithm;
            DerObjectIdentifier algOid = algID.ObjectID;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure(
                    Asn1Sequence.GetInstance(keyInfo.ParsePrivateKey()));

                return(new RsaPrivateCrtKeyParameters(
                           keyStructure.Modulus,
                           keyStructure.PublicExponent,
                           keyStructure.PrivateExponent,
                           keyStructure.Prime1,
                           keyStructure.Prime2,
                           keyStructure.Exponent1,
                           keyStructure.Exponent2,
                           keyStructure.Coefficient));
            }
            // TODO?
//			else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                DHParameter para = new DHParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                BigInteger   lVal     = para.L;
                int          l        = lVal == null ? 0 : lVal.IntValue;
                DHParameters dhParams = new DHParameters(para.P, para.G, null, l);

                return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                return(new ElGamalPrivateKeyParameters(
                           derX.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
            {
                DerInteger    derX = (DerInteger)keyInfo.ParsePrivateKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPrivateKeyParameters(derX.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECPrivateKeyStructure ec = new ECPrivateKeyStructure(
                    Asn1Sequence.GetInstance(keyInfo.ParsePrivateKey()));
                BigInteger d = ec.GetKey();

                if (para.IsNamedCurve)
                {
                    return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPrivateKeyParameters(d, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));

                Asn1Object            privKey = keyInfo.ParsePrivateKey();
                ECPrivateKeyStructure ec;

                if (privKey is DerInteger)
                {
                    // TODO Do we need to pass any parameters here?
                    ec = new ECPrivateKeyStructure(((DerInteger)privKey).Value);
                }
                else
                {
                    ec = ECPrivateKeyStructure.GetInstance(privKey);
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key");
                }

                return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));

                DerOctetString derX = (DerOctetString)keyInfo.ParsePrivateKey();
                BigInteger     x    = new BigInteger(1, Arrays.Reverse(derX.GetOctets()));

                return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised");
            }
        }
        public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo)
        {
            //IL_02a2: Unknown result type (might be due to invalid IL or missing references)
            AlgorithmIdentifier privateKeyAlgorithm = keyInfo.PrivateKeyAlgorithm;
            DerObjectIdentifier algorithm           = privateKeyAlgorithm.Algorithm;

            if (algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption) || algorithm.Equals(X509ObjectIdentifiers.IdEARsa) || algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algorithm.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPrivateKeyStructure instance = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());
                return(new RsaPrivateCrtKeyParameters(instance.Modulus, instance.PublicExponent, instance.PrivateExponent, instance.Prime1, instance.Prime2, instance.Exponent1, instance.Exponent2, instance.Coefficient));
            }
            if (algorithm.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                DHParameter  dHParameter = new DHParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object()));
                DerInteger   derInteger  = (DerInteger)keyInfo.ParsePrivateKey();
                int          l           = dHParameter.L?.IntValue ?? 0;
                DHParameters parameters  = new DHParameters(dHParameter.P, dHParameter.G, null, l);
                return(new DHPrivateKeyParameters(derInteger.Value, parameters, algorithm));
            }
            if (algorithm.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object()));
                DerInteger       derInteger2      = (DerInteger)keyInfo.ParsePrivateKey();
                return(new ElGamalPrivateKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G)));
            }
            if (algorithm.Equals(X9ObjectIdentifiers.IdDsa))
            {
                DerInteger    derInteger3 = (DerInteger)keyInfo.ParsePrivateKey();
                Asn1Encodable parameters2 = privateKeyAlgorithm.Parameters;
                DsaParameters parameters3 = null;
                if (parameters2 != null)
                {
                    DsaParameter instance2 = DsaParameter.GetInstance(parameters2.ToAsn1Object());
                    parameters3 = new DsaParameters(instance2.P, instance2.Q, instance2.G);
                }
                return(new DsaPrivateKeyParameters(derInteger3.Value, parameters3));
            }
            if (algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters        x962Parameters = new X962Parameters(privateKeyAlgorithm.Parameters.ToAsn1Object());
                X9ECParameters        x9ECParameters = ((!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters));
                ECPrivateKeyStructure instance3      = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());
                BigInteger            key            = instance3.GetKey();
                if (x962Parameters.IsNamedCurve)
                {
                    return(new ECPrivateKeyParameters("EC", key, (DerObjectIdentifier)x962Parameters.Parameters));
                }
                ECDomainParameters parameters4 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed());
                return(new ECPrivateKeyParameters(key, parameters4));
            }
            if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object()));
                ECDomainParameters             byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet);
                if (byOid == null)
                {
                    throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key");
                }
                Asn1Object            asn1Object            = keyInfo.ParsePrivateKey();
                ECPrivateKeyStructure eCPrivateKeyStructure = ((!(asn1Object is DerInteger)) ? ECPrivateKeyStructure.GetInstance(asn1Object) : new ECPrivateKeyStructure(byOid.N.BitLength, ((DerInteger)asn1Object).Value));
                return(new ECPrivateKeyParameters("ECGOST3410", eCPrivateKeyStructure.GetKey(), gost3410PublicKeyAlgParameters.PublicKeyParamSet));
            }
            if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object()));
                DerOctetString derOctetString = (DerOctetString)keyInfo.ParsePrivateKey();
                BigInteger     x = new BigInteger(1, Arrays.Reverse(derOctetString.GetOctets()));
                return(new Gost3410PrivateKeyParameters(x, gost3410PublicKeyAlgParameters2.PublicKeyParamSet));
            }
            throw new SecurityUtilityException("algorithm identifier in key not recognised");
        }
Example #15
0
        // RFC3852, section 5.1:
        // IF ((certificates is present) AND
        //    (any certificates with a type of other are present)) OR
        //    ((crls is present) AND
        //    (any crls with a type of other are present))
        // THEN version MUST be 5
        // ELSE
        //    IF (certificates is present) AND
        //       (any version 2 attribute certificates are present)
        //    THEN version MUST be 4
        //    ELSE
        //       IF ((certificates is present) AND
        //          (any version 1 attribute certificates are present)) OR
        //          (any SignerInfo structures are version 3) OR
        //          (encapContentInfo eContentType is other than id-data)
        //       THEN version MUST be 3
        //       ELSE version MUST be 1
        //
        private DerInteger CalculateVersion(
            DerObjectIdentifier contentOid,
            Asn1Set certs,
            Asn1Set crls,
            Asn1Set signerInfs)
        {
            bool otherCert       = false;
            bool otherCrl        = false;
            bool attrCertV1Found = false;
            bool attrCertV2Found = false;

            if (certs != null)
            {
                foreach (object obj in certs)
                {
                    if (obj is Asn1TaggedObject)
                    {
                        Asn1TaggedObject tagged = (Asn1TaggedObject)obj;

                        if (tagged.TagNo == 1)
                        {
                            attrCertV1Found = true;
                        }
                        else if (tagged.TagNo == 2)
                        {
                            attrCertV2Found = true;
                        }
                        else if (tagged.TagNo == 3)
                        {
                            otherCert = true;
                            break;
                        }
                    }
                }
            }

            if (otherCert)
            {
                return(new DerInteger(5));
            }

            if (crls != null)
            {
                foreach (object obj in crls)
                {
                    if (obj is Asn1TaggedObject)
                    {
                        otherCrl = true;
                        break;
                    }
                }
            }

            if (otherCrl)
            {
                return(new DerInteger(5));
            }

            if (attrCertV2Found)
            {
                return(new DerInteger(4));
            }

            if (attrCertV1Found)
            {
                return(new DerInteger(3));
            }

            if (contentOid.Equals(CmsObjectIdentifiers.Data) &&
                !CheckForVersion3(signerInfs))
            {
                return(new DerInteger(1));
            }

            return(new DerInteger(3));
        }
Example #16
0
        public virtual bool Match(object obj)
        {
            X509Certificate x509Certificate = obj as X509Certificate;

            if (x509Certificate == null)
            {
                return(false);
            }
            if (!MatchExtension(authorityKeyIdentifier, x509Certificate, X509Extensions.AuthorityKeyIdentifier))
            {
                return(false);
            }
            if (basicConstraints != -1)
            {
                int num = x509Certificate.GetBasicConstraints();
                if (basicConstraints == -2)
                {
                    if (num != -1)
                    {
                        return(false);
                    }
                }
                else if (num < basicConstraints)
                {
                    return(false);
                }
            }
            if (certificate != null && !certificate.Equals(x509Certificate))
            {
                return(false);
            }
            if (certificateValid != null && !x509Certificate.IsValid(certificateValid.Value))
            {
                return(false);
            }
            if (extendedKeyUsage != null)
            {
                global::System.Collections.IList list = x509Certificate.GetExtendedKeyUsage();
                if (list != null)
                {
                    {
                        global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)extendedKeyUsage).GetEnumerator();
                        try
                        {
                            while (enumerator.MoveNext())
                            {
                                DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current();
                                if (!list.Contains((object)derObjectIdentifier.Id))
                                {
                                    return(false);
                                }
                            }
                        }
                        finally
                        {
                            global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                            if (disposable != null)
                            {
                                disposable.Dispose();
                            }
                        }
                    }
                }
            }
            if (issuer != null && !issuer.Equivalent(x509Certificate.IssuerDN, inOrder: true))
            {
                return(false);
            }
            if (keyUsage != null)
            {
                bool[] array = x509Certificate.GetKeyUsage();
                if (array != null)
                {
                    for (int i = 0; i < 9; i++)
                    {
                        if (keyUsage[i] && !array[i])
                        {
                            return(false);
                        }
                    }
                }
            }
            if (policy != null)
            {
                Asn1OctetString extensionValue = x509Certificate.GetExtensionValue(X509Extensions.CertificatePolicies);
                if (extensionValue == null)
                {
                    return(false);
                }
                Asn1Sequence instance = Asn1Sequence.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
                if (((global::System.Collections.ICollection)policy).get_Count() < 1 && instance.Count < 1)
                {
                    return(false);
                }
                bool flag = false;
                {
                    global::System.Collections.IEnumerator enumerator = instance.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            PolicyInformation policyInformation = (PolicyInformation)enumerator.get_Current();
                            if (policy.Contains(policyInformation.PolicyIdentifier))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    finally
                    {
                        global::System.IDisposable disposable2 = enumerator as global::System.IDisposable;
                        if (disposable2 != null)
                        {
                            disposable2.Dispose();
                        }
                    }
                }
                if (!flag)
                {
                    return(false);
                }
            }
            if (privateKeyValid != null)
            {
                Asn1OctetString extensionValue2 = x509Certificate.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
                if (extensionValue2 == null)
                {
                    return(false);
                }
                PrivateKeyUsagePeriod   instance2 = PrivateKeyUsagePeriod.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
                global::System.DateTime value     = privateKeyValid.Value;
                global::System.DateTime dateTime  = instance2.NotAfter.ToDateTime();
                global::System.DateTime dateTime2 = instance2.NotBefore.ToDateTime();
                if (value.CompareTo((object)dateTime) > 0 || value.CompareTo((object)dateTime2) < 0)
                {
                    return(false);
                }
            }
            if (serialNumber != null && !serialNumber.Equals(x509Certificate.SerialNumber))
            {
                return(false);
            }
            if (subject != null && !subject.Equivalent(x509Certificate.SubjectDN, inOrder: true))
            {
                return(false);
            }
            if (!MatchExtension(subjectKeyIdentifier, x509Certificate, X509Extensions.SubjectKeyIdentifier))
            {
                return(false);
            }
            if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(x509Certificate)))
            {
                return(false);
            }
            if (subjectPublicKeyAlgID != null && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(x509Certificate).AlgorithmID))
            {
                return(false);
            }
            return(true);
        }
Example #17
0
        public static AsymmetricKeyParameter CreateKey(
            SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.Algorithm;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
                    keyInfo.ParsePublicKey());

                return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.ParsePublicKey());

                BigInteger y = dhPublicKey.Y.Value;

                if (IsPkcsDHParam(seq))
                {
                    return(ReadPkcsDHParam(algOid, y, seq));
                }

                DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);

                BigInteger p = dhParams.P.Value;
                BigInteger g = dhParams.G.Value;
                BigInteger q = dhParams.Q.Value;

                BigInteger j = null;
                if (dhParams.J != null)
                {
                    j = dhParams.J.Value;
                }

                DHValidationParameters validation        = null;
                DHValidationParms      dhValidationParms = dhParams.ValidationParms;
                if (dhValidationParms != null)
                {
                    byte[]     seed        = dhValidationParms.Seed.GetBytes();
                    BigInteger pgenCounter = dhValidationParms.PgenCounter.Value;

                    // TODO Check pgenCounter size?

                    validation = new DHValidationParameters(seed, pgenCounter.IntValue);
                }

                return(new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation)));
            }
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DerInteger derY = (DerInteger)keyInfo.ParsePublicKey();

                return(ReadPkcsDHParam(algOid, derY.Value, seq));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.ParsePublicKey();

                return(new ElGamalPublicKeyParameters(
                           derY.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) ||
                     algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger    derY = (DerInteger)keyInfo.ParsePublicKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPublicKeyParameters(derY.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                Asn1OctetString key  = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
                X9ECPoint       derQ = new X9ECPoint(x9.Curve, key);
                ECPoint         q    = derQ.Point;

                if (para.IsNamedCurve)
                {
                    return(new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPublicKeyParameters(q, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams        = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);
                DerObjectIdentifier            publicKeyParamSet = gostParams.PublicKeyParamSet;

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(publicKeyParamSet);
                if (ecP == null)
                {
                    return(null);
                }

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.ParsePublicKey();
                }
                catch (IOException e)
                {
                    throw new ArgumentException("error recovering GOST3410_2001 public key", e);
                }

                int fieldSize = 32;
                int keySize   = 2 * fieldSize;

                byte[] keyEnc = key.GetOctets();
                if (keyEnc.Length != keySize)
                {
                    throw new ArgumentException("invalid length for GOST3410_2001 public key");
                }

                byte[] x9Encoding = new byte[1 + keySize];
                x9Encoding[0] = 0x04;
                for (int i = 1; i <= fieldSize; ++i)
                {
                    x9Encoding[i]             = keyEnc[fieldSize - i];
                    x9Encoding[i + fieldSize] = keyEnc[keySize - i];
                }

                ECPoint q = ecP.Curve.DecodePoint(x9Encoding);

                return(new ECPublicKeyParameters("ECGOST3410", q, publicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.ParsePublicKey();
                }
                catch (IOException e)
                {
                    throw new ArgumentException("error recovering GOST3410_94 public key", e);
                }

                byte[] keyBytes = Arrays.Reverse(key.GetOctets()); // was little endian

                BigInteger y = new BigInteger(1, keyBytes);

                return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X25519))
            {
                return(new X25519PublicKeyParameters(GetRawKey(keyInfo, X25519PublicKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X448))
            {
                return(new X448PublicKeyParameters(GetRawKey(keyInfo, X448PublicKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519))
            {
                return(new Ed25519PublicKeyParameters(GetRawKey(keyInfo, Ed25519PublicKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448))
            {
                return(new Ed448PublicKeyParameters(GetRawKey(keyInfo, Ed448PublicKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256) ||
                     algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512))
            {
                Gost3410PublicKeyAlgParameters gostParams        = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);
                DerObjectIdentifier            publicKeyParamSet = gostParams.PublicKeyParamSet;

                ECGost3410Parameters ecDomainParameters = new ECGost3410Parameters(
                    new ECNamedDomainParameters(publicKeyParamSet, ECGost3410NamedCurves.GetByOid(publicKeyParamSet)),
                    publicKeyParamSet,
                    gostParams.DigestParamSet,
                    gostParams.EncryptionParamSet);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.ParsePublicKey();
                }
                catch (IOException e)
                {
                    throw new ArgumentException("error recovering GOST3410_2012 public key", e);
                }

                int fieldSize = 32;
                if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512))
                {
                    fieldSize = 64;
                }
                int keySize = 2 * fieldSize;

                byte[] keyEnc = key.GetOctets();
                if (keyEnc.Length != keySize)
                {
                    throw new ArgumentException("invalid length for GOST3410_2012 public key");
                }

                byte[] x9Encoding = new byte[1 + keySize];
                x9Encoding[0] = 0x04;
                for (int i = 1; i <= fieldSize; ++i)
                {
                    x9Encoding[i]             = keyEnc[fieldSize - i];
                    x9Encoding[i + fieldSize] = keyEnc[keySize - i];
                }

                ECPoint q = ecDomainParameters.Curve.DecodePoint(x9Encoding);

                return(new ECPublicKeyParameters(q, ecDomainParameters));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in public key not recognised: " + algOid);
            }
        }
Example #18
0
        /**
         * return an IList of the values found in the name, in the order they
         * were found, with the DN label corresponding to passed in oid.
         */
        public IList GetValueList(DerObjectIdentifier oid)
        {
            IList v = Platform.CreateArrayList();
            for (int i = 0; i != values.Count; i++)
            {
                if (null == oid || oid.Equals(ordering[i]))
                {
                    string val = (string)values[i];

                    if (val.StartsWith("\\#"))
                    {
                        val = val.Substring(1);
                    }

                    v.Add(val);
                }
            }
            return v;
        }
Example #19
0
        public override string ToString()
        {
            //IL_0000: Unknown result type (might be due to invalid IL or missing references)
            //IL_0006: Expected O, but got Unknown
            StringBuilder val     = new StringBuilder();
            string        newLine = Platform.NewLine;

            val.Append("  [0]         Version: ").Append(Version).Append(newLine);
            val.Append("         SerialNumber: ").Append((object)SerialNumber).Append(newLine);
            val.Append("             IssuerDN: ").Append((object)IssuerDN).Append(newLine);
            val.Append("           Start Date: ").Append((object)NotBefore).Append(newLine);
            val.Append("           Final Date: ").Append((object)NotAfter).Append(newLine);
            val.Append("            SubjectDN: ").Append((object)SubjectDN).Append(newLine);
            val.Append("           Public Key: ").Append((object)GetPublicKey()).Append(newLine);
            val.Append("  Signature Algorithm: ").Append(SigAlgName).Append(newLine);
            byte[] signature = GetSignature();
            val.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);
                val.Append("                       ").Append(Hex.ToHexString(signature, i, length)).Append(newLine);
            }
            X509Extensions extensions = c.TbsCertificate.Extensions;

            if (extensions != null)
            {
                global::System.Collections.IEnumerator enumerator = extensions.ExtensionOids.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    val.Append("       Extensions: \n");
                }
                do
                {
                    DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current();
                    X509Extension       extension           = extensions.GetExtension(derObjectIdentifier);
                    if (extension.Value != null)
                    {
                        byte[]     octets     = extension.Value.GetOctets();
                        Asn1Object asn1Object = Asn1Object.FromByteArray(octets);
                        val.Append("                       critical(").Append(extension.IsCritical).Append(") ");
                        try
                        {
                            if (derObjectIdentifier.Equals(X509Extensions.BasicConstraints))
                            {
                                val.Append((object)BasicConstraints.GetInstance(asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(X509Extensions.KeyUsage))
                            {
                                val.Append((object)KeyUsage.GetInstance(asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.NetscapeCertType))
                            {
                                val.Append((object)new NetscapeCertType((DerBitString)asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl))
                            {
                                val.Append((object)new NetscapeRevocationUrl((DerIA5String)asn1Object));
                            }
                            else if (derObjectIdentifier.Equals(MiscObjectIdentifiers.VerisignCzagExtension))
                            {
                                val.Append((object)new VerisignCzagExtension((DerIA5String)asn1Object));
                            }
                            else
                            {
                                val.Append(derObjectIdentifier.Id);
                                val.Append(" value = ").Append(Asn1Dump.DumpAsString(asn1Object));
                            }
                        }
                        catch (global::System.Exception)
                        {
                            val.Append(derObjectIdentifier.Id);
                            val.Append(" value = ").Append("*****");
                        }
                    }
                    val.Append(newLine);
                }while (enumerator.MoveNext());
            }
            return(val.ToString());
        }
Example #20
0
        public X9Curve(
            X9FieldID fieldID,
            BigInteger order,
            BigInteger cofactor,
            Asn1Sequence seq)
        {
            if (fieldID == null)
            {
                throw new ArgumentNullException("fieldID");
            }
            if (seq == null)
            {
                throw new ArgumentNullException("seq");
            }

            this.fieldIdentifier = fieldID.Identifier;

            if (fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField))
            {
                BigInteger p = ((DerInteger)fieldID.Parameters).Value;
                BigInteger A = new BigInteger(1, Asn1OctetString.GetInstance(seq[0]).GetOctets());
                BigInteger B = new BigInteger(1, Asn1OctetString.GetInstance(seq[1]).GetOctets());
                curve = new FpCurve(p, A, B, order, cofactor);
            }
            else if (fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField))
            {
                // Characteristic two field
                DerSequence         parameters     = (DerSequence)fieldID.Parameters;
                int                 m              = ((DerInteger)parameters[0]).IntValueExact;
                DerObjectIdentifier representation = (DerObjectIdentifier)parameters[1];

                int k1 = 0;
                int k2 = 0;
                int k3 = 0;
                if (representation.Equals(X9ObjectIdentifiers.TPBasis))
                {
                    // Trinomial basis representation
                    k1 = ((DerInteger)parameters[2]).IntValueExact;
                }
                else
                {
                    // Pentanomial basis representation
                    DerSequence pentanomial = (DerSequence)parameters[2];
                    k1 = ((DerInteger)pentanomial[0]).IntValueExact;
                    k2 = ((DerInteger)pentanomial[1]).IntValueExact;
                    k3 = ((DerInteger)pentanomial[2]).IntValueExact;
                }
                BigInteger A = new BigInteger(1, Asn1OctetString.GetInstance(seq[0]).GetOctets());
                BigInteger B = new BigInteger(1, Asn1OctetString.GetInstance(seq[1]).GetOctets());
                curve = new F2mCurve(m, k1, k2, k3, A, B, order, cofactor);
            }
            else
            {
                throw new ArgumentException("This type of ECCurve is not implemented");
            }

            if (seq.Count == 3)
            {
                seed = ((DerBitString)seq[2]).GetBytes();
            }
        }
        public static IAsymmetricKeyParameter CreateKey(
            PrivateKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.ObjectID;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure(
                    Asn1Sequence.GetInstance(keyInfo.PrivateKey));

                return(new RsaPrivateCrtKeyParameters(
                           keyStructure.Modulus,
                           keyStructure.PublicExponent,
                           keyStructure.PrivateExponent,
                           keyStructure.Prime1,
                           keyStructure.Prime2,
                           keyStructure.Exponent1,
                           keyStructure.Exponent2,
                           keyStructure.Coefficient));
            }
            // TODO?
//			else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                DHParameter para = new DHParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.PrivateKey;

                IBigInteger  lVal     = para.L;
                int          l        = lVal == null ? 0 : lVal.IntValue;
                DHParameters dhParams = new DHParameters(para.P, para.G, null, l);

                return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.PrivateKey;

                return(new ElGamalPrivateKeyParameters(
                           derX.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
            {
                DerInteger    derX = (DerInteger)keyInfo.PrivateKey;
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPrivateKeyParameters(derX.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());
                X9ECParameters ecP;

                if (para.IsNamedCurve)
                {
                    ecP = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    ecP = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECDomainParameters dParams = new ECDomainParameters(
                    ecP.Curve,
                    ecP.G,
                    ecP.N,
                    ecP.H,
                    ecP.GetSeed());

                ECPrivateKeyStructure ec = new ECPrivateKeyStructure(
                    Asn1Sequence.GetInstance(keyInfo.PrivateKey));

                return(new ECPrivateKeyParameters(ec.GetKey(), dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));

                ECPrivateKeyStructure ec = new ECPrivateKeyStructure(
                    Asn1Sequence.GetInstance(keyInfo.PrivateKey));

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    return(null);
                }

                return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));

                DerOctetString derX     = (DerOctetString)keyInfo.PrivateKey;
                byte[]         keyEnc   = derX.GetOctets();
                byte[]         keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i];                     // was little endian
                }

                IBigInteger x = new BigInteger(1, keyBytes);

                return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised");
            }
        }
Example #22
0
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];

            byte[] keyBytes       = null;
            byte[] salt           = null;
            int    iterationCount = 0;

            if (IsPkcs12(mechanism))
            {
                Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters);
                salt           = pbeParams.GetIV();
                iterationCount = pbeParams.Iterations.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
            }
            else if (IsPkcs5Scheme2(mechanism))
            {
                // See below
            }
            else
            {
                PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters);
                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            }

            ICipherParameters parameters = null;

            if (IsPkcs5Scheme2(mechanism))
            {
                PbeS2Parameters     s2p       = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
                AlgorithmIdentifier encScheme = s2p.EncryptionScheme;
                DerObjectIdentifier encOid    = encScheme.ObjectID;
                Asn1Object          encParams = encScheme.Parameters.ToAsn1Object();

                // TODO What about s2p.KeyDerivationFunc.ObjectID?
                Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object());

                byte[] iv;
                if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc))                 // PKCS5.B.2.3
                {
                    RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams);
                    iv = rc2Params.GetIV();
                }
                else
                {
                    iv = Asn1OctetString.GetInstance(encParams).GetOctets();
                }

                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);

                int keyLength = pbeParams.KeyLength != null
                                        ?       pbeParams.KeyLength.IntValue * 8
                                        :       GeneratorUtilities.GetDefaultKeySize(encOid);

                PbeParametersGenerator gen = MakePbeGenerator(
                    (string)algorithmType[mechanism], null, keyBytes, salt, iterationCount);

                parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength);

                if (iv != null)
                {
                    // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?)
                    if (Arrays.AreEqual(iv, new byte[iv.Length]))
                    {
                        //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****");
                    }
                    else
                    {
                        parameters = new ParametersWithIV(parameters, iv);
                    }
                }
            }
            else if (mechanism.StartsWith("PBEwithSHA-1"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-1and128bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 40);
                }
                else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 40, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithSHA-256"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithMD5"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithMD5andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithMD2"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount);
                if (mechanism.Equals("PBEwithMD2andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD2andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
            }
            else if (mechanism.StartsWith("PBEwithHmac"))
            {
                string  digestName = mechanism.Substring("PBEwithHmac".Length);
                IDigest digest     = DigestUtilities.GetDigest(digestName);

                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount);

                int bitLen = digest.GetDigestSize() * 8;
                parameters = generator.GenerateDerivedMacParameters(bitLen);
            }

            Array.Clear(keyBytes, 0, keyBytes.Length);

            return(FixDesParity(mechanism, parameters));
        }
Example #23
0
        private bool DoVerify(
            AsymmetricKeyParameter key,
            Asn1.Cms.AttributeTable signedAttrTable)
        {
            string  digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
            IDigest digest     = Helper.GetDigestInstance(digestName);

            DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID;
            Asn1Encodable       sigParams = this.encryptionAlgorithm.Parameters;
            ISigner             sig;

            if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
            {
                // RFC 4056 2.2
                // When the id-RSASSA-PSS algorithm identifier is used for a signature,
                // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
                if (sigParams == null)
                {
                    throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");
                }

                try
                {
                    // TODO Provide abstract configuration mechanism

                    Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
                        sigParams.ToAsn1Object());

                    if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
                    }
                    if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");
                    }

                    IDigest pssDigest    = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID);
                    int     saltLength   = pss.SaltLength.Value.IntValue;
                    byte    trailerField = (byte)pss.TrailerField.Value.IntValue;

                    // RFC 4055 3.1
                    // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
                    if (trailerField != 1)
                    {
                        throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");
                    }

                    sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength);
                }
                catch (Exception e)
                {
                    throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
                }
            }
            else
            {
                // TODO Probably too strong a check at the moment
//				if (sigParams != null)
//					throw new CmsException("unrecognised signature parameters provided");

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

                sig = Helper.GetSignatureInstance(signatureName);
            }

            try
            {
                sig.Init(false, key);

                if (signedAttributes == null)
                {
                    if (content != null)
                    {
                        content.Write(new CmsSignedDataGenerator.SigOutputStream(sig));
                        content.Write(new CmsSignedDataGenerator.DigOutputStream(digest));

                        resultDigest = DigestUtilities.DoFinal(digest);
                    }
                    else
                    {
                        resultDigest = digestCalculator.GetDigest();

                        // need to decrypt signature and check message bytes
                        return(VerifyDigest(resultDigest, key, this.GetSignature()));
                    }
                }
                else
                {
                    byte[] hash;
                    if (content != null)
                    {
                        content.Write(
                            new CmsSignedDataGenerator.DigOutputStream(digest));

                        hash = DigestUtilities.DoFinal(digest);
                    }
                    else if (digestCalculator != null)
                    {
                        hash = digestCalculator.GetDigest();
                    }
                    else
                    {
                        hash = null;
                    }

                    resultDigest = hash;

                    Asn1.Cms.Attribute dig  = signedAttrTable[Asn1.Cms.CmsAttributes.MessageDigest];
                    Asn1.Cms.Attribute type = signedAttrTable[Asn1.Cms.CmsAttributes.ContentType];

                    if (dig == null)
                    {
                        throw new SignatureException("no hash for content found in signed attributes");
                    }

                    if (type == null && !contentType.Equals(CmsAttributes.CounterSignature))
                    {
                        throw new SignatureException("no content type id found in signed attributes");
                    }

                    Asn1Object hashObj = dig.AttrValues[0].ToAsn1Object();

                    if (hashObj is Asn1OctetString)
                    {
                        byte[] signedHash = ((Asn1OctetString)hashObj).GetOctets();

                        if (!Arrays.AreEqual(hash, signedHash))
                        {
                            throw new SignatureException("content hash found in signed attributes different");
                        }
                    }
                    else if (hashObj is DerNull)
                    {
                        if (hash != null)
                        {
                            throw new SignatureException("NULL hash found in signed attributes when one expected");
                        }
                    }

                    if (type != null)
                    {
                        DerObjectIdentifier typeOID = (DerObjectIdentifier)type.AttrValues[0];

                        if (!typeOID.Equals(contentType))
                        {
                            throw new SignatureException("contentType in signed attributes different");
                        }
                    }

                    byte[] tmp = this.GetEncodedSignedAttributes();
                    sig.BlockUpdate(tmp, 0, tmp.Length);
                }

                return(sig.VerifySignature(this.GetSignature()));
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException(
                          "key not appropriate to signature in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException(
                          "can't process mime object to create signature.", e);
            }
            catch (SignatureException e)
            {
                throw new CmsException(
                          "invalid signature format in message: " + e.Message, e);
            }
        }
Example #24
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 = 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 #25
0
        protected virtual void LoadKeyBag(PrivateKeyInfo privKeyInfo, Asn1Set bagAttributes)
        {
            AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo);

            IDictionary        attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
            AsymmetricKeyEntry keyEntry   = new AsymmetricKeyEntry(privKey, attributes);

            string          alias   = null;
            Asn1OctetString localId = null;

            if (bagAttributes != null)
            {
                foreach (Asn1Sequence sq in bagAttributes)
                {
                    DerObjectIdentifier aOid    = DerObjectIdentifier.GetInstance(sq[0]);
                    Asn1Set             attrSet = Asn1Set.GetInstance(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] = keyEntry;
                        }
                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                        {
                            localId = (Asn1OctetString)attr;
                        }
                    }
                }
            }

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

                if (alias == null)
                {
                    keys[name] = keyEntry;
                }
                else
                {
                    // TODO There may have been more than one alias
                    localIds[alias] = name;
                }
            }
            else
            {
                unmarkedKeyEntry = keyEntry;
            }
        }
Example #26
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 #27
0
        public bool Equivalent(X509Name other)
        {
            if (other == null)
            {
                return(false);
            }
            if (other == this)
            {
                return(true);
            }
            int count = ordering.Count;

            if (count != other.ordering.Count)
            {
                return(false);
            }
            bool[] array = new bool[count];
            int    num;
            int    num2;
            int    num3;

            if (ordering[0].Equals(other.ordering[0]))
            {
                num  = 0;
                num2 = count;
                num3 = 1;
            }
            else
            {
                num  = count - 1;
                num2 = -1;
                num3 = -1;
            }
            for (int i = num; i != num2; i += num3)
            {
                bool flag = false;
                DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)ordering[i];
                string s = (string)values[i];
                for (int j = 0; j < count; j++)
                {
                    if (!array[j])
                    {
                        DerObjectIdentifier obj = (DerObjectIdentifier)other.ordering[j];
                        if (derObjectIdentifier.Equals(obj))
                        {
                            string s2 = (string)other.values[j];
                            if (equivalentStrings(s, s2))
                            {
                                array[j] = true;
                                flag     = true;
                                break;
                            }
                        }
                    }
                }
                if (!flag)
                {
                    return(false);
                }
            }
            return(true);
        }
Example #28
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;
                    }
                }
            }
        }
        public static AsymmetricKeyParameter CreateKey(
            SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.ObjectID;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
                    keyInfo.GetPublicKey());

                return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey());

                BigInteger y = dhPublicKey.Y.Value;

                if (IsPkcsDHParam(seq))
                {
                    return(ReadPkcsDHParam(algOid, y, seq));
                }

                DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);

                BigInteger p = dhParams.P.Value;
                BigInteger g = dhParams.G.Value;
                BigInteger q = dhParams.Q.Value;

                BigInteger j = null;
                if (dhParams.J != null)
                {
                    j = dhParams.J.Value;
                }

                DHValidationParameters validation        = null;
                DHValidationParms      dhValidationParms = dhParams.ValidationParms;
                if (dhValidationParms != null)
                {
                    byte[]     seed        = dhValidationParms.Seed.GetBytes();
                    BigInteger pgenCounter = dhValidationParms.PgenCounter.Value;

                    // TODO Check pgenCounter size?

                    validation = new DHValidationParameters(seed, pgenCounter.IntValue);
                }

                return(new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation)));
            }
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(ReadPkcsDHParam(algOid, derY.Value, seq));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(new ElGamalPublicKeyParameters(
                           derY.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) ||
                     algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger    derY = (DerInteger)keyInfo.GetPublicKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPublicKeyParameters(derY.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                Asn1OctetString key  = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
                X9ECPoint       derQ = new X9ECPoint(x9.Curve, key);
                ECPoint         q    = derQ.Point;

                if (para.IsNamedCurve)
                {
                    return(new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPublicKeyParameters(q, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = key.GetOctets();
                byte[] x      = new byte[32];
                byte[] y      = new byte[32];

                for (int i = 0; i != y.Length; i++)
                {
                    x[i] = keyEnc[32 - 1 - i];
                }

                for (int i = 0; i != x.Length; i++)
                {
                    y[i] = keyEnc[64 - 1 - i];
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    return(null);
                }

                ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y), false);

                return(new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                DerOctetString derY;
                try
                {
                    derY = (DerOctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc   = derY.GetOctets();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i];                     // was little endian
                }

                BigInteger y = new BigInteger(1, keyBytes);

                return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid);
            }
        }
Example #30
0
        /**
         * Create an AlgorithmIdentifier for the passed in encryption algorithm.
         *
         * @param encryptionOID OID for the encryption algorithm
         * @param keySize key size in bits (-1 if unknown)
         * @param random SecureRandom to use for parameter generation.
         * @return a full AlgorithmIdentifier including parameters
         * @throws IllegalArgumentException if encryptionOID cannot be matched
         */
        public static AlgorithmIdentifier GenerateEncryptionAlgID(DerObjectIdentifier encryptionOID, int keySize, SecureRandom random)

        {
            if (encryptionOID.Equals(NistObjectIdentifiers.IdAes128Cbc) ||
                encryptionOID.Equals(NistObjectIdentifiers.IdAes192Cbc) ||
                encryptionOID.Equals(NistObjectIdentifiers.IdAes256Cbc) ||
                encryptionOID.Equals(NttObjectIdentifiers.IdCamellia128Cbc) ||
                encryptionOID.Equals(NttObjectIdentifiers.IdCamellia192Cbc) ||
                encryptionOID.Equals(NttObjectIdentifiers.IdCamellia256Cbc) ||
                encryptionOID.Equals(KisaObjectIdentifiers.IdSeedCbc))
            {
                byte[] iv = new byte[16];

                random.NextBytes(iv);

                return(new AlgorithmIdentifier(encryptionOID, new DerOctetString(iv)));
            }
            else if (encryptionOID.Equals(PkcsObjectIdentifiers.DesEde3Cbc) ||
                     encryptionOID.Equals(IDEA_CBC) ||
                     encryptionOID.Equals(OiwObjectIdentifiers.DesCbc))
            {
                byte[] iv = new byte[8];

                random.NextBytes(iv);

                return(new AlgorithmIdentifier(encryptionOID, new DerOctetString(iv)));
            }
            else if (encryptionOID.Equals(CAST5_CBC))
            {
                byte[] iv = new byte[8];

                random.NextBytes(iv);

                Cast5CbcParameters cbcParams = new Cast5CbcParameters(iv, keySize);

                return(new AlgorithmIdentifier(encryptionOID, cbcParams));
            }
            else if (encryptionOID.Equals(PkcsObjectIdentifiers.rc4))
            {
                return(new AlgorithmIdentifier(encryptionOID, DerNull.Instance));
            }
            else if (encryptionOID.Equals(PkcsObjectIdentifiers.RC2Cbc))
            {
                byte[] iv = new byte[8];

                random.NextBytes(iv);

                RC2CbcParameter cbcParams = new RC2CbcParameter(rc2Table[128], iv);

                return(new AlgorithmIdentifier(encryptionOID, cbcParams));
            }
            else
            {
                throw new InvalidOperationException("unable to match algorithm");
            }
        }
Example #31
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());
        }
Example #32
0
        public static AsymmetricKeyParameter CreateKey(
            SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.ObjectID;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
                    keyInfo.GetPublicKey());

                return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent));
            }
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement) ||
                     algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                DHParameter para = new DHParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                BigInteger   lVal     = para.L;
                int          l        = lVal == null ? 0 : lVal.IntValue;
                DHParameters dhParams = new DHParameters(para.P, para.G, null, l);

                return(new DHPublicKeyParameters(derY.Value, dhParams));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(new ElGamalPublicKeyParameters(
                           derY.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) ||
                     algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger    derY = (DerInteger)keyInfo.GetPublicKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPublicKeyParameters(derY.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(
                    algID.Parameters.ToAsn1Object());
                X9ECParameters ecP;

                if (para.IsNamedCurve)
                {
                    // TODO ECGost3410NamedCurves support (returns ECDomainParameters though)

                    DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters;
                    ecP = X962NamedCurves.GetByOid(oid);

                    if (ecP == null)
                    {
                        ecP = SecNamedCurves.GetByOid(oid);

                        if (ecP == null)
                        {
                            ecP = NistNamedCurves.GetByOid(oid);

                            if (ecP == null)
                            {
                                ecP = TeleTrusTNamedCurves.GetByOid(oid);
                            }
                        }
                    }
                }
                else
                {
                    ecP = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECDomainParameters dParams = new ECDomainParameters(
                    ecP.Curve,
                    ecP.G,
                    ecP.N,
                    ecP.H,
                    ecP.GetSeed());

                DerBitString    bits = keyInfo.PublicKeyData;
                byte[]          data = bits.GetBytes();
                Asn1OctetString key  = new DerOctetString(data);

                X9ECPoint derQ = new X9ECPoint(dParams.Curve, key);

                return(new ECPublicKeyParameters(derQ.Point, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = key.GetOctets();
                byte[] x      = new byte[32];
                byte[] y      = new byte[32];

                for (int i = 0; i != y.Length; i++)
                {
                    x[i] = keyEnc[32 - 1 - i];
                }

                for (int i = 0; i != x.Length; i++)
                {
                    y[i] = keyEnc[64 - 1 - i];
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    return(null);
                }

                ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y), false);

                return(new ECPublicKeyParameters(q, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                DerOctetString derY;
                try
                {
                    derY = (DerOctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc   = derY.GetOctets();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i];                     // was little endian
                }

                BigInteger y = new BigInteger(1, keyBytes);

                return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid);
            }
        }
Example #33
0
        /**
         * test for equivalence - note: case is ignored.
         */
        public bool Equivalent(
            X509Name other)
        {
            if (other == null)
            {
                return(false);
            }

            if (other == this)
            {
                return(true);
            }

            int orderingSize = ordering.Count;

            if (orderingSize != other.ordering.Count)
            {
                return(false);
            }

            bool[] indexes = new bool[orderingSize];
            int    start, end, delta;

            if (ordering[0].Equals(other.ordering[0]))   // guess forward
            {
                start = 0;
                end   = orderingSize;
                delta = 1;
            }
            else  // guess reversed - most common problem
            {
                start = orderingSize - 1;
                end   = -1;
                delta = -1;
            }

            for (int i = start; i != end; i += delta)
            {
                bool found = false;
                DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
                string value            = (string)values[i];

                for (int j = 0; j < orderingSize; j++)
                {
                    if (indexes[j])
                    {
                        continue;
                    }

                    DerObjectIdentifier oOid = (DerObjectIdentifier)other.ordering[j];

                    if (oid.Equals(oOid))
                    {
                        string oValue = (string)other.values[j];

                        if (equivalentStrings(value, oValue))
                        {
                            indexes[j] = true;
                            found      = true;
                            break;
                        }
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }

            return(true);
        }
Example #34
0
 private static String LookupMnemonicByOID(DerObjectIdentifier oid)
 {
     if (oid.Equals(X509ObjectIdentifiers.Organization))
     {
         return("O");
     }
     if (oid.Equals(X509ObjectIdentifiers.OrganizationalUnitName))
     {
         return("OU");
     }
     if (oid.Equals(X509ObjectIdentifiers.CommonName))
     {
         return("CN");
     }
     if (oid.Equals(X509ObjectIdentifiers.CountryName))
     {
         return("C");
     }
     if (oid.Equals(X509ObjectIdentifiers.StateOrProvinceName))
     {
         return("ST");
     }
     if (oid.Equals(X509ObjectIdentifiers.LocalityName))
     {
         return("L");
     }
     if (oid.Equals(X509ObjectIdentifiers.IdSha1))
     {
         return("SHA1");
     }
     if (oid.Equals(NistObjectIdentifiers.IdSha224))
     {
         return("SHA224");
     }
     if (oid.Equals(NistObjectIdentifiers.IdSha256))
     {
         return("SHA256");
     }
     if (oid.Equals(NistObjectIdentifiers.IdSha384))
     {
         return("SHA384");
     }
     if (oid.Equals(NistObjectIdentifiers.IdSha512))
     {
         return("SHA512");
     }
     if (oid.Equals(PKCS1_SHA256_WITH_RSA_OID))
     {
         return("SHA256withRSA");
     }
     if (oid.Equals(PKCS1_SHA384_WITH_RSA_OID))
     {
         return("SHA384withRSA");
     }
     if (oid.Equals(PKCS1_SHA512_WITH_RSA_OID))
     {
         return("SHA512withRSA");
     }
     if (oid.Equals(PKCS1_SHA224_WITH_RSA_OID))
     {
         return("SHA224withRSA");
     }
     throw new ArgumentException("Unknown OID " + oid);
 }