示例#1
0
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(42);
            }
            X509CertificateStructure certificateAt        = serverCertificate.GetCertificateAt(0);
            SubjectPublicKeyInfo     subjectPublicKeyInfo = certificateAt.SubjectPublicKeyInfo;

            try
            {
                mServerPublicKey = PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
            }
            catch (Exception alertCause)
            {
                throw new TlsFatalAlert(43, alertCause);
                IL_003d :;
            }
            if (mTlsSigner == null)
            {
                try
                {
                    mDHAgreePublicKey = TlsDHUtilities.ValidateDHPublicKey((DHPublicKeyParameters)mServerPublicKey);
                }
                catch (InvalidCastException alertCause2)
                {
                    throw new TlsFatalAlert(46, alertCause2);
                    IL_0072 :;
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 8);
            }
            else
            {
                if (!mTlsSigner.IsValidPublicKey(mServerPublicKey))
                {
                    throw new TlsFatalAlert(46);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 128);
            }
            base.ProcessServerCertificate(serverCertificate);
        }
示例#2
0
        public override void ProcessServerCertificate(AbstractCertificate serverCertificate)
        {
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            Certificate realCertificate       = serverCertificate as Certificate;
            X509CertificateStructure x509Cert = null;

            if (realCertificate != null)
            {
                x509Cert = realCertificate.GetCertificateAt(0);
            }

            SubjectPublicKeyInfo keyInfo = serverCertificate.SubjectPublicKeyInfo();

            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            // Sanity check the PublicKeyFactory
            if (this.mServerPublicKey.IsPrivate)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            this.mRsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.mServerPublicKey);

            if (x509Cert != null)
            {
                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment);
            }

            base.ProcessServerCertificate(serverCertificate);
        }
示例#3
0
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            //IL_0058: Expected O, but got Unknown
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(42);
            }
            X509CertificateStructure certificateAt        = serverCertificate.GetCertificateAt(0);
            SubjectPublicKeyInfo     subjectPublicKeyInfo = certificateAt.SubjectPublicKeyInfo;

            try
            {
                mServerPublicKey = PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
            }
            catch (global::System.Exception alertCause)
            {
                throw new TlsFatalAlert(43, alertCause);
            }
            if (mTlsSigner == null)
            {
                try
                {
                    mECAgreePublicKey = TlsEccUtilities.ValidateECPublicKey((ECPublicKeyParameters)mServerPublicKey);
                }
                catch (InvalidCastException val)
                {
                    InvalidCastException alertCause2 = val;
                    throw new TlsFatalAlert(46, (global::System.Exception)(object) alertCause2);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 8);
            }
            else
            {
                if (!mTlsSigner.IsValidPublicKey(mServerPublicKey))
                {
                    throw new TlsFatalAlert(46);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 128);
            }
            base.ProcessServerCertificate(serverCertificate);
        }
    protected virtual void ReceiveCertificateVerifyMessage(MemoryStream buf)
    {
        if (mCertificateRequest == null)
        {
            throw new InvalidOperationException();
        }
        DigitallySigned digitallySigned = DigitallySigned.Parse(Context, buf);

        TlsProtocol.AssertEmpty(buf);
        try
        {
            SignatureAndHashAlgorithm algorithm = digitallySigned.Algorithm;
            byte[] hash;
            if (TlsUtilities.IsTlsV12(Context))
            {
                TlsUtilities.VerifySupportedSignatureAlgorithm(mCertificateRequest.SupportedSignatureAlgorithms, algorithm);
                hash = mPrepareFinishHash.GetFinalHash(algorithm.Hash);
            }
            else
            {
                hash = mSecurityParameters.SessionHash;
            }
            X509CertificateStructure certificateAt        = mPeerCertificate.GetCertificateAt(0);
            SubjectPublicKeyInfo     subjectPublicKeyInfo = certificateAt.SubjectPublicKeyInfo;
            AsymmetricKeyParameter   publicKey            = PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
            TlsSigner tlsSigner = TlsUtilities.CreateTlsSigner((byte)mClientCertificateType);
            tlsSigner.Init(Context);
            if (!tlsSigner.VerifyRawSignature(algorithm, digitallySigned.Signature, publicKey, hash))
            {
                throw new TlsFatalAlert(51);
            }
        }
        catch (TlsFatalAlert tlsFatalAlert)
        {
            throw tlsFatalAlert;
        }
        catch (Exception alertCause)
        {
            throw new TlsFatalAlert(51, alertCause);
        }
    }
