public Certificate(X509Certificate2 cert)
        {
            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            certificate = cert;

            KeyAlgorithm = certificate.GetKeyAlgorithm();
            HasPrivateKey = certificate.HasPrivateKey;
            SerialNumber = certificate.SerialNumber;
            Thumbprint = certificate.Thumbprint;
            FriendlyName = certificate.FriendlyName;// !string.IsNullOrWhiteSpace(_certificate.FriendlyName) ? _certificate.FriendlyName : string.Format("[{0}]\t[{1}]", _certificate.Issuer, _certificate.Subject);
            Subject = certificate.Subject;
            EffectiveDate = certificate.NotBefore;
            ExpirationDate = certificate.NotAfter;
            Format = certificate.GetFormat();
            Issuer = certificate.Issuer;
            SignatureAlgorithm = certificate.SignatureAlgorithm.FriendlyName;
            Version = certificate.Version.ToString();

            Extentions = new List<string>();
            foreach (X509Extension ext in certificate.Extensions)
            {
                Extentions.Add(ext.Format(false));
            }
        }
Example #2
0
        public static Dictionary <string, string> ParseCert(byte[] certDER)
        {
            var ret = new Dictionary <string, string>();

            try {
                var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certDER);
                //logger.Debug("X.509v3証明書の発行先であるプリンシパルの名前(古い形式)");
                //logger.Debug(x509.GetName());

                ret.Add("X.509v3証明書の形式の名前", x509.GetFormat());
                ret.Add("バージョン", $"{x509.Version}");
                ret.Add("シリアル番号", x509.GetSerialNumberString());
                ret.Add("署名アルゴリズム", x509.SignatureAlgorithm.FriendlyName);
                ret.Add("証明書を発行した証明機関の名前", x509.Issuer);
                ret.Add("サブジェクトの識別名", x509.Subject);
                ret.Add("証明書のハッシュ値の16進文字列", x509.GetCertHashString());
                ret.Add("証明書の発効日", x509.GetEffectiveDateString());
                ret.Add("証明書の失効日", x509.GetExpirationDateString());
                ret.Add("キーアルゴリズム情報", x509.GetKeyAlgorithm());
                ret.Add("キーアルゴリズムパラメータ", x509.GetKeyAlgorithmParametersString());
                ret.Add("公開鍵", x509.GetPublicKeyString());

                foreach (var extension in x509.Extensions)
                {
                    /*
                     * if (extension.Oid.FriendlyName == "キー使用法") {
                     *  var ext = (X509KeyUsageExtension)extension;
                     *  ret.Add("Extension キー使用法", ext.KeyUsages.ToString());
                     * }
                     * if (extension.Oid.FriendlyName == "拡張キー使用法") {
                     *  var ext = (X509EnhancedKeyUsageExtension)extension;
                     *  string value = "";
                     *  var oids = ext.EnhancedKeyUsages;
                     *  foreach (var oid in oids) {
                     *      value = value + oid.FriendlyName + "(" + oid.Value + ")";
                     *  }
                     *  ret.Add("Extension 拡張キー使用法", value);
                     * }
                     */

                    ret.Add($"- Extension {extension.Oid.FriendlyName}", extension.Oid.Value);
                }

                //logger.Debug("X.509v3証明書を発行した証明機関の名前(古い形式)");
                //logger.Debug(x509.GetIssuerName());

                //logger.Debug("X.509証明書全体の生データ");
                //logger.Debug(x509.GetRawCertDataString());
            } catch (Exception ex) {
                logger.Debug(ex);
            }
            return(ret);
        }
Example #3
0
        public MFTestResults CertTest_Test()
        {
            bool bRes = true;

            try
            {
                //string filename = "microsoft.cer";
                using (Session session = new Session("", MechanismType.RSA_PKCS))
                {
                    X509Certificate2 cert = new X509Certificate2(session, Properties.Resources.GetBytes(Properties.Resources.BinaryResources.microsoft));
                    Log.Comment(cert.Subject);

                    Log.Comment(cert.Issuer);

                    byte[] serialNumber = new byte[cert.GetSerialNumber().Length];
                    Array.Copy(cert.GetSerialNumber(), 0,
                                         serialNumber, 0,
                                         cert.GetSerialNumber().Length);
                    PrintByteArray(serialNumber);

                    Log.Comment(cert.GetKeyAlgorithm());


                    byte[] publicKey = new byte[cert.GetPublicKey().Length];
                    Array.Copy(cert.GetPublicKey(), 0,
                                         publicKey, 0,
                                         cert.GetPublicKey().Length);
                    PrintByteArray(publicKey);

                    Log.Comment(cert.GetEffectiveDateString());
                    Log.Comment(cert.GetExpirationDateString());
                }
            }
            catch
            {
                bRes = false;
            }

            return bRes ? MFTestResults.Pass : MFTestResults.Fail;
        }
