示例#1
0
        static byte[] GetPfxCertificateByteArray(ref string certString, ref string privateKey)
        {
            byte[] certArray       = Convert.FromBase64String(certString);
            byte[] privateKeyArray = Convert.FromBase64String(privateKey);


            //Translate to Pkcs#12
            var store = new Pkcs12StoreBuilder().Build();

            Org.BouncyCastle.X509.X509Certificate certTranslate = new X509CertificateParser().ReadCertificate(certArray);

            var certEntry = new X509CertificateEntry(certTranslate);
            var pk        = PrivateKeyFactory.CreateKey(privateKeyArray);
            var keyEntry  = new AsymmetricKeyEntry(pk);

            store.SetKeyEntry("", keyEntry, new X509CertificateEntry[] { certEntry });


            MemoryStream stream = new MemoryStream();

            store.Save(stream, new char[] { }, new SecureRandom());

            stream.Dispose();
            //FromString
            byte[] pfxByteArray = stream.ToArray();

            return(pfxByteArray);
        }
示例#2
0
        public void SetKeyEntry(
            string alias,
            AsymmetricKeyEntry keyEntry,
            X509CertificateEntry[] chain)
        {
            if (alias == null)
            {
                throw new ArgumentNullException("alias");
            }
            if (keyEntry == null)
            {
                throw new ArgumentNullException("keyEntry");
            }
            if (keyEntry.Key.IsPrivate && (chain == null))
            {
                throw new ArgumentException("No certificate chain for private key");
            }

            if (keys[alias] != null)
            {
                DeleteEntry(alias);
            }

            keys[alias]  = keyEntry;
            certs[alias] = chain[0];

            for (int i = 0; i != chain.Length; i++)
            {
                chainCerts[new CertId(chain[i].Certificate.GetPublicKey())] = chain[i];
            }
        }
示例#3
0
        private void init(string aPfxFilePath, string aPassword)
        {
            FileStream         fin          = new FileStream(aPfxFilePath, FileMode.Open, FileAccess.Read);
            Pkcs12StoreBuilder storeBuilder = new Pkcs12StoreBuilder();
            Pkcs12Store        pkcs12Store  = storeBuilder.Build();

            pkcs12Store.Load(fin, aPassword.ToCharArray());
            fin.Close();
            IEnumerable aliases           = pkcs12Store.Aliases;
            IEnumerator aliasesEnumerator = aliases.GetEnumerator();

            while (aliasesEnumerator.MoveNext())
            {
                string alias = (string)aliasesEnumerator.Current;
                signingBouncyCert = pkcs12Store.GetCertificate(alias);
                X509Certificate x509Certificate    = signingBouncyCert.Certificate;
                ECertificate    cert               = new ECertificate(x509Certificate.GetEncoded());
                EKeyUsage       eKeyUsage          = cert.getExtensions().getKeyUsage();
                bool            isDigitalSignature = eKeyUsage.isDigitalSignature();
                if (isDigitalSignature)
                {
                    signingBouncyKeyEntry = pkcs12Store.GetKey(alias);
                    signingCertificate    = cert;
                    break;
                }
            }
        }