示例#5
0
 public X509Certificate(X509CertificateStructure c)
 {
     this.c = c;
     try
     {
         Asn1OctetString extensionValue = GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
         if (extensionValue != null)
         {
             basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
         }
     }
     catch (Exception arg)
     {
         throw new CertificateParsingException("cannot construct BasicConstraints: " + arg);
         IL_004c :;
     }
     try
     {
         Asn1OctetString extensionValue2 = GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
         if (extensionValue2 != null)
         {
             DerBitString instance = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
             byte[]       bytes    = instance.GetBytes();
             int          num      = bytes.Length * 8 - instance.PadBits;
             keyUsage = new bool[(num >= 9) ? num : 9];
             for (int i = 0; i != num; i++)
             {
                 keyUsage[i] = ((bytes[i / 8] & (128 >> i % 8)) != 0);
             }
         }
         else
         {
             keyUsage = null;
         }
     }
     catch (Exception arg2)
     {
         throw new CertificateParsingException("cannot construct KeyUsage: " + arg2);
         IL_0108 :;
     }
 }
示例#6
0
        private CscaMasterList(Asn1Sequence seq)
        {
            //IL_0022: Unknown result type (might be due to invalid IL or missing references)
            //IL_0046: Unknown result type (might be due to invalid IL or missing references)
            if (seq == null || seq.Count == 0)
            {
                throw new ArgumentException("null or empty sequence passed.");
            }
            if (seq.Count != 2)
            {
                throw new ArgumentException(string.Concat((object)"Incorrect sequence size: ", (object)seq.Count));
            }
            version = DerInteger.GetInstance(seq[0]);
            Asn1Set instance = Asn1Set.GetInstance(seq[1]);

            certList = new X509CertificateStructure[instance.Count];
            for (int i = 0; i < certList.Length; i++)
            {
                certList[i] = X509CertificateStructure.GetInstance(instance[i]);
            }
        }
示例#7
0
        public static string ComputeSHA256(byte[] certificate)
        {
            // Load ASN.1 encoded certificate structure
            var certAsn1   = Asn1Object.FromByteArray(certificate);
            var certStruct = X509CertificateStructure.GetInstance(certAsn1);

            // Extract SPKI and DER-encode it
            var spki    = certStruct.SubjectPublicKeyInfo;
            var spkiDer = spki.GetDerEncoded();

            // Compute spki fingerprint (sha256)
            string spkiFingerprint;

            using (var digester = SHA256.Create())
            {
                var digest = digester.ComputeHash(spkiDer);
                spkiFingerprint = Convert.ToBase64String(digest);
            }

            return($"sha256/{spkiFingerprint}");
        }
