private static Asn1Sequence FromCertificate(
            X509Certificate certificate)
        {
            try
            {
                GeneralName genName = new GeneralName(
                    PrincipalUtilities.GetIssuerX509Principal(certificate));

                if (certificate.Version == 3)
                {
                    Asn1OctetString ext = certificate.GetExtensionValue(X509Extensions.SubjectKeyIdentifier);

                    if (ext != null)
                    {
                        Asn1OctetString str = (Asn1OctetString)X509ExtensionUtilities.FromExtensionValue(ext);

                        return((Asn1Sequence) new AuthorityKeyIdentifier(
                                   str.GetOctets(), new GeneralNames(genName), certificate.SerialNumber).ToAsn1Object());
                    }
                }

                SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                    certificate.GetPublicKey());

                return((Asn1Sequence) new AuthorityKeyIdentifier(
                           info, new GeneralNames(genName), certificate.SerialNumber).ToAsn1Object());
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("Exception extracting certificate details", e);
            }
        }
 public void Validate(X509Certificate cert)
 {
     try
     {
         byte[] b = DigestUtilities.CalculateDigest(certID.GetHashAlgorithmName(), cert.GetEncoded());
         if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), b))
         {
             throw new TspValidationException("certificate hash does not match certID hash.");
         }
         if (certID.IssuerSerial != null)
         {
             if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
             {
                 throw new TspValidationException("certificate serial number does not match certID for signature.");
             }
             GeneralName[] names = certID.IssuerSerial.Issuer.GetNames();
             X509Name      issuerX509Principal = PrincipalUtilities.GetIssuerX509Principal(cert);
             bool          flag = false;
             for (int i = 0; i != names.Length; i++)
             {
                 if (names[i].TagNo == 4 && X509Name.GetInstance(names[i].Name).Equivalent(issuerX509Principal))
                 {
                     flag = true;
                     break;
                 }
             }
             if (!flag)
             {
                 throw new TspValidationException("certificate name does not match certID for signature. ");
             }
         }
         TspUtil.ValidateCertificate(cert);
         cert.CheckValidity(tstInfo.GenTime);
         if (!tsaSignerInfo.Verify(cert))
         {
             throw new TspValidationException("signature not created by certificate.");
         }
     }
     catch (CmsException ex)
     {
         if (ex.InnerException != null)
         {
             throw new TspException(ex.Message, ex.InnerException);
         }
         throw new TspException("CMS exception: " + ex, ex);
     }
     catch (CertificateEncodingException ex2)
     {
         throw new TspException("problem processing certificate: " + ex2, ex2);
     }
     catch (SecurityUtilityException ex3)
     {
         throw new TspException("cannot find algorithm: " + ex3.Message, ex3);
     }
 }
    public AttributeCertificateHolder(X509Certificate cert)
    {
        X509Name issuerX509Principal;

        try
        {
            issuerX509Principal = PrincipalUtilities.GetIssuerX509Principal(cert);
        }
        catch (Exception ex)
        {
            throw new CertificateParsingException(ex.Message);
        }
        holder = new Holder(new IssuerSerial(GenerateGeneralNames(issuerX509Principal), new DerInteger(cert.SerialNumber)));
    }
Exemplo n.º 4
0
        private static void ConfirmDataReceived(RecipientInformationStore recipients,
                                                byte[] expectedData, X509Certificate reciCert, AsymmetricKeyParameter reciPrivKey)
        {
            RecipientID rid = new RecipientID();

            rid.Issuer       = PrincipalUtilities.GetIssuerX509Principal(reciCert);
            rid.SerialNumber = reciCert.SerialNumber;

            RecipientInformation recipient = recipients[rid];

            Assert.IsNotNull(recipient);

            byte[] actualData = recipient.GetContent(reciPrivKey);
            Assert.IsTrue(Arrays.AreEqual(expectedData, actualData));
        }
Exemplo n.º 5
0
        public void TestECKeyAgree()
        {
            byte[] data = Hex.Decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");

            CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();

            edGen.AddKeyAgreementRecipient(
                CmsEnvelopedDataGenerator.ECDHSha1Kdf,
                OrigECKP.Private,
                OrigECKP.Public,
                ReciECCert,
                CmsEnvelopedDataGenerator.Aes128Wrap);

            MemoryStream bOut = new MemoryStream();

            Stream outStr = edGen.Open(bOut, CmsEnvelopedDataGenerator.Aes128Cbc);

            outStr.Write(data, 0, data.Length);

            outStr.Close();

            CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray());

            RecipientInformationStore recipients = ep.GetRecipientInfos();

            Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.Aes128Cbc);

            RecipientID recSel = new RecipientID();

//			recSel.SetIssuer(PrincipalUtilities.GetIssuerX509Principal(ReciECCert).GetEncoded());
            recSel.Issuer       = PrincipalUtilities.GetIssuerX509Principal(ReciECCert);
            recSel.SerialNumber = ReciECCert.SerialNumber;

            RecipientInformation recipient = recipients.GetFirstRecipient(recSel);

            CmsTypedStream recData = recipient.GetContentStream(ReciECKP.Private);

            Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream)));

            ep.Close();
        }