Example #4
0
        /// <summary>
        /// Creates a new X509 certificate from the contents of an RFC 7468 PEM-encoded certificate and private key.
        /// </summary>
        /// <param name="certPem">The text of the PEM-encoded X509 certificate.</param>
        /// <param name="keyPem">The text of the PEM-encoded private key.</param>
        /// <returns>A new certificate with the private key.</returns>
        /// <exception cref="CryptographicException">
        /// <para>The contents of <paramref name="certPem" /> do not contain a PEM-encoded certificate, or it is malformed.</para>
        /// <para>-or-</para>
        /// <para>The contents of <paramref name="keyPem" /> do not contain a PEM-encoded private key, or it is malformed.</para>
        /// <para>-or-</para>
        /// <para>The contents of <paramref name="keyPem" /> contains a key that does not match the public key in the certificate.</para>
        /// <para>-or-</para>
        /// <para>The certificate uses an unknown public key algorithm.</para>
        /// </exception>
        /// <remarks>
        /// <para>
        ///   The SubjectPublicKeyInfo from the certificate determines what PEM labels are accepted for the private key.
        ///   For RSA certificates, accepted private key PEM labels are "RSA PRIVATE KEY" and "PRIVATE KEY".
        ///   For ECDSA and ECDH certificates, accepted private key PEM labels are "EC PRIVATE KEY" and "PRIVATE KEY".
        ///   For DSA certificates, the accepted private key PEM label is "PRIVATE KEY".
        /// </para>
        /// <para>PEM-encoded items that have a different label are ignored.</para>
        /// <para>
        ///   If the PEM-encoded certificate and private key are in the same text, use the same
        ///   string for both <paramref name="certPem" /> and <paramref name="keyPem" />, such as:
        ///   <code>
        ///     CreateFromPem(combinedCertAndKey, combinedCertAndKey);
        ///   </code>
        ///   Combined PEM-encoded certificates and keys do not require a specific order. For the certificate, the
        ///   the first certificate with a CERTIFICATE label is loaded. For the private key, the first private
        ///   key with an acceptable label is loaded. More advanced scenarios for loading certificates and
        ///   private keys can leverage <see cref="System.Security.Cryptography.PemEncoding" /> to enumerate
        ///   PEM-encoded values and apply any custom loading behavior.
        /// </para>
        /// <para>
        /// For password protected PEM-encoded keys, use <see cref="CreateFromEncryptedPem" /> to specify a password.
        /// </para>
        /// </remarks>
        public static X509Certificate2 CreateFromPem(ReadOnlySpan <char> certPem, ReadOnlySpan <char> keyPem)
        {
            using (X509Certificate2 certificate = CreateFromPem(certPem))
            {
                string keyAlgorithm = certificate.GetKeyAlgorithm();

                return(keyAlgorithm switch
                {
                    Oids.Rsa => ExtractKeyFromPem <RSA>(keyPem, s_RsaPublicKeyPrivateKeyLabels, RSA.Create, certificate.CopyWithPrivateKey),
                    Oids.Dsa => ExtractKeyFromPem <DSA>(keyPem, s_DsaPublicKeyPrivateKeyLabels, DSA.Create, certificate.CopyWithPrivateKey),
                    Oids.EcPublicKey when IsECDsa(certificate) =>
                    ExtractKeyFromPem <ECDsa>(
                        keyPem,
                        s_EcPublicKeyPrivateKeyLabels,
                        ECDsa.Create,
                        certificate.CopyWithPrivateKey),
                    Oids.EcPublicKey when IsECDiffieHellman(certificate) =>
                    ExtractKeyFromPem <ECDiffieHellman>(
                        keyPem,
                        s_EcPublicKeyPrivateKeyLabels,
                        ECDiffieHellman.Create,
                        certificate.CopyWithPrivateKey),
                    _ => throw new CryptographicException(SR.Format(SR.Cryptography_UnknownKeyAlgorithm, keyAlgorithm)),
                });
Example #5
0
        /// <summary>
        /// Gera assinatura Digital do XML
        /// </summary>
        /// <param name="XMLString"></param>
        /// <param name="RefUri"></param>
        /// <param name="X509Cert"></param>
        /// <returns></returns>
        public int Assinar(string XMLString, string RefUri, X509Certificate2 X509Cert)
        {


            int resultado = 0;
            msgResultado = "Assinatura realizada com sucesso";
            try
            {
                //   certificado para ser utilizado na assinatura
                //
                string _xnome = "";

                bool bX509Cert = false;

                if (X509Cert != null)
                {
                    _xnome = X509Cert.Subject.ToString();
                }
                else
                {
                    bX509Cert = true;
                }
                X509Certificate2 _X509Cert = new X509Certificate2();
                X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, (object)_xnome, true);

                //if (collection1.Count == 0)
                if (bX509Cert)
                {
                    resultado = 2;
                    msgResultado = "Problemas no certificado digital";
                }
                else
                {
                    // certificado ok
                    //_X509Cert = collection1[0];

                    _X509Cert = X509Cert;
                    string x;
                    x = _X509Cert.GetKeyAlgorithm().ToString();
                    // Create a new XML document.

                    XmlDocument doc = new XmlDocument();

                    // Format the document to ignore white spaces.
                    doc.PreserveWhitespace = false;

                    // Load the passed XML file using it's name.
                    try
                    {
                        doc.LoadXml(XMLString);

                        // Verifica se a tag a ser assinada existe é única
                        int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count;

                        if (qtdeRefUri == 0)
                        {
                            //  a URI indicada não existe
                            resultado = 4;
                            msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste";
                        }
                        // Exsiste mais de uma tag a ser assinada
                        else
                        {

                            if (qtdeRefUri > 1)
                            {
                                // existe mais de uma URI indicada
                                resultado = 5;
                                msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica";

                            }
                            else
                            {
                                try
                                {
                                    //Claudinei - o.s. 23615 - 10/08/2009
                                    //for (int i = 0; i < qtdeRefUri; i++)
                                    {
                                        //Fim - Claudinei - o.s. 23615 - 10/08/2009

                                        // Create a SignedXml object.
                                        SignedXml signedXml = new SignedXml(doc);

                                        //sTipoAssinatura = _X509Cert.PrivateKey.KeySize.ToString();
                                        // Add the key to the SignedXml document 
                                        signedXml.SigningKey = _X509Cert.PrivateKey;

                                        // Create a reference to be signed
                                        Reference reference = new Reference();
                                        // pega o uri que deve ser assinada
                                        XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).Item(0).Attributes; //Claudinei - o.s. 23615 - 10/08/2009
                                        foreach (XmlAttribute _atributo in _Uri)
                                        {
                                            if (_atributo.Name == "Id")
                                            {
                                                reference.Uri = "#" + _atributo.InnerText;
                                            }
                                        }

                                        // Add an enveloped transformation to the reference.
                                        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                                        reference.AddTransform(env);

                                        XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                                        reference.AddTransform(c14);

                                        // Add the reference to the SignedXml object.
                                        signedXml.AddReference(reference);

                                        // Create a new KeyInfo object
                                        KeyInfo keyInfo = new KeyInfo();

                                        // Load the certificate into a KeyInfoX509Data object
                                        // and add it to the KeyInfo object.
                                        keyInfo.AddClause(new KeyInfoX509Data(_X509Cert));

                                        // Add the KeyInfo object to the SignedXml object.
                                        signedXml.KeyInfo = keyInfo;

                                        signedXml.ComputeSignature();

                                        // Get the XML representation of the signature and save
                                        // it to an XmlElement object.
                                        XmlElement xmlDigitalSignature = signedXml.GetXml();

                                        // Append the element to the XML document.

                                        //Claudinei - o.s. 23581 - 07/07/2009
                                        /*
                                        string teste = "";
                                        //XmlNode xmlno = new XmlNode();
                                        foreach (XmlNode xmlno in doc)
                                        {
                                            teste = xmlno.Name.ToString();
                                        }
                                         */
                                        //Fim - Claudinei - o.s. 23581 - 07/07/2009

                                        //Danner - o.s. 23732 - 11/11/2009
                                        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                        //Fim - Danner - o.s. 23732 - 11/11/2009
                                        XMLDoc = new XmlDocument();
                                        XMLDoc.PreserveWhitespace = false;
                                        XMLDoc = doc;
                                    } //Claudinei - o.s. 23615 - 10/08/2009
                                }

                                catch (Exception caught)
                                {
                                    resultado = 7;
                                    msgResultado = "Erro: Ao assinar o documento - " + caught.Message;
                                }

                            }
                        }
                    }

                    catch (Exception caught)
                    {
                        resultado = 3;
                        msgResultado = "Erro: XML mal formado - " + caught.Message;
                    }
                }
            }
            catch (Exception caught)
            {
                resultado = 1;
                msgResultado = "Erro: Problema ao acessar o certificado digital" + caught.Message;
            }

            return resultado;
        }
        /// <summary>
        /// Create a certificate using the established subject, key, and optional extensions using
        /// the provided certificate as the issuer.
        /// </summary>
        /// <param name="issuerCertificate">
        ///   An X509Certificate2 instance representing the issuing Certificate Authority (CA).
        /// </param>
        /// <param name="notBefore">
        ///   The oldest date and time where this certificate is considered valid.
        ///   Typically <see cref="DateTimeOffset.UtcNow"/>, plus or minus a few seconds.
        /// </param>
        /// <param name="notAfter">
        ///   The date and time where this certificate is no longer considered valid.
        /// </param>
        /// <param name="serialNumber">
        ///   The serial number to use for the new certificate. This value should be unique per issuer.
        ///   The value is interpreted as an unsigned (big) integer in big endian byte ordering.
        /// </param>
        /// <returns>
        ///   An <see cref="X509Certificate2"/> with the specified values. The returned object will
        ///   not assert <see cref="X509Certificate2.HasPrivateKey" />.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="issuerCertificate"/> is null.</exception>
        /// <exception cref="ArgumentException">
        ///   The <see cref="X509Certificate2.HasPrivateKey"/> value for <paramref name="issuerCertificate"/> is false.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   The type of signing key represented by <paramref name="issuerCertificate"/> could not be determined.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   <paramref name="notAfter"/> represents a date and time before <paramref name="notBefore"/>.
        /// </exception>
        /// <exception cref="ArgumentException"><paramref name="serialNumber"/> has length 0.</exception>
        /// <exception cref="ArgumentException">
        ///   <paramref name="issuerCertificate"/> has a different key algorithm than the requested certificate.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///   <paramref name="issuerCertificate"/> is an RSA certificate and this object was created via a constructor
        ///   which does not accept a <see cref="RSASignaturePadding"/> value.
        /// </exception>
        public X509Certificate2 Create(
            X509Certificate2 issuerCertificate,
            DateTimeOffset notBefore,
            DateTimeOffset notAfter,
            ReadOnlySpan <byte> serialNumber)
        {
            if (issuerCertificate == null)
            {
                throw new ArgumentNullException(nameof(issuerCertificate));
            }
            if (!issuerCertificate.HasPrivateKey)
            {
                throw new ArgumentException(SR.Cryptography_CertReq_IssuerRequiresPrivateKey, nameof(issuerCertificate));
            }
            if (notAfter < notBefore)
            {
                throw new ArgumentException(SR.Cryptography_CertReq_DatesReversed);
            }
            if (serialNumber.IsEmpty)
            {
                throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(serialNumber));
            }

            if (issuerCertificate.PublicKey.Oid.Value != PublicKey.Oid.Value)
            {
                throw new ArgumentException(
                          SR.Format(
                              SR.Cryptography_CertReq_AlgorithmMustMatch,
                              issuerCertificate.PublicKey.Oid.Value,
                              PublicKey.Oid.Value),
                          nameof(issuerCertificate));
            }

            DateTime notBeforeLocal = notBefore.LocalDateTime;

            if (notBeforeLocal < issuerCertificate.NotBefore)
            {
                throw new ArgumentException(
                          SR.Format(
                              SR.Cryptography_CertReq_NotBeforeNotNested,
                              notBeforeLocal,
                              issuerCertificate.NotBefore),
                          nameof(notBefore));
            }

            DateTime notAfterLocal = notAfter.LocalDateTime;

            // Round down to the second, since that's the cert accuracy.
            // This makes one method which uses the same DateTimeOffset for chained notAfters
            // not need to do the rounding locally.
            long notAfterLocalTicks = notAfterLocal.Ticks;
            long fractionalSeconds  = notAfterLocalTicks % TimeSpan.TicksPerSecond;

            notAfterLocalTicks -= fractionalSeconds;
            notAfterLocal       = new DateTime(notAfterLocalTicks, notAfterLocal.Kind);

            if (notAfterLocal > issuerCertificate.NotAfter)
            {
                throw new ArgumentException(
                          SR.Format(
                              SR.Cryptography_CertReq_NotAfterNotNested,
                              notAfterLocal,
                              issuerCertificate.NotAfter),
                          nameof(notAfter));
            }

            // Check the Basic Constraints and Key Usage extensions to help identify inappropriate certificates.
            // Note that this is not a security check. The system library backing X509Chain will use these same criteria
            // to determine if a chain is valid; and a user can easily call the X509SignatureGenerator overload to
            // bypass this validation.  We're simply helping them at signing time understand that they've
            // chosen the wrong cert.
            var basicConstraints = (X509BasicConstraintsExtension?)issuerCertificate.Extensions[Oids.BasicConstraints2];
            var keyUsage         = (X509KeyUsageExtension?)issuerCertificate.Extensions[Oids.KeyUsage];

            if (basicConstraints == null)
            {
                throw new ArgumentException(SR.Cryptography_CertReq_BasicConstraintsRequired, nameof(issuerCertificate));
            }
            if (!basicConstraints.CertificateAuthority)
            {
                throw new ArgumentException(SR.Cryptography_CertReq_IssuerBasicConstraintsInvalid, nameof(issuerCertificate));
            }
            if (keyUsage != null && (keyUsage.KeyUsages & X509KeyUsageFlags.KeyCertSign) == 0)
            {
                throw new ArgumentException(SR.Cryptography_CertReq_IssuerKeyUsageInvalid, nameof(issuerCertificate));
            }

            AsymmetricAlgorithm?key = null;
            string keyAlgorithm     = issuerCertificate.GetKeyAlgorithm();
            X509SignatureGenerator generator;

            try
            {
                switch (keyAlgorithm)
                {
                case Oids.Rsa:
                    if (_rsaPadding == null)
                    {
                        throw new InvalidOperationException(SR.Cryptography_CertReq_RSAPaddingRequired);
                    }

                    RSA?rsa = issuerCertificate.GetRSAPrivateKey();
                    key       = rsa;
                    generator = X509SignatureGenerator.CreateForRSA(rsa !, _rsaPadding);
                    break;

                case Oids.EcPublicKey:
                    ECDsa?ecdsa = issuerCertificate.GetECDsaPrivateKey();
                    key       = ecdsa;
                    generator = X509SignatureGenerator.CreateForECDsa(ecdsa !);
                    break;

                default:
                    throw new ArgumentException(
                              SR.Format(SR.Cryptography_UnknownKeyAlgorithm, keyAlgorithm),
                              nameof(issuerCertificate));
                }

                return(Create(issuerCertificate.SubjectName, generator, notBefore, notAfter, serialNumber));
            }
            finally
            {
                key?.Dispose();
            }
        }