示例#8
0
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(0x2a);
            }
            X509CertificateStructure certificateAt        = serverCertificate.GetCertificateAt(0);
            SubjectPublicKeyInfo     subjectPublicKeyInfo = certificateAt.SubjectPublicKeyInfo;

            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(subjectPublicKeyInfo);
            }
            catch (Exception exception)
            {
                throw new TlsFatalAlert(0x2b, exception);
            }
            if (this.mTlsSigner == null)
            {
                try
                {
                    this.mDHAgreePublicKey = TlsDHUtilities.ValidateDHPublicKey((DHPublicKeyParameters)this.mServerPublicKey);
                    this.mDHParameters     = this.ValidateDHParameters(this.mDHAgreePublicKey.Parameters);
                }
                catch (InvalidCastException exception2)
                {
                    throw new TlsFatalAlert(0x2e, exception2);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 8);
            }
            else
            {
                if (!this.mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
                {
                    throw new TlsFatalAlert(0x2e);
                }
                TlsUtilities.ValidateKeyUsage(certificateAt, 0x80);
            }
            base.ProcessServerCertificate(serverCertificate);
        }
        public HeaderStructure(Asn1Sequence seq)
        {
            if (seq?.Count > 0 && seq[0] is Asn1Sequence seq2)
            {
                foreach (Asn1TaggedObject tag in seq2.OfType <Asn1TaggedObject>())
                {
                    switch (tag.TagNo)
                    {
                    case 5:
                        byte[] cert = (tag.GetObject() as Asn1OctetString)?.GetOctets();
                        Certificate = X509CertificateStructure.GetInstance(cert);
                        break;

                    case 6:
                        cert         = (tag.GetObject() as Asn1OctetString)?.GetOctets();
                        Certificate2 = X509CertificateStructure.GetInstance(cert);
                        break;

                    case 10:
                        PublicX = Asn1OctetString.GetInstance(tag.GetObject())?.GetOctets();
                        break;
                    }
                }

                Asn1Sequence seq3 = seq2?.OfType <Asn1Sequence>().FirstOrDefault();
                PrivateKeyParameters = KeyParameters.GetInstance(seq3);
                Attributes           = seq2?.OfType <DerBitString>().FirstOrDefault();
            }

            if (seq?.Count > 1)
            {
                HMACKey = (seq[1] as Asn1OctetString)?.GetOctets();
            }

            if (HMACKey == null || Attributes == null || PrivateKeyParameters == null || PublicX == null)
            {
                throw new CryptographicException("Ошибка в данных header.key.");
            }
        }
示例#10
0
 public X509Certificate(X509CertificateStructure c)
 {
     this.c = c;
     try
     {
         Asn1OctetString extensionValue = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
         if (extensionValue != null)
         {
             this.basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
         }
     }
     catch (Exception arg)
     {
         throw new CertificateParsingException("cannot construct BasicConstraints: " + arg);
     }
     try
     {
         Asn1OctetString extensionValue2 = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
         if (extensionValue2 != null)
         {
             DerBitString instance = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
             byte[]       bytes    = instance.GetBytes();
             int          num      = bytes.Length * 8 - instance.PadBits;
             this.keyUsage = new bool[(num < 9) ? 9 : num];
             for (int num2 = 0; num2 != num; num2++)
             {
                 this.keyUsage[num2] = (((int)bytes[num2 / 8] & 128 >> num2 % 8) != 0);
             }
         }
         else
         {
             this.keyUsage = null;
         }
     }
     catch (Exception arg2)
     {
         throw new CertificateParsingException("cannot construct KeyUsage: " + arg2);
     }
 }
 public X509Certificate(X509CertificateStructure c)
 {
     this.c = c;
     try
     {
         Asn1OctetString extensionValue = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
         if (extensionValue != null)
         {
             this.basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
         }
     }
     catch (Exception exception)
     {
         throw new CertificateParsingException("cannot construct BasicConstraints: " + exception);
     }
     try
     {
         Asn1OctetString extensionValue = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
         if (extensionValue != null)
         {
             DerBitString instance = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
             byte[]       bytes    = instance.GetBytes();
             int          num      = (bytes.Length * 8) - instance.PadBits;
             this.keyUsage = new bool[(num >= 9) ? num : 9];
             for (int i = 0; i != num; i++)
             {
                 this.keyUsage[i] = (bytes[i / 8] & (((int)0x80) >> (i % 8))) != 0;
             }
         }
         else
         {
             this.keyUsage = null;
         }
     }
     catch (Exception exception2)
     {
         throw new CertificateParsingException("cannot construct KeyUsage: " + exception2);
     }
 }