示例#4
0
        public static string X509Certificate2ToPEM(X509Certificate2 cert)
        {
            try
            {
                if (cert.HasPrivateKey)
                {
                    byte[] pkcsarray = cert.Export(X509ContentType.Pkcs12);
                    if (pkcsarray.Length == 0)
                    {
                        throw new CryptoException("Empty PKCS12 Array");
                    }
                    X509Certificate        certout = null;
                    AsymmetricKeyParameter priv    = null;
                    using (MemoryStream ms = new MemoryStream(pkcsarray))
                    {
                        Pkcs12Store pkstore = new Pkcs12Store();
                        pkstore.Load(ms, new char[] { });
                        foreach (string s in pkstore.Aliases.Cast <string>())
                        {
                            X509CertificateEntry entry = pkstore.GetCertificate(s);
                            if (entry != null)
                            {
                                certout = entry.Certificate;
                            }
                            AsymmetricKeyEntry kentry = pkstore.GetKey(s);
                            if (kentry != null)
                            {
                                priv = kentry.Key;
                            }
                        }

                        if (certout == null)
                        {
                            throw new CryptoException("Certificate not found");
                        }
                    }

                    using (StringWriter sw = new StringWriter())
                    {
                        PemWriter pemWriter = new PemWriter(sw);
                        pemWriter.WriteObject(certout);
                        if (priv != null)
                        {
                            pemWriter.WriteObject(priv);
                        }
                        sw.Flush();
                        return(sw.ToString());
                    }
                }

                X509Certificate c = DotNetUtilities.FromX509Certificate(cert);
                return(DumpOnePEM(c, null));
                // return cert.Export(X509ContentType.SerializedCert).ToUTF8String();
            }
            catch (Exception e)
            {
                throw new CryptoException($"Unable to open pkcs12, wrong password?. {e.Message}", e);
            }
        }
        private void ExportKey(ListItemEntry entry, String algorithm, char[] password, String path)
        {
            AsymmetricKeyEntry keyentry = _store.GetKey(entry.Alias);
            string             pem      = PemUtilities.Encode(keyentry.Key, algorithm, password,
                                                              Repository.Srand);

            File.WriteAllText(path, pem);
        }
        public static string GetPayloadSignature(string payload)
        {
            string keypairPath     = ConfigurationManager.AppSettings["keypairPath"];
            string keypairPassword = ConfigurationManager.AppSettings["keypairPassword"];

            FileStream  fileStream   = null;
            Pkcs12Store keypairStore = null;

            try
            {
                fileStream   = new FileStream(keypairPath, FileMode.Open, FileAccess.Read);
                keypairStore = new Pkcs12Store(fileStream, keypairPassword.ToCharArray());
            }
            catch (FileNotFoundException e)
            {
                throw new ApiException(400, "\n\nContenedor no encontrado, verifique la ruta.\n\n" + e.Message);
            }
            catch (Exception e)
            {
                throw new ApiException(400, "\n\nPassword del contenedor erróneo.\n\n" + e.Message);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

            string alias = null;

            foreach (string al in keypairStore.Aliases)
            {
                if (keypairStore.IsKeyEntry(al) && keypairStore.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                }
            }

            AsymmetricKeyEntry     pKey       = keypairStore.GetKey(alias);
            ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)pKey.Key;

            byte[] tmpPayload = Encoding.UTF8.GetBytes(payload);

            ISigner sign = SignerUtilities.GetSigner("SHA-256withECDSA");

            sign.Init(true, privateKey);
            sign.BlockUpdate(tmpPayload, 0, tmpPayload.Length);

            byte[] signature = sign.GenerateSignature();

            byte[] asciiBytes = Hex.Encode(signature);
            char[] asciiChars = new char[Encoding.UTF8.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
            Encoding.UTF8.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
            string xSignature = new string(asciiChars);

            return(xSignature);
        }
        /// <summary>
        /// Open the certificate
        /// </summary>
        private void LoadPfx(out X509Certificate[] certificates, out AsymmetricKeyEntry privateKey)
        {
            if (!string.IsNullOrEmpty(pfxFile))
            {
                // Load PFX directly
                using (var pfxStream = new FileStream(pfxFile, FileMode.Open, FileAccess.Read))
                {
                    var pfx   = new Pkcs12Store(pfxStream, pfxPassword.ToCharArray());
                    var alias = pfx.Aliases.Cast <string>().FirstOrDefault(pfx.IsKeyEntry);
                    if (alias == null)
                    {
                        throw new ArgumentException("Cannot find a certificate with a key");
                    }
                    certificates = pfx.GetCertificateChain(alias).Select(x => x.Certificate).ToArray();
                    privateKey   = pfx.GetKey(alias);
                }
            }
            else if (!string.IsNullOrEmpty(certificateThumbprint))
            {
                // Load thumbprint
                var x509 = CertificateSupport.GetCertByThumbprint(certificateThumbprint);
                if (x509 == null)
                {
                    throw new ArgumentException("Failed to load certificate by thumbprint");
                }
                if (!x509.HasPrivateKey)
                {
                    throw new ArgumentException("Certificate has no private key");
                }

                // Gets the certificates
                var parser = new X509CertificateParser();
                certificates = new[] { parser.ReadCertificate(x509.RawData) };

                // Get the private key
                var netPrivateKey = x509.PrivateKey as RSACryptoServiceProvider;
                if (netPrivateKey == null)
                {
                    throw new ArgumentException("Private key is not an RSA crypto service provider");
                }
                var parameters    = netPrivateKey.ExportParameters(true);
                var keyParameters = new RsaPrivateCrtKeyParameters(
                    new BigInteger(1, parameters.Modulus),
                    new BigInteger(1, parameters.Exponent),
                    new BigInteger(1, parameters.D),
                    new BigInteger(1, parameters.P),
                    new BigInteger(1, parameters.Q),
                    new BigInteger(1, parameters.DP),
                    new BigInteger(1, parameters.DQ),
                    new BigInteger(1, parameters.InverseQ));
                privateKey = new AsymmetricKeyEntry(keyParameters);
            }
            else
            {
                throw new ArgumentException("No certificate specified");
            }
        }
示例#8
0
        public void CreateSignature(String src, String dest, String fieldname, AsymmetricKeyEntry pk,
                                    IList <X509Certificate> chain)
        {
            PdfReader  reader = new PdfReader(src);
            FileStream os     = new FileStream(dest, FileMode.Create);
            IExternalSignatureContainer external = new MyExternalSignatureContainer(pk, chain);

            MakeSignature.SignDeferred(reader, fieldname, os, external);
        }
示例#9
0
 private void testSupportedTypes(AsymmetricKeyEntry privKey, X509CertificateEntry[] chain)
 {
     basicStoreTest(privKey, chain,
                    PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc,
                    PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc);
     basicStoreTest(privKey, chain,
                    PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc,
                    PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc);
 }
示例#10
0
        /// <summary>
        /// Sign (fill) named field in the document soft way (using existing stamper)
        /// </summary>
        /// <param name="stamper">PdfStamper</param>
        /// <param name="fieldName">Field to be signed</param>
        /// <param name="reason">Sign reason</param>
        /// <param name="location">Sign location</param>
        /// <param name="graphics">Sign graphic</param>
        /// <param name="certFile">PFX certificate</param>
        /// <param name="certPassword">password of certificate</param>
        /// <param name="renderingMode">SignatureRender renderingMode</param>
        /// <param name="certificationLevel">PdfSignatureAppearance Certification Level</param>
        /// <returns>Successfull or not</returns>
        public static bool SignField(ref PdfStamper stamper,
                                     string fieldName,
                                     string reason,
                                     string location,
                                     Bitmap graphics,
                                     string certFile,
                                     string certPassword,
                                     PdfSignatureAppearance.SignatureRender renderingMode = PdfSignatureAppearance.SignatureRender.GraphicAndDescription,
                                     int certificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED)
        {
            bool result = false;

            try
            {
                if (stamper.Reader.AcroFields.Fields.ContainsKey(fieldName))
                {
                    PdfSignatureAppearance psa = GetPSA(fieldName, stamper, graphics, reason, location, renderingMode, certificationLevel);

                    Pkcs12Store store = new Pkcs12Store(new FileStream(certFile, FileMode.Open), certPassword.ToCharArray());
                    string      alias = "";
                    ICollection <X509Certificate> chain = new List <X509Certificate>();

                    foreach (string al in store.Aliases)
                    {
                        if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                        {
                            alias = al;
                            break;
                        }
                    }
                    AsymmetricKeyEntry ake = store.GetKey(alias);

                    foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
                    {
                        chain.Add(c.Certificate);
                    }

                    RsaPrivateCrtKeyParameters parameters = ake.Key as RsaPrivateCrtKeyParameters;

                    psa.SetCrypto(parameters, chain.ToArray(), null, PdfSignatureAppearance.WINCER_SIGNED);

                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }

            return(result);
        }
示例#11
0
        public static void WriteCertificateAsPem(string name, byte[] rawBytes, string exportPassword, ZipArchive s)
        {
            var a = new Pkcs12Store();

            a.Load(new MemoryStream(rawBytes), Array.Empty <char>());

            X509CertificateEntry entry = null;
            AsymmetricKeyEntry   key   = null;

            foreach (var alias in a.Aliases)
            {
                var aliasKey = a.GetKey(alias.ToString());
                if (aliasKey != null)
                {
                    entry = a.GetCertificate(alias.ToString());
                    key   = aliasKey;
                    break;
                }
            }

            if (entry == null)
            {
                throw new InvalidOperationException("Could not find private key.");
            }

            using (var stream = s.CreateEntry(name + ".crt").Open())
                using (var writer = new StreamWriter(stream))
                {
                    var pw = new PemWriter(writer);
                    pw.WriteObject(entry.Certificate);
                }
            using (var stream = s.CreateEntry(name + ".key").Open())
                using (var writer = new StreamWriter(stream))
                {
                    var pw = new PemWriter(writer);

                    object privateKey;
                    if (exportPassword != null)
                    {
                        privateKey = new MiscPemGenerator(
                            key.Key,
                            "DES-EDE3-CBC",
                            exportPassword.ToCharArray(),
                            CertificateUtils.GetSeededSecureRandom())
                                     .Generate();
                    }
                    else
                    {
                        privateKey = key.Key;
                    }

                    pw.WriteObject(privateKey);

                    writer.Flush();
                }
        }
示例#12
0
    public override bool Equals(object obj)
    {
        AsymmetricKeyEntry asymmetricKeyEntry = obj as AsymmetricKeyEntry;

        if (asymmetricKeyEntry == null)
        {
            return(false);
        }
        return(key.Equals(asymmetricKeyEntry.key));
    }
示例#13
0
        private void UpdateKeyPairType(char[] password)
        {
            Pkcs12Store store = LoadCAPfx(password);

            if (store.ContainsAlias(CaAlias) && store.IsEntryOfType(CaAlias, typeof(AsymmetricKeyEntry)))
            {
                AsymmetricKeyEntry keyEntry = store.GetKey(CaAlias);
                CaCertificate = store.GetCertificate(CaAlias).Certificate;
                KeyPairType   = KeyPairUtils.QueryKeyType(keyEntry.Key);
            }
        }
示例#14
0
        public static void ExportPKCS12(String path, String alias, AsymmetricKeyEntry privKey, char[] password,
                                        params X509CertificateEntry[] certs)
        {
            var keyStore = new Pkcs12Store();

            keyStore.SetKeyEntry(alias, privKey, certs);
            using (var fs = new FileStream(path, FileMode.Create))
            {
                keyStore.Save(fs, password, Repository.Srand);
            }
        }
示例#15
0
        /// <summary>
        /// Exports the specified stream and password to a pkcs12 encrypted file.
        /// </summary>
        /// <remarks>
        /// Exports the specified stream and password to a pkcs12 encrypted file.
        /// </remarks>
        /// <param name="stream">The output stream.</param>
        /// <param name="password">The password to use to lock the private keys.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An error occurred while writing to the stream.
        /// </exception>
        public void Export(Stream stream, string password)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            var store = new Pkcs12Store();

            foreach (var certificate in certs)
            {
                if (keys.ContainsKey(certificate))
                {
                    continue;
                }

                var alias = certificate.GetCommonName();

                if (alias == null)
                {
                    continue;
                }

                var entry = new X509CertificateEntry(certificate);

                store.SetCertificateEntry(alias, entry);
            }

            foreach (var kvp in keys)
            {
                var alias = kvp.Key.GetCommonName();

                if (alias == null)
                {
                    continue;
                }

                var entry = new AsymmetricKeyEntry(kvp.Value);
                var cert  = new X509CertificateEntry(kvp.Key);
                var chain = new List <X509CertificateEntry> ();

                chain.Add(cert);

                store.SetKeyEntry(alias, entry, chain.ToArray());
            }

            store.Save(stream, password.ToCharArray(), new SecureRandom());
        }
示例#16
0
        private static byte[] GeneratePkcs12(
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keys,
            Org.BouncyCastle.X509.X509Certificate cert,
            string friendlyName,
            string password,
            System.Collections.Generic.Dictionary <string, Org.BouncyCastle.X509.X509Certificate> chain)
        {
            System.Collections.Generic.List <X509CertificateEntry> chainCerts =
                new System.Collections.Generic.List <X509CertificateEntry>();

            // Create the PKCS12 store
            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            // Add a Certificate entry
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);

            store.SetCertificateEntry(friendlyName, certEntry); // use DN as the Alias.
                                                                //chainCerts.Add(certEntry);

            // Add chain entries
            System.Collections.Generic.List <byte[]> additionalCertsAsBytes =
                new System.Collections.Generic.List <byte[]>();
            if (chain != null && chain.Count > 0)
            {
                foreach (System.Collections.Generic.KeyValuePair <string, X509Certificate> additionalCert in chain)
                {
                    additionalCertsAsBytes.Add(additionalCert.Value.GetEncoded());
                }
            }

            if (chain != null && chain.Count > 0)
            {
                System.Collections.Generic.IEnumerable <X509Certificate> addicionalCertsAsX09Chain =
                    BuildCertificateChainBC(cert.GetEncoded(), additionalCertsAsBytes);

                foreach (X509Certificate addCertAsX09 in addicionalCertsAsX09Chain)
                {
                    chainCerts.Add(new X509CertificateEntry(addCertAsX09));
                }
            }

            // Add a key entry
            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private);

            // no chain
            store.SetKeyEntry(friendlyName, keyEntry, new X509CertificateEntry[] { certEntry });

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                store.Save(memoryStream, password.ToCharArray(), new Org.BouncyCastle.Security.SecureRandom());
                return(memoryStream.ToArray());
            }
        }
