byte[] GetEncodedName()
        {
            int           encodingSize = 0;
            StringBuilder errorString  = null;

            CertStrToName(CertEncodingType.X509AsnEncoding | CertEncodingType.PKCS7AsnEncoding,
                          DistinguishedName,
                          StringType.OIDNameString | StringType.ReverseFlag,
                          IntPtr.Zero,
                          null,
                          ref encodingSize,
                          ref errorString);

            byte[] encodedBytes = new byte[encodingSize];
            bool   ok           = CertStrToName(CertEncodingType.X509AsnEncoding | CertEncodingType.PKCS7AsnEncoding,
                                                DistinguishedName,
                                                StringType.OIDNameString | StringType.ReverseFlag,
                                                IntPtr.Zero,
                                                encodedBytes,
                                                ref encodingSize,
                                                ref errorString);

            if (!ok)
            {
                PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
            }

            return(encodedBytes);
        }
        private byte[] GetEncodedName()
        {
            int           pcbEncoded = 0;
            StringBuilder ppszError  = null;

            CertStrToName(CertEncodingType.PKCS7AsnEncoding | CertEncodingType.X509AsnEncoding, this.DistinguishedName, StringType.ReverseFlag | StringType.OIDNameString, IntPtr.Zero, null, ref pcbEncoded, ref ppszError);
            byte[] pbEncoded = new byte[pcbEncoded];
            if (!CertStrToName(CertEncodingType.PKCS7AsnEncoding | CertEncodingType.X509AsnEncoding, this.DistinguishedName, StringType.ReverseFlag | StringType.OIDNameString, IntPtr.Zero, pbEncoded, ref pcbEncoded, ref ppszError))
            {
                PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
            }
            return(pbEncoded);
        }
        private void CreateCertContext(string name, DateTime start, DateTime expire)
        {
            CriticalAllocHandle providerInfo = this.GetProviderInfo();
            CriticalAllocHandle handle2      = GetSha1AlgorithmId();
            SystemTime          pStartTime   = new SystemTime(start);
            SystemTime          pEndTime     = new SystemTime(expire);
            CertificateName     name2        = new CertificateName(name);

            using (CryptoApiBlob blob = name2.GetCryptoApiBlob())
            {
                using (providerInfo)
                {
                    using (handle2)
                    {
                        this.cert = CertCreateSelfSignCertificate(this.keyContainer, blob.GetMemoryForPinning(), SelfSignFlags.None, (IntPtr)providerInfo, (IntPtr)handle2, ref pStartTime, ref pEndTime, IntPtr.Zero);
                        if (this.cert.IsInvalid)
                        {
                            PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                        }
                        if (!CertSetCertificateContextProperty(this.cert, 1, 0, this.key))
                        {
                            PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                        }
                    }
                }
            }
        }
 private void Export()
 {
     using (CertificateStoreHandle handle = CertOpenStore(new IntPtr(2), 0, IntPtr.Zero, 0, IntPtr.Zero))
     {
         StoreCertificateHandle handle2;
         if (!CertAddCertificateContextToStore(handle, this.cert, AddDisposition.ReplaceExisting, out handle2))
         {
             int error = Marshal.GetLastWin32Error();
             Utility.CloseInvalidOutSafeHandle(handle2);
             PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(new Win32Exception(error));
         }
         using (handle2)
         {
             CryptoApiBlob blob = new CryptoApiBlob();
             CryptoApiBlob.InteropHelper memoryForPinning = blob.GetMemoryForPinning();
             GCHandle handle3 = GCHandle.Alloc(memoryForPinning, GCHandleType.Pinned);
             try
             {
                 if (!PFXExportCertStoreEx(handle, handle3.AddrOfPinnedObject(), this.password, IntPtr.Zero, PfxExportFlags.ExportPrivateKeys | PfxExportFlags.ReportNotAbleToExportPrivateKey | PfxExportFlags.ReportNoPrivateKey))
                 {
                     PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                 }
                 int size = memoryForPinning.size;
                 handle3.Free();
                 blob.AllocateBlob(size);
                 handle3 = GCHandle.Alloc(blob.GetMemoryForPinning(), GCHandleType.Pinned);
                 if (!PFXExportCertStoreEx(handle, handle3.AddrOfPinnedObject(), this.password, IntPtr.Zero, PfxExportFlags.ExportPrivateKeys | PfxExportFlags.ReportNotAbleToExportPrivateKey | PfxExportFlags.ReportNoPrivateKey))
                 {
                     PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                 }
                 this.exportedBytes = blob.GetBytes();
             }
             finally
             {
                 handle3.Free();
                 if (blob != null)
                 {
                     blob.Dispose();
                 }
             }
         }
     }
 }
        void CreateCertContext(string name, DateTime start, DateTime expire)
        {
            CriticalAllocHandle provInfo;
            CriticalAllocHandle algorithmId;

            provInfo    = GetProviderInfo();
            algorithmId = GetSha1AlgorithmId();

            // convert the times to SystemTime structures
            SystemTime beginTime  = new SystemTime(start);
            SystemTime expireTime = new SystemTime(expire);

            // convert the name into a X500 name
            CertificateName certName = new CertificateName(name);

            using (CryptoApiBlob nameBlob = certName.GetCryptoApiBlob())
            {
                using (provInfo)
                {
                    using (algorithmId)
                    {
                        cert = CertCreateSelfSignCertificate(keyContainer,
                                                             nameBlob.GetMemoryForPinning(),
                                                             SelfSignFlags.None,
                                                             provInfo,
                                                             algorithmId,
                                                             ref beginTime,
                                                             ref expireTime,
                                                             IntPtr.Zero);

                        if (cert.IsInvalid)
                        {
                            PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                        }

                        //                        if (!CertSetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, 0, provInfo))
                        //                          PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                        if (!CertSetCertificateContextProperty(cert, CERT_KEY_SPEC_PROP_ID, 0, key))
                        {
                            PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                        }
                    }
                }
            }
        }
        void Export()
        {
            Fx.Assert(this.exportedBytes == null, "calling Export twice!!");

            // create a temporary store to export
            using (CertificateStoreHandle store = CertOpenStore(new IntPtr(CERT_STORE_PROV_MEMORY),
                                                                0,
                                                                IntPtr.Zero,
                                                                0,
                                                                IntPtr.Zero))
            {
                // add the certificate to the store
                StoreCertificateHandle addedCert;
                if (!CertAddCertificateContextToStore(store,
                                                      cert,
                                                      AddDisposition.ReplaceExisting,
                                                      out addedCert))
                {
                    int error = Marshal.GetLastWin32Error();
                    Utility.CloseInvalidOutSafeHandle(addedCert);
                    PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(new Win32Exception(error));
                }

                using (addedCert)
                {
                    // Translate to a PFX
                    CryptoApiBlob pfxBlob            = new CryptoApiBlob();
                    CryptoApiBlob.InteropHelper blob = pfxBlob.GetMemoryForPinning();
                    GCHandle pfxHandle = GCHandle.Alloc(blob, GCHandleType.Pinned);

                    try
                    {
                        // first figure out the storage space necessary
                        bool result = PFXExportCertStoreEx(store,
                                                           pfxHandle.AddrOfPinnedObject(),
                                                           password,
                                                           IntPtr.Zero,
                                                           PfxExportFlags.ExportPrivateKeys |
                                                           PfxExportFlags.ReportNoPrivateKey |
                                                           PfxExportFlags.ReportNotAbleToExportPrivateKey);

                        if (!result)
                        {
                            PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                        }

                        int storageSize = blob.size;
                        pfxHandle.Free();
                        pfxBlob.AllocateBlob(storageSize);
                        blob      = pfxBlob.GetMemoryForPinning();
                        pfxHandle = GCHandle.Alloc(blob, GCHandleType.Pinned);

                        // now do the translation
                        if (!PFXExportCertStoreEx(store,
                                                  pfxHandle.AddrOfPinnedObject(),
                                                  password,
                                                  IntPtr.Zero,
                                                  PfxExportFlags.ExportPrivateKeys |
                                                  PfxExportFlags.ReportNoPrivateKey |
                                                  PfxExportFlags.ReportNotAbleToExportPrivateKey))
                        {
                            PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
                        }
                        exportedBytes = pfxBlob.GetBytes();
                    }
                    finally
                    {
                        if (pfxHandle != null)
                        {
                            pfxHandle.Free();
                        }

                        if (pfxBlob != null)
                        {
                            pfxBlob.Dispose();
                        }
                    }
                }
            }
        }