示例#12
0
 public X509Certificate(X509CertificateStructure c)
 {
     this.c = c;
     try
     {
         Asn1OctetString extensionValue = GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
         if (extensionValue != null)
         {
             basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
         }
     }
     catch (global::System.Exception ex)
     {
         throw new CertificateParsingException(string.Concat((object)"cannot construct BasicConstraints: ", (object)ex));
     }
     try
     {
         Asn1OctetString extensionValue2 = GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
         if (extensionValue2 != null)
         {
             DerBitString instance = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
             byte[]       bytes    = instance.GetBytes();
             int          num      = bytes.Length * 8 - instance.PadBits;
             keyUsage = new bool[(num < 9) ? 9 : num];
             for (int i = 0; i != num; i++)
             {
                 keyUsage[i] = (bytes[i / 8] & (128 >> i % 8)) != 0;
             }
         }
         else
         {
             keyUsage = null;
         }
     }
     catch (global::System.Exception ex2)
     {
         throw new CertificateParsingException(string.Concat((object)"cannot construct KeyUsage: ", (object)ex2));
     }
 }
示例#13
0
        /// <summary>
        /// Get a signature block that java will load a JAR with
        /// </summary>
        /// <param name="sfFileData">The data to sign</param>
        /// <returns>The signature block (including certificate) for the data passed in</returns>
        private byte[] SignIt(byte[] sfFileData)
        {
            AsymmetricKeyParameter privateKey = null;

            var cert = LoadCert(_pemData, out privateKey);

            //create things needed to make the CmsSignedDataGenerator work
            var certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(new List <X509Certificate>()
            {
                cert
            }));
            CmsSignedDataGenerator dataGen = new CmsSignedDataGenerator();

            dataGen.AddCertificates(certStore);
            dataGen.AddSigner(privateKey, cert, CmsSignedDataGenerator.EncryptionRsa, CmsSignedDataGenerator.DigestSha256);

            //content is detached- i.e. not included in the signature block itself
            CmsProcessableByteArray detachedContent = new CmsProcessableByteArray(sfFileData);
            var signedContent = dataGen.Generate(detachedContent, false);

            //do lots of stuff to get things in the proper ASN.1 structure for java to parse it properly.  much trial and error.
            var                 signerInfos            = signedContent.GetSignerInfos();
            var                 signer                 = signerInfos.GetSigners().Cast <SignerInformation>().First();
            SignerInfo          signerInfo             = signer.ToSignerInfo();
            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();

            digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier("2.16.840.1.101.3.4.2.1"), DerNull.Instance));
            ContentInfo         encapContentInfo = new ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.1"), null);
            Asn1EncodableVector asnVector        = new Asn1EncodableVector();

            asnVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
            Asn1EncodableVector signersVector = new Asn1EncodableVector();

            signersVector.Add(signerInfo.ToAsn1Object());
            SignedData  signedData  = new SignedData(new DerSet(digestAlgorithmsVector), encapContentInfo, new BerSet(asnVector), null, new DerSet(signersVector));
            ContentInfo contentInfo = new ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.2"), signedData);

            return(contentInfo.GetDerEncoded());
        }
示例#14
0
 public static global::System.Collections.IList GetCertificatesFromStore(IX509Store certStore)
 {
     try
     {
         global::System.Collections.IList list = Platform.CreateArrayList();
         if (certStore != null)
         {
             {
                 global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)certStore.GetMatches(null)).GetEnumerator();
                 try
                 {
                     while (enumerator.MoveNext())
                     {
                         X509Certificate x509Certificate = (X509Certificate)enumerator.get_Current();
                         list.Add((object)X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(x509Certificate.GetEncoded())));
                     }
                 }
                 finally
                 {
                     global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                     if (disposable != null)
                     {
                         disposable.Dispose();
                     }
                 }
             }
         }
         return(list);
     }
     catch (CertificateEncodingException e)
     {
         throw new CmsException("error encoding certs", e);
     }
     catch (global::System.Exception e2)
     {
         throw new CmsException("error processing certs", e2);
     }
 }