示例#17
0
        public static void Main(String[] args)
        {
            Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
            String      alias = "";
            ICollection <X509Certificate> chain = new List <X509Certificate>();

            // searching for private key

            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
            C2_09_SignatureTypes       app        = new C2_09_SignatureTypes();

            app.Sign(SRC, String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
                     CryptoStandard.CMS, PdfSignatureAppearance.NOT_CERTIFIED, "Test 1", "Ghent");
            app.Sign(SRC, String.Format(DEST, 2), chain, parameters, DigestAlgorithms.SHA512,
                     CryptoStandard.CMS, PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, "Test 1", "Ghent");
            app.Sign(SRC, String.Format(DEST, 3), chain, parameters, DigestAlgorithms.SHA256,
                     CryptoStandard.CADES, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, "Test 1", "Ghent");
            app.Sign(SRC, String.Format(DEST, 4), chain, parameters, DigestAlgorithms.RIPEMD160,
                     CryptoStandard.CADES, PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED, "Test 1", "Ghent");

            app.AddWrongAnnotation(String.Format(DEST, 1), String.Format(DEST, "1_annotated_wrong"));
            app.AddAnnotation(String.Format(DEST, 1), String.Format(DEST, "1_annotated"));
            app.AddAnnotation(String.Format(DEST, 2), String.Format(DEST, "2_annotated"));
            app.AddAnnotation(String.Format(DEST, 3), String.Format(DEST, "3_annotated"));
            app.AddAnnotation(String.Format(DEST, 4), String.Format(DEST, "4_annotated"));
            app.AddText(String.Format(DEST, 1), String.Format(DEST, "1_text"));

            app.SignAgain(String.Format(DEST, 1), String.Format(DEST, "1_double"), chain, parameters, DigestAlgorithms.SHA256,
                          CryptoStandard.CMS, "Second signature test", "Ghent");
            app.SignAgain(String.Format(DEST, 2), String.Format(DEST, "2_double"), chain, parameters, DigestAlgorithms.SHA256,
                          CryptoStandard.CMS, "Second signature test", "Ghent");
            app.SignAgain(String.Format(DEST, 3), String.Format(DEST, "3_double"), chain, parameters, DigestAlgorithms.SHA256,
                          CryptoStandard.CMS, "Second signature test", "Ghent");
            app.SignAgain(String.Format(DEST, 4), String.Format(DEST, "4_double"), chain, parameters, DigestAlgorithms.SHA256,
                          CryptoStandard.CMS, "Second signature test", "Ghent");
        }