Example #7
0
        public void TestCertMangling()
        {
            string certString = @"MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
            EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
            BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
            CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
            WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
            b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
            SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
            YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
            jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
            qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
            zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
            PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
            3yILeYQzllt/g0rKVRk=";

            X509Certificate2 c = new X509Certificate2();
            c.Import(Convert.FromBase64String(certString));
            Assert.AreEqual("[email protected], CN=www.google.com, O=\"Google, Inc\", L=Mountain View, S=California, C=US", c.Issuer);
            //Assert.AreEqual("CN=Microsoft Corporate Root CA, O=Microsoft Corporation", c.Subject);
            Assert.AreEqual("X509", c.GetFormat());
            Assert.AreEqual("1.2.840.10045.2.1", c.GetKeyAlgorithm());
            Assert.AreEqual("06052B81040022", c.GetKeyAlgorithmParametersString());
            Assert.AreEqual("ECC", c.PublicKey.Oid.FriendlyName);
            ECDiffieHellmanPublicKey certKey = CryptoUtils.ImportEccPublicKeyFromCertificate(c);
            //Console.WriteLine(certKey.ToXmlString());

            // https://blogs.msdn.microsoft.com/shawnfa/2007/01/22/elliptic-curve-diffie-hellman/
            // http://stackoverflow.com/questions/11266711/using-cngkey-to-generate-rsa-key-pair-in-pem-dkim-compatible-using-c-simi
            {
                string input = "eyJhbGciOiJFUzM4NCIsIng1dSI6Ik1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFN25uWnBDZnhtQ3JTd0RkQnY3ZUJYWE10S2hyb3hPcmlFcjNobU1PSkF1dy9acFFYajFLNUdHdEhTNENwRk50dGQxSllBS1lvSnhZZ2F5a3BpZTBFeUF2M3FpSzZ1dElIMnFuT0F0M1ZOclFZWGZJWkpTL1ZSZTNJbDhQZ3U5Q0IifQo.eyJleHAiOjE0NjQ5ODM4NDUsImV4dHJhRGF0YSI6eyJkaXNwbGF5TmFtZSI6Imd1cnVueCIsImlkZW50aXR5IjoiYWY2ZjdjNWUtZmNlYS0zZTQzLWJmM2EtZTAwNWU0MDBlNTc4In0sImlkZW50aXR5UHVibGljS2V5IjoiTUhZd0VBWUhLb1pJemowQ0FRWUZLNEVFQUNJRFlnQUU3bm5acENmeG1DclN3RGRCdjdlQlhYTXRLaHJveE9yaUVyM2htTU9KQXV3L1pwUVhqMUs1R0d0SFM0Q3BGTnR0ZDFKWUFLWW9KeFlnYXlrcGllMEV5QXYzcWlLNnV0SUgycW5PQXQzVk5yUVlYZklaSlMvVlJlM0lsOFBndTlDQiIsIm5iZiI6MTQ2NDk4Mzg0NH0K.4OrvYYbX09iwOkz-7_N_5yEejuATcUogEbe69fB-kr7r6sH_qSu6bxp9L64SEgABb0rU7tyYCLVnaCSQjd9Dvb34WI9EducgOPJ92qHspcpXr7j716LDfhZE31ksMtWQ";

                ECDiffieHellmanPublicKey rootKey = CryptoUtils.CreateEcDiffieHellmanPublicKey("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V");

                Console.WriteLine($"Root Public Key:\n{rootKey.ToXmlString()}");
                CngKey key = CngKey.Import(rootKey.ToByteArray(), CngKeyBlobFormat.EccPublicBlob);

                Console.WriteLine("Key family: " + key.AlgorithmGroup);
                //   "identityPublicKey": "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7nnZpCfxmCrSwDdBv7eBXXMtKhroxOriEr3hmMOJAuw/ZpQXj1K5GGtHS4CpFNttd1JYAKYoJxYgaykpie0EyAv3qiK6utIH2qnOAt3VNrQYXfIZJS/VRe3Il8Pgu9CB",

                var newKey = CryptoUtils.ImportECDsaCngKeyFromString("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE7nnZpCfxmCrSwDdBv7eBXXMtKhroxOriEr3hmMOJAuw/ZpQXj1K5GGtHS4CpFNttd1JYAKYoJxYgaykpie0EyAv3qiK6utIH2qnOAt3VNrQYXfIZJS/VRe3Il8Pgu9CB");
                string decoded = JWT.Decode(input, newKey);
                //Assert.AreEqual("", decoded);

                //ECDsaCng t = new ECDsaCng();
                //t.HashAlgorithm = CngAlgorithm.ECDiffieHellmanP384;
                //t.KeySize = 384;
                //byte[] test = t.Key.Export(CngKeyBlobFormat.EccPublicBlob);
                //Assert.AreEqual(test, newKey);

                //string decoded = JWT.Decode(input, t.Key);
            }

            // Private key (in reality this is not necessary since we will generate it)
            AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(Base64Url.Decode("MB8CAQAwEAYHKoZIzj0CAQYFK4EEACIECDAGAgEBBAEB"));
            PrivateKeyInfo privKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
            byte[] derKey = privKeyInfo.GetDerEncoded();
            CngKey privCngKey = CngKey.Import(derKey, CngKeyBlobFormat.Pkcs8PrivateBlob);

            Console.WriteLine(privKeyInfo.PrivateKeyAlgorithm.Algorithm);
            Console.WriteLine(privCngKey.Algorithm.Algorithm);

            // Public key
            ECDiffieHellmanPublicKey clientKey = CryptoUtils.CreateEcDiffieHellmanPublicKey("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs");

            // EC key to generate shared secret

            ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(privCngKey);
            ecKey.HashAlgorithm = CngAlgorithm.Sha256;
            ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            ecKey.SecretPrepend = new byte[128]; // Server token
            //ecKey.SecretPrepend = new byte[0]; // Server token

            Console.WriteLine(ecKey.HashAlgorithm);
            Console.WriteLine(ecKey.KeyExchangeAlgorithm);

            byte[] secret = ecKey.DeriveKeyMaterial(clientKey);

            Console.WriteLine(Package.HexDump(secret));
            Console.WriteLine(Package.HexDump(Base64Url.Decode("ZOBpyzki/M8UZv5tiBih048eYOBVPkQE3r5Fl0gmUP4=")));
            Console.WriteLine(Package.HexDump(Base64Url.Decode("DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod")));

            //Console.WriteLine(Package.HexDump(Base64Url.Decode("DEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyod")));
        }