示例#15
0
        public virtual void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (keyExchange != KeyExchangeAlgorithm.RSA_PSK)
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            X509CertificateStructure x509Cert = serverCertificate.certs[0];
            SubjectPublicKeyInfo     keyInfo  = x509Cert.SubjectPublicKeyInfo;

            try
            {
                this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            //			catch (RuntimeException)
            catch (Exception)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
            }

            // Sanity check the PublicKeyFactory
            if (this.serverPublicKey.IsPrivate)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            this.rsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.serverPublicKey);

            TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment);

            // TODO

            /*
             * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
             * signing algorithm for the certificate must be the same as the algorithm for the
             * certificate key."
             */
        }
示例#16
0
        internal CertificateSubject(X509CertificateStructure cert)
        {
            if (cert == null)
            {
                throw new ArgumentNullException(nameof(cert));
            }

            var ids    = cert.Subject.GetOidList();
            var values = cert.Subject.GetValueList();

            for (var index = 0; index < ids.Count; index++)
            {
                if (X509Name.CN.Equals(ids[index]))
                {
                    this.CommonName = (string)values[index];
                }
                else if (X509Name.O.Equals(ids[index]))
                {
                    this.Organistion = (string)values[index];
                }
                else if (X509Name.OU.Equals(ids[index]))
                {
                    this.OrganistionUnit = (string)values[index];
                }
                else if (X509Name.L.Equals(ids[index]))
                {
                    this.Location = (string)values[index];
                }
                else if (X509Name.ST.Equals(ids[index]))
                {
                    this.State = (string)values[index];
                }
                else if (X509Name.C.Equals(ids[index]))
                {
                    this.Country = (string)values[index];
                }
            }
        }
 private CertificatePair(Asn1Sequence seq)
 {
     if (seq.Count != 1 && seq.Count != 2)
     {
         throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
     }
     foreach (object item in seq)
     {
         Asn1TaggedObject instance = Asn1TaggedObject.GetInstance(item);
         if (instance.TagNo == 0)
         {
             forward = X509CertificateStructure.GetInstance(instance, explicitly: true);
         }
         else
         {
             if (instance.TagNo != 1)
             {
                 throw new ArgumentException("Bad tag number: " + instance.TagNo);
             }
             reverse = X509CertificateStructure.GetInstance(instance, explicitly: true);
         }
     }
 }
示例#18
0
        private CscaMasterList(
            Asn1Sequence seq)
        {
            if (seq == null || seq.Count == 0)
            {
                throw new ArgumentException("null or empty sequence passed.");
            }

            if (seq.Count != 2)
            {
                throw new ArgumentException("Incorrect sequence size: " + seq.Count);
            }

            this.version = DerInteger.GetInstance(seq[0]);

            Asn1Set certSet = Asn1Set.GetInstance(seq[1]);

            this.certList = new X509CertificateStructure[certSet.Count];
            for (int i = 0; i < certList.Length; i++)
            {
                certList[i] = X509CertificateStructure.GetInstance(certSet[i]);
            }
        }
示例#19
0
        public void testSignSimpleEcdsaExternal()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";

            string keyId = "alias/SigningExamples-ECC_NIST_P256";
            Func <System.Collections.Generic.List <string>, string> selector = list => list.Find(name => name.StartsWith("ECDSA_SHA_256"));

            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate2 = CertificateUtils.generateSelfSignedCertificate(
                keyId,
                "CN=AWS KMS PDF Signing Test ECDSA,OU=mkl tests,O=mkl",
                selector
                );
            X509Certificate          certificate = new X509Certificate(X509CertificateStructure.GetInstance(certificate2.RawData));
            AwsKmsSignatureContainer signature   = new AwsKmsSignatureContainer(certificate, keyId, selector);

            using (PdfReader pdfReader = new PdfReader(testFileName))
                using (FileStream result = File.Create("circles-aws-kms-signed-simple-ECDSA-External.pdf"))
                {
                    PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());

                    pdfSigner.SignExternalContainer(signature, 8192);
                }
        }
 public static IList GetCertificatesFromStore(IX509Store certStore)
 {
     try
     {
         IList list = Platform.CreateArrayList();
         if (certStore != null)
         {
             foreach (X509Certificate match in certStore.GetMatches(null))
             {
                 list.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(match.GetEncoded())));
             }
         }
         return(list);
     }
     catch (CertificateEncodingException e)
     {
         throw new CmsException("error encoding certs", e);
     }
     catch (Exception e2)
     {
         throw new CmsException("error processing certs", e2);
     }
 }