Exemplo n.º 6
0
            internal RecipientInfo ToRecipientInfo(
                KeyParameter key,
                SecureRandom random)
            {
                byte[] keyBytes = key.GetKey();

                if (pubKey != null)
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

                    keyWrapper.Init(true, new ParametersWithRandom(pubKey, random));

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    RecipientIdentifier recipId;
                    if (cert != null)
                    {
                        TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                            Asn1Object.FromByteArray(cert.GetTbsCertificate()));

                        Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber(
                            tbs.Issuer, tbs.SerialNumber.Value);

                        recipId = new RecipientIdentifier(encSid);
                    }
                    else
                    {
                        recipId = new RecipientIdentifier(subKeyId);
                    }

                    return(new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncAlg, encKey)));
                }
                else if (originator != null)
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(
                        DerObjectIdentifier.GetInstance(
                            Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id);

                    keyWrapper.Init(true, new ParametersWithRandom(secKey, random));

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    RecipientEncryptedKey rKey = new RecipientEncryptedKey(
                        new KeyAgreeRecipientIdentifier(
                            new Asn1.Cms.IssuerAndSerialNumber(
                                PrincipalUtilities.GetIssuerX509Principal(cert),
                                cert.SerialNumber)),
                        encKey);

                    return(new RecipientInfo(
                               new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(rKey))));
                }
                else if (derivationAlg != null)
                {
                    string   rfc3211WrapperName = Helper.GetRfc3211WrapperName(secKeyAlgorithm);
                    IWrapper keyWrapper         = Helper.CreateWrapper(rfc3211WrapperName);


                    // Note: In Java build, the IV is automatically generated in JCE layer
                    int    ivLength = rfc3211WrapperName.StartsWith("DESEDE") ? 8 : 16;
                    byte[] iv       = new byte[ivLength];
                    random.NextBytes(iv);


                    ICipherParameters parameters = new ParametersWithIV(secKey, iv);
                    keyWrapper.Init(true, new ParametersWithRandom(parameters, random));

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

//					byte[] iv = keyWrapper.GetIV();

                    DerSequence seq = new DerSequence(
                        new DerObjectIdentifier(secKeyAlgorithm),
                        new DerOctetString(iv));

                    keyEncAlg = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdAlgPwriKek, seq);

                    return(new RecipientInfo(new PasswordRecipientInfo(derivationAlg, keyEncAlg, encKey)));
                }
                else
                {
                    IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

                    keyWrapper.Init(true, new ParametersWithRandom(secKey, random));

                    Asn1OctetString encKey = new DerOctetString(
                        keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

                    return(new RecipientInfo(new KekRecipientInfo(secKeyId, keyEncAlg, encKey)));
                }
            }
        /**
         * Validate the time stamp token.
         * <p>
         * To be valid the token must be signed by the passed in certificate and
         * the certificate must be the one referred to by the SigningCertificate
         * attribute included in the the hashed attributes of the token. The
         * certificate must also have the ExtendedKeyUsageExtension with only
         * KeyPurposeID.IdKPTimeStamping and have been valid at the time the
         * timestamp was created.
         * </p>
         * <p>
         * A successful call to validate means all the above are true.
         * </p>
         */
        public void Validate(
            X509Certificate cert)
        {
            IDigest digest;

            try
            {
                digest = DigestUtilities.GetDigest("SHA-1");
            }
            catch (SecurityUtilityException e)
            {
                throw new TspException("cannot find algorithm: " + e.Message, e);
            }

            try
            {
                byte[] certEncoded = cert.GetEncoded();
                digest.BlockUpdate(certEncoded, 0, certEncoded.Length);
                byte[] hash = DigestUtilities.DoFinal(digest);

                if (!Arrays.AreEqual(certID.GetCertHash(), hash))
                {
                    throw new TspValidationException("certificate hash does not match certID hash.");
                }

                if (certID.IssuerSerial != null)
                {
                    if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
                    {
                        throw new TspValidationException("certificate serial number does not match certID for signature.");
                    }

                    GeneralName[] names     = certID.IssuerSerial.Issuer.GetNames();
                    X509Name      principal = PrincipalUtilities.GetIssuerX509Principal(cert);
                    bool          found     = false;

                    for (int i = 0; i != names.Length; i++)
                    {
                        if (names[i].TagNo == 4 &&
                            X509Name.GetInstance(names[i].Name).Equals(principal))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        throw new TspValidationException("certificate name does not match certID for signature. ");
                    }
                }

                TspUtil.ValidateCertificate(cert);

                cert.CheckValidity(tstInfo.GenTime);

                if (!tsaSignerInfo.Verify(cert))
                {
                    throw new TspValidationException("signature not created by certificate.");
                }
            }
            catch (CmsException e)
            {
                if (e.InnerException != null)
                {
                    throw new TspException(e.Message, e.InnerException);
                }

                throw new TspException("CMS exception: " + e, e);
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("problem processing certificate: " + e, e);
            }
        }
    public bool Match(X509Certificate x509Cert)
    {
        try
        {
            if (holder.BaseCertificateID != null)
            {
                return(holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer));
            }
            if (holder.EntityName != null && MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName))
            {
                return(true);
            }
            if (holder.ObjectDigestInfo != null)
            {
                IDigest digest = null;
                try
                {
                    digest = DigestUtilities.GetDigest(DigestAlgorithm);
                }
                catch (Exception)
                {
                    return(false);
                }
                switch (DigestedObjectType)
                {
                case 0:
                {
                    byte[] encoded2 = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(x509Cert.GetPublicKey()).GetEncoded();
                    digest.BlockUpdate(encoded2, 0, encoded2.Length);
                    break;
                }

                case 1:
                {
                    byte[] encoded = x509Cert.GetEncoded();
                    digest.BlockUpdate(encoded, 0, encoded.Length);
                    break;
                }
                }
                if (!Arrays.AreEqual(DigestUtilities.DoFinal(digest), GetObjectDigest()))
                {
                    return(false);
                }
            }
        }
        catch (CertificateEncodingException)
        {
            return(false);
        }
        return(false);
    }