Example #8
0
 /// <summary>
 /// Возвращает <see langword="true"/> для сертификатов ГОСТ Р 34.10-2012/512.
 /// </summary>
 public static bool IsGost_R3410_2012_512(this X509Certificate2 certificate)
 {
     return(Gost_R3410_2012_512_Constants.KeyAlgorithm.Value.Equals(certificate.GetKeyAlgorithm()));
 }
        public override void AssignSession(Session oS)
        {
            base.AssignSession(oS);
            var dataItems = new List<DataItem>();
            dataItems.Add(new DataItem("Is Https", oS.isHTTPS));

            if (oS.isHTTPS && oS.oFlags.ContainsKey(CertificateStorage.CeritificateRequestPropertyName))
            {
                try
                {
                    var thumbprint = oS.oFlags[CertificateStorage.CeritificateRequestPropertyName];
                    FiddlerApplication.Log.LogString(thumbprint);

                    if (CertificateStorage.Certificates.ContainsKey(thumbprint))
                    {
                        var certificate = CertificateStorage.Certificates[thumbprint];
                        var cert = new X509Certificate2(certificate);

                        _informationTab.Certificate = cert;
                        //most commonly desired information up top.
                        dataItems.InsertRange(0, new[] { new DataItem("FriendlyName", cert.FriendlyName),
                                                         new DataItem("Subject", cert.Subject),
                                                         new DataItem("Issuer", cert.Issuer),
                                                         new DataItem("Effective Date", cert.GetEffectiveDateString()),
                                                         new DataItem("Expiration Date", cert.GetExpirationDateString()),
                                                         new DataItem("Thumbprint", cert.Thumbprint),
                                                         new DataItem("------------------------", "------------------------")});

                        //alphabatized data properties below
                        dataItems.Add(new DataItem("Archived", cert.Archived));
                        dataItems.Add(new DataItem("FriendlyName", cert.FriendlyName));
                        dataItems.Add(new DataItem("Certficate Hash", cert.GetCertHashString()));
                        dataItems.Add(new DataItem("Certificate Format", cert.GetFormat()));
                        dataItems.Add(new DataItem("Effective Date", cert.GetEffectiveDateString()));
                        dataItems.Add(new DataItem("Expiration Date", cert.GetExpirationDateString()));
                        dataItems.Add(new DataItem("Full Issuer Name", cert.IssuerName.Format(true)));
                        dataItems.Add(new DataItem("Full Subject Name", cert.SubjectName.Format(true)));
                        dataItems.Add(new DataItem("Has Private Key", cert.HasPrivateKey));
                        dataItems.Add(new DataItem("Issuer", cert.Issuer));
                        dataItems.Add(new DataItem("Key Algorithm", cert.GetKeyAlgorithm()));
                        dataItems.Add(new DataItem("Key Algorithm Parameters", cert.GetKeyAlgorithmParametersString()));
                        dataItems.Add(new DataItem("Public Key", cert.GetPublicKeyString()));
                        dataItems.Add(new DataItem("Raw Certificate Data", cert.GetRawCertDataString()));
                        dataItems.Add(new DataItem("SerialNumberString", cert.GetSerialNumberString()));
                        dataItems.Add(new DataItem("Subject", cert.Subject));
                        dataItems.Add(new DataItem("Thumbprint", cert.Thumbprint));
                        dataItems.Add(new DataItem("Version", cert.Version));

                        dataItems.Add(new DataItem("------------------------", "------------------------"));
                        dataItems.Add(new DataItem("Extensions", string.Empty));
                        dataItems.Add(new DataItem("------------------------", "------------------------"));
                        foreach (var extension in cert.Extensions)
                        {
                            dataItems.Add(new DataItem(extension.Oid.FriendlyName, extension.Format(true)));
                        }
                    }
                }
                catch (Exception ex)
                {
                    FiddlerApplication.Log.LogString("Unexpected error loading the assigned certificate." + ex.Message);
                }
            }

            _informationTab.DataGrid.DataSource = dataItems;
        }
        private byte[] Build(
            X509Certificate2 issuerCertificate,
            BigInteger crlNumber,
            DateTimeOffset nextUpdate,
            DateTimeOffset thisUpdate,
            HashAlgorithmName hashAlgorithm,
            RSASignaturePadding?rsaSignaturePadding)
        {
            ArgumentNullException.ThrowIfNull(issuerCertificate);

            if (!issuerCertificate.HasPrivateKey)
            {
                throw new ArgumentException(
                          SR.Cryptography_CertReq_IssuerRequiresPrivateKey,
                          nameof(issuerCertificate));
            }
            if (crlNumber < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(crlNumber), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if (nextUpdate <= thisUpdate)
            {
                throw new ArgumentException(SR.Cryptography_CRLBuilder_DatesReversed);
            }

            ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));

            // Check the Basic Constraints and Key Usage extensions to help identify inappropriate certificates.
            // Note that this is not a security check. The system library backing X509Chain will use these same criteria
            // to determine if the CRL is valid; and a user can easily call the X509SignatureGenerator overload to
            // bypass this validation.  We're simply helping them at signing time understand that they've
            // chosen the wrong cert.
            var basicConstraints     = (X509BasicConstraintsExtension?)issuerCertificate.Extensions[Oids.BasicConstraints2];
            var keyUsage             = (X509KeyUsageExtension?)issuerCertificate.Extensions[Oids.KeyUsage];
            var subjectKeyIdentifier =
                (X509SubjectKeyIdentifierExtension?)issuerCertificate.Extensions[Oids.SubjectKeyIdentifier];

            if (basicConstraints == null)
            {
                throw new ArgumentException(
                          SR.Cryptography_CertReq_BasicConstraintsRequired,
                          nameof(issuerCertificate));
            }

            if (!basicConstraints.CertificateAuthority)
            {
                throw new ArgumentException(
                          SR.Cryptography_CertReq_IssuerBasicConstraintsInvalid,
                          nameof(issuerCertificate));
            }

            if (keyUsage != null && (keyUsage.KeyUsages & X509KeyUsageFlags.CrlSign) == 0)
            {
                throw new ArgumentException(
                          SR.Cryptography_CRLBuilder_IssuerKeyUsageInvalid,
                          nameof(issuerCertificate));
            }

            AsymmetricAlgorithm?key = null;
            string keyAlgorithm     = issuerCertificate.GetKeyAlgorithm();
            X509SignatureGenerator generator;

            try
            {
                switch (keyAlgorithm)
                {
                case Oids.Rsa:
                    if (rsaSignaturePadding is null)
                    {
                        throw new ArgumentException(SR.Cryptography_CertReq_RSAPaddingRequired);
                    }

                    RSA?rsa = issuerCertificate.GetRSAPrivateKey();
                    key       = rsa;
                    generator = X509SignatureGenerator.CreateForRSA(rsa !, rsaSignaturePadding);
                    break;

                case Oids.EcPublicKey:
                    ECDsa?ecdsa = issuerCertificate.GetECDsaPrivateKey();
                    key       = ecdsa;
                    generator = X509SignatureGenerator.CreateForECDsa(ecdsa !);
                    break;

                default:
                    throw new ArgumentException(
                              SR.Format(SR.Cryptography_UnknownKeyAlgorithm, keyAlgorithm),
                              nameof(issuerCertificate));
                }

                X509AuthorityKeyIdentifierExtension akid;

                if (subjectKeyIdentifier is not null)
                {
                    akid = X509AuthorityKeyIdentifierExtension.CreateFromSubjectKeyIdentifier(subjectKeyIdentifier);
                }
                else
                {
                    akid = X509AuthorityKeyIdentifierExtension.CreateFromIssuerNameAndSerialNumber(
                        issuerCertificate.IssuerName,
                        issuerCertificate.SerialNumberBytes.Span);
                }

                return(Build(
                           issuerCertificate.SubjectName,
                           generator,
                           crlNumber,
                           nextUpdate,
                           thisUpdate,
                           hashAlgorithm,
                           akid));
            }
            finally
            {
                key?.Dispose();
            }
        }
        public string SignXml(string xmlString, string signTag, X509Certificate2 certificate)
        {
            try
            {
                // checking if there is a certified used on xml sign
                string _xnome = "";
                if (certificate != null)
                    _xnome = certificate.Subject.ToString();

                string x;
                x = certificate.GetKeyAlgorithm().ToString();

                // Create a new XML document.
                XmlDocument doc = new XmlDocument();

                // Format the document to ignore white spaces.
                doc.PreserveWhitespace = false;

                // Load the passed XML file using it’s name.
                try
                {
                    doc.LoadXml(xmlString);

                    // cheching the element will be sign
                    int tagQuantity = doc.GetElementsByTagName(signTag).Count;

                    if (tagQuantity == 0)
                    {
                        return "A tag de assinatura " + signTag.Trim() + " não existe";
                    }
                    else
                    {
                        if (tagQuantity > 1)
                        {
                            return "A tag de assinatura " + signTag.Trim() + " não é unica";
                        }
                        else
                        {
                            try
                            {
                                // Create a SignedXml object.
                                SignedXml signedXml = new SignedXml(doc);

                                // Add the key to the SignedXml document
                                signedXml.SigningKey = certificate.PrivateKey;

                                // Create a reference to be signed
                                Reference reference = new Reference();

                                XmlAttributeCollection tag = doc.GetElementsByTagName(signTag).Item(0).Attributes;
                                foreach (XmlAttribute xmlAttr in tag)
                                {
                                    if (xmlAttr.Name == "Id")
                                        reference.Uri = "#" + xmlAttr.InnerText;
                                }

                                // Felipe Hosomi - se reference.Uri == null, dá erro na assinatura
                                if (reference.Uri == null)
                                {
                                    reference.Uri = String.Empty;
                                }

                                // Add an enveloped transformation to the reference.
                                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                                reference.AddTransform(env);

                                XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                                reference.AddTransform(c14);

                                // Add the reference to the SignedXml object.
                                signedXml.AddReference(reference);

                                // Create a new KeyInfo object
                                KeyInfo keyInfo = new KeyInfo();

                                // Load the certificate into a KeyInfoX509Data object
                                // and add it to the KeyInfo object.
                                keyInfo.AddClause(new KeyInfoX509Data(certificate));

                                // Add the KeyInfo object to the SignedXml object.
                                signedXml.KeyInfo = keyInfo;
                                signedXml.ComputeSignature();

                                // Get the XML representation of the signature and save
                                // it to an XmlElement object.
                                XmlElement xmlDigitalSignature = signedXml.GetXml();

                                // save element on XML
                                doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                XmlDocument XMLDoc = new XmlDocument();
                                XMLDoc.PreserveWhitespace = false;
                                XMLDoc = doc;

                                // XML document already signed
                                return XMLDoc.OuterXml;
                            }
                            catch (Exception e)
                            {
                                return "Erro ao assinar o documento - " + e.Message;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    return "XML mal formado - " + e.Message;
                }
            }
            catch (Exception e)
            {
                return "Problema ao acessar o certificado digital" + e.Message;
            }
        }
Example #12
0
File: Main.cs Project: rmc00/gsf
        // Registers the service OID for the given product.
        private void RegisterServiceOID(Product product)
        {
            List<Product> productsUsingThisOID;
            X509Certificate2 certificate;
            string certificatePath;
            string keyAlgorithm;

            // If the service is already registered, don't need to do anything
            if ((object)product.ServiceOID == null)
            {
                // Get the path to the certificate used to obtain the OID for this fix
                certificatePath = Path.Combine(product.InstallPath, product.Name + ".cer");

                if (File.Exists(certificatePath))
                {
                    StatusTextBox.AppendText(string.Format("Registering service OID for {0}... ", product.Name));

                    // Get the key algorithm of the certificate,
                    // which is the OID used by the service
                    certificate = new X509Certificate2(certificatePath);
                    keyAlgorithm = certificate.GetKeyAlgorithm();

                    // Determine which other products are sharing this service OID
                    productsUsingThisOID = m_products
                        .Where(p => p.ServiceOID == keyAlgorithm)
                        .ToList();

                    // Set service OID to the key algorithm of the certificate
                    product.ServiceOID = keyAlgorithm;

                    // Store the OID of that certificate in case we need to unregister it later
                    using (RegistryKey productKey = Registry.LocalMachine.CreateSubKey(string.Format(@"Software\Grid Protection Alliance\{0}", product.Name)))
                    {
                        if ((object)productKey != null)
                            productKey.SetValue("ServiceOID", keyAlgorithm);
                    }

                    if (productsUsingThisOID.Count == 0)
                    {
                        RegisterOID(keyAlgorithm);
                        AppendStatusMessage("Done.");
                    }
                    else if (productsUsingThisOID.Count == 1)
                    {
                        AppendStatusMessage(string.Format("Service OID already registered for {0}.", productsUsingThisOID[0].Name));
                    }
                    else
                    {
                        AppendStatusMessage(string.Format("Service OID already registered for {0} other products.", productsUsingThisOID.Count));
                    }
                }
            }
        }