示例#21
0
        public static Certificate Parse(Stream input)
        {
            int length = TlsUtilities.ReadUint24(input);

            if (length == 0)
            {
                return(EmptyChain);
            }
            MemoryStream stream = new MemoryStream(TlsUtilities.ReadFully(length, input), false);
            IList        list   = Platform.CreateArrayList();

            while (stream.Position < stream.Length)
            {
                Asn1Object obj2 = TlsUtilities.ReadDerObject(TlsUtilities.ReadOpaque24(stream));
                list.Add(X509CertificateStructure.GetInstance(obj2));
            }
            X509CertificateStructure[] certificateList = new X509CertificateStructure[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                certificateList[i] = (X509CertificateStructure)list[i];
            }
            return(new Certificate(certificateList));
        }
示例#22
0
        public void testSignSimpleRsa()
        {
            string testFileName = @"..\..\..\resources\circles.pdf";

            string keyId = "alias/SigningExamples-RSA_2048";
            Func <System.Collections.Generic.List <string>, string> selector = list => list.Find(name => name.StartsWith("RSASSA_PKCS1_V1_5"));
            AwsKmsSignature signature = new AwsKmsSignature(keyId, selector);

            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate2 = CertificateUtils.generateSelfSignedCertificate(
                keyId,
                "CN=AWS KMS PDF Signing Test RSA,OU=mkl tests,O=mkl",
                selector
                );
            X509Certificate certificate = new X509Certificate(X509CertificateStructure.GetInstance(certificate2.RawData));

            using (PdfReader pdfReader = new PdfReader(testFileName))
                using (FileStream result = File.Create("circles-aws-kms-signed-simple-RSA.pdf"))
                {
                    PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode());

                    pdfSigner.SignDetached(signature, new X509Certificate[] { certificate }, null, null, null, 0, CryptoStandard.CMS);
                }
        }
示例#23
0
        public byte[] GetEncoded()
        {
            try
            {
                X509CertificateStructure f = null, r = null;

                if (forward != null)
                {
                    f = X509CertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(forward.GetEncoded()));

                    if (f == null)
                    {
                        throw new CertificateEncodingException("unable to get encoding for forward");
                    }
                }

                if (reverse != null)
                {
                    r = X509CertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(reverse.GetEncoded()));

                    if (r == null)
                    {
                        throw new CertificateEncodingException("unable to get encoding for reverse");
                    }
                }

                return(new CertificatePair(f, r).GetDerEncoded());
            }
            catch (Exception e)
            {
                // TODO
//				throw new ExtCertificateEncodingException(e.toString(), e);
                throw new CertificateEncodingException(e.Message, e);
            }
        }