示例#18
0
        public byte[] signPdfWithPfxFile(string pfxFile, string pinCode, string pdfFileName)
        {
            PfxSigner    signer = new PfxSigner(SignatureAlg.RSA_SHA256.getName(), pfxFile, pinCode);
            ECertificate signatureCertificate = signer.getSignersCertificate();
            Pkcs12Store  store = new Pkcs12Store(new FileStream(pfxFile, FileMode.Open), pinCode.ToCharArray());
            String       alias = "";
            string       dest  = AppDomain.CurrentDomain.BaseDirectory + "\\tmp.pdf";

            if (File.Exists(dest))
            {
                File.Delete(dest);
            }
            ICollection <Org.BouncyCastle.X509.X509Certificate> chain = new List <Org.BouncyCastle.X509.X509Certificate>();

            // searching for private key
            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            // Creating the reader and the stamper
            PdfReader  reader  = new PdfReader(pdfFileName);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.Reason   = "";
            appearance.Location = "";
            //appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");//don't show rectangle on pdf
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CADES);
            byte[] buffer = File.ReadAllBytes(dest);
            File.Delete(dest);
            return(buffer);
        }
示例#19
0
        virtual public void XmlDSigRsaKS()
        {
            Directory.CreateDirectory(DestDir);

            String filename = "xfa.signed.pdf";
            String output   = DestDir + filename;

            MemoryStream ks = new MemoryStream();

            using (FileStream reader = new FileStream(KEYSTORE, FileMode.Open)) {
                byte[] buffer = new byte[reader.Length];
                reader.Read(buffer, 0, (int)reader.Length);
                ks.Write(buffer, 0, buffer.Length);
                ks.Position = 0;
            }
            Pkcs12Store            store = new Pkcs12Store(ks, PASSWORD.ToCharArray());
            String                 alias = "";
            List <X509Certificate> chain = new List <X509Certificate>();

            // searching for private key

            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            SignWithCertificate(Src, output, parameters, chain.ToArray(), DigestAlgorithms.SHA1);

            String cmp = SaveXmlFromResult(output);

            Assert.IsTrue(VerifySignature(cmp), "XmlDSig Verification");

            Assert.IsTrue(CompareXmls(cmp, CmpDir + filename.Replace(".pdf", ".xml")));
        }
        /// <summary>
        /// Generate a PFX certificate.
        /// </summary>
        /// <param name="PFXFilePassword">PFX password to open the certificate file.</param>
        /// <param name="isRootCertificate">Set to true if the certificate is a Root certificate.</param>
        /// <returns>The PFX file as byte[] array.</returns>
        public byte[] GenerateCertificate(string PFXFilePassword, bool isRootCertificate)
        {
            X509Name x509Name;

            byte[] array;
            try
            {
                if (this.Subject == null && this.attrs.Count == 0)
                {
                    throw new CryptographicException("Certificate subject must be set.");
                }
                if (Licensing.demoVersion && this.ValidTo > this.ValidFrom.AddDays(30))
                {
                    Licensing.ShowDemoMessage();
                    this.ValidTo = this.ValidFrom.AddDays(30);
                }
                X509Certificate         x509Certificate         = null;
                AsymmetricCipherKeyPair asymmetricCipherKeyPair = this.MakeKeyPair(this.GetKeyLength(this.KeySize));
                AsymmetricKeyParameter  @private = asymmetricCipherKeyPair.Private;
                x509Name        = (string.IsNullOrEmpty(this.Subject) ? new X509Name(this.ord, this.attrs) : new X509Name(true, this.Subject));
                x509Certificate = (this.rootKeyPair == null || this.rootCert == null ? this.MakeCertificate(asymmetricCipherKeyPair, x509Name, asymmetricCipherKeyPair, x509Name, isRootCertificate, false) : this.MakeCertificate(asymmetricCipherKeyPair, x509Name, this.rootKeyPair, this.rootCert.SubjectDN, isRootCertificate, true));
                Pkcs12Store          pkcs12Store          = new Pkcs12Store();
                AsymmetricKeyEntry   asymmetricKeyEntry   = new AsymmetricKeyEntry(@private);
                X509CertificateEntry x509CertificateEntry = new X509CertificateEntry(x509Certificate);
                if (this.rootKeyPair == null || this.rootCert == null)
                {
                    X509CertificateEntry[] x509CertificateEntryArray = new X509CertificateEntry[] { x509CertificateEntry };
                    pkcs12Store.SetKeyEntry(this.FriendlyName, asymmetricKeyEntry, x509CertificateEntryArray);
                }
                else
                {
                    X509CertificateEntry   x509CertificateEntry1      = new X509CertificateEntry(this.rootCert);
                    X509CertificateEntry[] x509CertificateEntryArray1 = new X509CertificateEntry[] { x509CertificateEntry, x509CertificateEntry1 };
                    pkcs12Store.SetKeyEntry(this.FriendlyName, asymmetricKeyEntry, x509CertificateEntryArray1);
                }
                MemoryStream memoryStream = new MemoryStream();
                pkcs12Store.Save(memoryStream, PFXFilePassword.ToCharArray(), this.GetSecureRandom());
                memoryStream.Flush();
                memoryStream.Close();
                array = memoryStream.ToArray();
            }
            catch (Exception exception)
            {
                throw new CryptographicException(string.Concat("Certificate generation error. ", exception.Message));
            }
            return(array);
        }
