Ejemplo n.º 1
0
        public byte[] Export(PkiArchiveFormat format, PkiKey privateKey = null,
                             IEnumerable <PkiCertificate> chain         = null,
                             char[] password = null)
        {
            // Based on:
            //    https://stackoverflow.com/a/44798441/5428506

            switch (format)
            {
            case PkiArchiveFormat.Pem:
                using (var buff = new MemoryStream())
                {
                    byte[] bytes = privateKey?.Export(PkiEncodingFormat.Pem, password);
                    if (bytes != null)
                    {
                        buff.Write(bytes, 0, bytes.Length);
                    }
                    bytes = Export(PkiEncodingFormat.Pem);
                    buff.Write(bytes, 0, bytes.Length);
                    if (chain != null)
                    {
                        foreach (var c in chain)
                        {
                            bytes = c.Export(PkiEncodingFormat.Pem);
                            buff.Write(bytes, 0, bytes.Length);
                        }
                    }
                    return(buff.ToArray());
                }

            case PkiArchiveFormat.Pkcs12:
                var alias = AliasOf(this);
                var store = new Pkcs12StoreBuilder().Build();
                if (privateKey != null)
                {
                    store.SetKeyEntry(alias, new AsymmetricKeyEntry(privateKey.NativeKey),
                                      new[] { new X509CertificateEntry(NativeCertificate) });
                }
                else
                {
                    store.SetCertificateEntry(alias, new X509CertificateEntry(NativeCertificate));
                }

                if (chain != null)
                {
                    foreach (var c in chain)
                    {
                        store.SetCertificateEntry(AliasOf(c),
                                                  new X509CertificateEntry(c.NativeCertificate));
                    }
                }
                using (var buff = new MemoryStream())
                {
                    store.Save(buff, password ?? new char[0], new SecureRandom());
                    return(buff.ToArray());
                }

            default:
                throw new NotSupportedException();
            }
        }
Ejemplo n.º 2
0
 public RecoverableSerialForm(PkiKey key)
 {
     _algorithm = key.Algorithm;
     _key       = key.Export(PkiEncodingFormat.Der);
     _isPrivate = key.IsPrivate;
 }