示例#24
0
        public override void NotifyClientCertificate(AbstractCertificate clientCertificateIn)
        {
            Certificate clientCertificate = clientCertificateIn as Certificate;

            bool isEmpty = (clientCertificate == null || clientCertificate.IsEmpty);

            if (isEmpty != (mConfig.clientAuth == TlsTestConfig.CLIENT_AUTH_NONE))
            {
                throw new InvalidOperationException();
            }
            if (isEmpty && (mConfig.serverCertReq == TlsTestConfig.SERVER_CERT_REQ_MANDATORY))
            {
                throw new TlsFatalAlert(AlertDescription.handshake_failure);
            }

            X509CertificateStructure[] chain = clientCertificate.GetCertificateList();

            // TODO Cache test resources?
            if (!isEmpty && !(chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-client.pem")) ||
                              chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-client-dsa.pem")) ||
                              chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-client-ecdsa.pem"))))
            {
                throw new TlsFatalAlert(AlertDescription.bad_certificate);
            }

            if (TlsTestConfig.DEBUG)
            {
                Console.WriteLine("TLS server received client certificate chain of length " + chain.Length);
                for (int i = 0; i != chain.Length; i++)
                {
                    X509CertificateStructure entry = chain[i];
                    // TODO Create fingerprint based on certificate signature algorithm digest
                    Console.WriteLine("    fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " ("
                                      + entry.Subject + ")");
                }
            }
        }
示例#25
0
        protected virtual void ReceiveCertificateVerifyMessage(MemoryStream buf)
        {
            DigitallySigned clientCertificateVerify = DigitallySigned.Parse(Context, buf);

            AssertEmpty(buf);

            // Verify the CertificateVerify message contains a correct signature.
            try
            {
                byte[] hash;
                if (TlsUtilities.IsTlsV12(Context))
                {
                    hash = mPrepareFinishHash.GetFinalHash(clientCertificateVerify.Algorithm.Hash);
                }
                else
                {
                    hash = mSecurityParameters.SessionHash;
                }

                X509CertificateStructure x509Cert  = mPeerCertificate.GetCertificateAt(0);
                SubjectPublicKeyInfo     keyInfo   = x509Cert.SubjectPublicKeyInfo;
                AsymmetricKeyParameter   publicKey = PublicKeyFactory.CreateKey(keyInfo);

                TlsSigner tlsSigner = TlsUtilities.CreateTlsSigner((byte)mClientCertificateType);
                tlsSigner.Init(Context);
                if (!tlsSigner.VerifyRawSignature(clientCertificateVerify.Algorithm,
                                                  clientCertificateVerify.Signature, publicKey, hash))
                {
                    throw new TlsFatalAlert(AlertDescription.decrypt_error);
                }
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.decrypt_error, e);
            }
        }
示例#26
0
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (mKeyExchange != KeyExchangeAlgorithm.RSA_PSK)
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(AlertDescription.bad_certificate);
            }

            X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0);

            SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;

            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            // Sanity check the PublicKeyFactory
            if (this.mServerPublicKey.IsPrivate)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            this.mRsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.mServerPublicKey);

            TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment);

            base.ProcessServerCertificate(serverCertificate);
        }
示例#27
0
        /**
         * Parse the ServerCertificate message.
         *
         * @param inStr The stream where to parse from.
         * @return A Certificate object with the certs, the server has sended.
         * @throws IOException If something goes wrong during parsing.
         */
        internal static Certificate Parse(
            Stream inStr)
        {
            X509CertificateStructure[] certs;
            int       left = TlsUtilities.ReadUint24(inStr);
            ArrayList tmp  = new ArrayList();

            while (left > 0)
            {
                int size = TlsUtilities.ReadUint24(inStr);
                left -= 3 + size;
                byte[] buf = new byte[size];
                TlsUtilities.ReadFully(buf, inStr);
                MemoryStream bis = new MemoryStream(buf, false);
                Asn1Object   o   = Asn1Object.FromStream(bis);
                tmp.Add(X509CertificateStructure.GetInstance(o));
                if (bis.Position < bis.Length)
                {
                    throw new ArgumentException("Sorry, there is garbage data left after the certificate");
                }
            }
            certs = (X509CertificateStructure[])tmp.ToArray(typeof(X509CertificateStructure));
            return(new Certificate(certs));
        }