示例#21
0
        private void GetPrivateKey(Stream fs, string passWord)
        {
            Pkcs12Store store = new Pkcs12Store(fs, passWord.ToCharArray());

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    AsymmetricKeyEntry asymmetricKey = store.GetKey(n);

                    if (asymmetricKey.Key.IsPrivate)
                    {
                        this.merchantPrivateKey = asymmetricKey.Key as ECPrivateKeyParameters;
                    }
                }
            }
        }
示例#22
0
        public IActionResult GetKeyFromPfx(IFormFile request, string password, string filename = "certificate.key")
        {
            using var streamReader = new StreamReader(request.OpenReadStream());
            var    store      = new Pkcs12Store(streamReader.BaseStream, password.ToCharArray());
            string firstAlias = store.Aliases.OfType <string>().FirstOrDefault();

            if (string.IsNullOrWhiteSpace(firstAlias))
            {
                throw new InvalidOperationException("Unable to find any certificateName in PFX store");
            }

            AsymmetricKeyEntry key          = store.GetKey(firstAlias);
            string             convertedKey = ConvertToPemFormat(key.Key);

            byte[] result = Encoding.ASCII.GetBytes(convertedKey);
            return(File(result, MediaTypeNames.Application.Octet, filename));
        }
示例#23
0
        private void testNoExtraLocalKeyID(byte[] store1data)
        {
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");

            kpg.Init(new RsaKeyGenerationParameters(
                         BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25));

            AsymmetricCipherKeyPair newPair = kpg.GenerateKeyPair();

            Pkcs12Store store1 = new Pkcs12StoreBuilder().Build();

            store1.Load(new MemoryStream(store1data, false), passwd);

            Pkcs12Store store2 = new Pkcs12StoreBuilder().Build();

            AsymmetricKeyEntry k1 = store1.GetKey("privatekey");

            X509CertificateEntry[] chain1 = store1.GetCertificateChain("privatekey");

            X509CertificateEntry[] chain2 = new X509CertificateEntry[chain1.Length + 1];

            Array.Copy(chain1, 0, chain2, 1, chain1.Length);

            chain2[0] = CreateCert(newPair.Public, k1.Key, "*****@*****.**", "*****@*****.**");

            if (chain1[0][PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
            {
                Fail("localKeyID not found initially");
            }

            store2.SetKeyEntry("new", new AsymmetricKeyEntry(newPair.Private), chain2);

            MemoryStream bOut = new MemoryStream();

            store2.Save(bOut, passwd, new SecureRandom());

            store2.Load(new MemoryStream(bOut.ToArray(), false), passwd);

            chain2 = store2.GetCertificateChain("new");

            if (chain2[1][PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] != null)
            {
                Fail("localKeyID found after save");
            }
        }
示例#24
0
        public async Task InstallAsync(string certResponse)
        {
            #region Bouncy castle PKCS #12 cert file generation
            var data = Convert.FromBase64String(certResponse);

            var parser = new X509CertificateParser();
            var cert   = parser.ReadCertificate(data);

            Pkcs12Store          store     = new Pkcs12StoreBuilder().Build();
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);
            store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(_privateKey);
            store.SetKeyEntry(cert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); //

            string pfx      = string.Empty;
            string password = "";
            using (MemoryStream ms = new MemoryStream())
            {
                store.Save(ms, password.ToCharArray(), _random);

                ms.Position = 0;
                await _storage.SetAsync("accessCert", ms.GetWindowsRuntimeBuffer());

                StreamReader streamReader = new StreamReader(ms);
                // Write to .PFX string
                byte[] arr = ms.ToArray();

                pfx = CryptographicBuffer.EncodeToBase64String(arr.AsBuffer());
            }
            #endregion
            await _storage.SetAsync(StorageKeyNames.PrivateKey, pfx);

            await CertificateEnrollmentManager.ImportPfxDataAsync(pfx, password, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "MAG_CERT");

            // Store the registered cert subject
            if (cert.SubjectDN != null)
            {
                var valueList = cert.SubjectDN.GetValueList(X509Name.CN);
                if (valueList.Count > 0)
                {
                    await _storage.SetAsync(StorageKeyNames.RegisteredCertSubject, (string)valueList[0]);
                }
            }
        }
示例#25
0
        internal byte[] CreatePfxContainer(X509Certificate cert, AsymmetricCipherKeyPair keys)
        {
            var certEntry = new X509CertificateEntry(cert);

            var pkcs12Store = new Pkcs12StoreBuilder()
                              .SetUseDerEncoding(true)
                              .Build();
            var keyEntry = new AsymmetricKeyEntry(keys.Private);

            pkcs12Store.SetKeyEntry("ServerInstance", keyEntry, new X509CertificateEntry[] { certEntry });

            using (MemoryStream stream = new MemoryStream())
            {
                pkcs12Store.Save(stream, null, new SecureRandom());
                var bytes = stream.ToArray();
                return(Pkcs12Utilities.ConvertToDefiniteLength(bytes));
            }
        }
示例#26
0
        private CertificateWithKey Convert(byte[] pfxCertificate)
        {
            using (var stream = new MemoryStream(pfxCertificate))
            {
                var store = new Pkcs12Store();
                store.Load(stream, Password.ToCharArray());
                string alias = store.Aliases.OfType <string>().Single();
                X509CertificateEntry certificateEntry = store.GetCertificate(alias);
                AsymmetricKeyEntry   keyEntry         = store.GetKey(alias);

                var result = new CertificateWithKey
                {
                    Certificate = new X509Certificate2(certificateEntry.Certificate.GetEncoded()),
                    KeyPair     = new AsymmetricCipherKeyPair(certificateEntry.Certificate.GetPublicKey(), keyEntry.Key)
                };
                return(result);
            }
        }
示例#27
0
        public X509Certificate2 CreateMutualAuthenticationX509(string fullSubject, DateTimeOffset validFrom, DateTimeOffset expires)
        {
            var random = GetSecureRandom();

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true,
                new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDN = new X509Name(fullSubject);
            var subjectKeyPair = GenerateRsaKeyPair();

            var issuerDN = subjectDN;
            var issuerKeyPair = subjectKeyPair;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            certificateGenerator.SetNotBefore(validFrom.DateTime);
            certificateGenerator.SetNotAfter(expires.DateTime);
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            var signatureFactory = new Asn1SignatureFactory(Asn1SignatureAlgorithm, issuerKeyPair.Private, random);
            var certificate = certificateGenerator.Generate(signatureFactory);

            var store = new Pkcs12Store();
            var friendlyName = certificate.SubjectDN.ToString();
            var certificateEntry = new X509CertificateEntry(certificate);
            var keyEntry = new AsymmetricKeyEntry(subjectKeyPair.Private);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, keyEntry, new[] { certificateEntry });
            var stream = new MemoryStream();
            store.Save(stream, new char[0], random);

            var bytes = stream.ToArray();
            return new X509Certificate2(bytes, (string)null, X509KeyStorageFlags.PersistKeySet);
        }