示例#28
0
        //public List<string> GetAuthorityInformationAccessOcspUrl(Org.BouncyCastle.X509.X509Certificate serverX509Certificate)
        //{
        //    List<string> ocspUrls = new List<string>();

        //    try
        //    {
        //         // "1.3.6.1.5.5.7.1.1"
        //        Asn1Object asn1Object = this.GetExtensionValue(rootX509Certificate, X509Extensions.AuthorityInfoAccess.Id);

        //        if (asn1Object == null)
        //        {
        //            return null;
        //        }
        //        // For a strange reason I cannot acess the aia.AccessDescription[].
        //        // Hope it will be fixed in the next version (1.5).
        //        // mySupply ApS - JLM - Still not working in 1.7
        //        // AuthorityInformationAccess aia = AuthorityInformationAccess.GetInstance(asn1Object);

        //        // Switched to manual parse
        //        Asn1Sequence s = (Asn1Sequence)asn1Object;
        //        IEnumerator elements = s.GetEnumerator();

        //        while (elements.MoveNext())
        //        {
        //            Asn1Sequence element = (Asn1Sequence)elements.Current;
        //            DerObjectIdentifier oid = (DerObjectIdentifier)element[0];

        //            if (oid.Id.Equals("1.3.6.1.5.5.7.48.1")) // Is Ocsp - yes
        //            {
        //                Asn1TaggedObject taggedObject = (Asn1TaggedObject)element[1];
        //                GeneralName gn = (GeneralName)GeneralName.GetInstance(taggedObject);
        //                ocspUrls.Add(((DerIA5String)DerIA5String.GetInstance(gn.Name)).GetString());
        //            }
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw new Exception("Error parsing AIA.", e);
        //    }

        //    return ocspUrls;
        //}

        private X509Extensions GetX509Extensions(X509Certificate2 certificate)
        {
            try
            {
                var inputStream          = new Asn1InputStream(certificate.RawData);
                var certificateAsAsn1    = inputStream.ReadObject();
                var certificateStructure = X509CertificateStructure.GetInstance(certificateAsAsn1);
                var toBeSignedPart       = certificateStructure.TbsCertificate;
                var extensions           = toBeSignedPart.Extensions;
                if (extensions == null)
                {
                    throw new CheckCertificateOcspUnexpectedException("No X509 extensions found");
                }
                return(extensions);
            }
            catch (CheckCertificateOcspUnexpectedException)
            {
                throw;
            }
            catch (CertificateEncodingException e)
            {
                throw new ArgumentException("Error while extracting Access Description", e);
            }
        }
示例#29
0
        public override IList <X509Certificate> GetCertificates()
        {
            IList <X509Certificate> list = new List <X509Certificate>();

            if (!onlyExtended)
            {
                logger.Info(cmsSignedData.GetCertificates("Collection").GetMatches(null).Count + " certificate in collection");
                foreach (X509Certificate ch in cmsSignedData.GetCertificates("Collection").GetMatches(null))
                {
                    X509Certificate c = ch;
                    logger.Info("Certificate for subject " + c.SubjectDN);
                    if (!list.Contains(c))
                    {
                        list.Add(c);
                    }
                }
            }
            // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
            SignerInformation si = BCStaticHelpers.GetSigner(cmsSignedData, signerId);

            if (si != null && si.UnsignedAttributes != null && si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertValues] != null)
            {
                DerSequence seq = (DerSequence)si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertValues].AttrValues[0];
                for (int i = 0; i < seq.Count; i++)
                {
                    X509CertificateStructure cs = X509CertificateStructure.GetInstance(seq[i]);
                    X509Certificate          c  = new X509Certificate(cs);
                    if (!list.Contains(c))
                    {
                        list.Add(c);
                    }
                }
            }

            return(list);
        }
        public VipNetContainerEntry(Asn1Sequence seq, byte[] keyBlock)
        {
            Version        = (DerInteger)seq[0];
            KeyInfo        = VipNetKeyInfo.GetInstance(seq[1]);
            DefenceKeyInfo = VipNetKeyInfo.GetInstance(seq[2]);
            KeyBlock       = keyBlock;

            for (int i = 3; i < seq.Count; ++i)
            {
                if (seq[i] is Asn1TaggedObject tag)
                {
                    switch (tag.TagNo)
                    {
                    case 0:
                        Certificate = X509CertificateStructure.GetInstance(tag.GetObject());
                        break;

                    case 1:
                        PublicKey = (DerOctetString)tag.GetObject();
                        break;
                    }
                }
            }
        }