示例#28
0
        /// <summary>
        /// Erstellung eines PKCS KeyStores
        /// </summary>
        /// <param name="certificate">Zertifikat für welches der KeyStore erstellt werden soll</param>
        /// <param name="keyPair">Schlüsselpaar welches dem KeyStore unterliegt</param>
        /// <param name="antragsteller">Antragsteller des Zertifikates</param>
        /// <param name="caZertifikat">Stammzertifikat falls es sich um dieses Zertifikat um ein Clientzertifikat handeln soll</param>
        /// <returns></returns>
        public static Pkcs12Store CreatePkcs12Store(X509Certificate certificate, AsymmetricCipherKeyPair keyPair, string antragsteller, X509Certificate caZertifikat = null)
        {
            Pkcs12Store pkcsStore = new Pkcs12StoreBuilder().Build();

            X509CertificateEntry certEntry = new X509CertificateEntry(certificate);

            pkcsStore.SetCertificateEntry(antragsteller, certEntry);

            if (caZertifikat != null)
            {
                var chainCerts = new List <X509CertificateEntry>();

                Dictionary <string, Org.BouncyCastle.X509.X509Certificate> chain = new Dictionary <string, Org.BouncyCastle.X509.X509Certificate>();
                string caCn = caZertifikat.SubjectDN.GetValues(X509Name.CN)[0].ToString();
                chain.Add(caCn, caZertifikat);

                var additionalCertsAsBytes = new List <byte[]>();
                if (chain != null && chain.Count > 0)
                {
                    foreach (var additionalCert in chain)
                    {
                        additionalCertsAsBytes.Add(additionalCert.Value.GetEncoded());
                    }
                }

                if (chain != null && chain.Count > 0)
                {
                    var addicionalCertsAsX09Chain = BuildCertificateChainBC(certificate.GetEncoded(), additionalCertsAsBytes);

                    foreach (var addCertAsX09 in addicionalCertsAsX09Chain)
                    {
                        X509Certificate tmpCertificate = (X509Certificate)addCertAsX09;
                        chainCerts.Add(new X509CertificateEntry(tmpCertificate));
                    }
                }
            }

            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keyPair.Private);

            pkcsStore.SetKeyEntry(antragsteller, keyEntry, new X509CertificateEntry[] { certEntry });

            return(pkcsStore);
        }
示例#29
0
        public void ResignIPA(List <X509Certificate> certificateChain, AsymmetricKeyEntry privateKey)
        {
            MobileProvisionFile mobileProvision = GetMobileProvision();

            byte[] buffer           = GetExecutableBytes();
            string bundleIdentifier = GetBundleIdentifier();

            byte[] infoFileBytes        = GetInfoFileBytes();
            byte[] codeResourcesBytes   = GetCodeResourcesBytes();
            List <MachObjectFile> files = MachObjectHelper.ReadMachObjects(buffer);

            foreach (MachObjectFile file in files)
            {
                CodeSignatureHelper.ResignExecutable(file, bundleIdentifier, certificateChain, privateKey, infoFileBytes, codeResourcesBytes, mobileProvision.PList.Entitlements);
            }
            byte[] executableBytes = MachObjectHelper.PackMachObjects(files);

            ReplaceExecutable(executableBytes);
        }
示例#30
0
        public void DeleteEntry(
            string alias)
        {
            if (alias == null)
            {
                throw new ArgumentNullException("alias");
            }

            AsymmetricKeyEntry k = (AsymmetricKeyEntry)keys[alias];

            if (k != null)
            {
                keys.Remove(alias);
            }

            X509CertificateEntry c = (X509CertificateEntry)certs[alias];

            if (c != null)
            {
                certs.Remove(alias);
                chainCerts.Remove(new CertId(c.Certificate.GetPublicKey()));
            }

            if (k != null)
            {
                string id = (string)localIds[alias];
                if (id != null)
                {
                    localIds.Remove(alias);
                    c = (X509CertificateEntry)keyCerts[id];
                }
                if (c != null)
                {
                    keyCerts.Remove(id);
                    chainCerts.Remove(new CertId(c.Certificate.GetPublicKey()));
                }
            }

            if (c == null && k == null)
            {
                throw new ArgumentException("no such entry as " + alias);
            }
        }