예제 #1
0
        public X509Certificate2 CreateSelfSignedCertificate(SelfSignedCertProperties properties)
        {
            this.ThrowIfDisposedOrNotOpen();
            this.GenerateKeyExchangeKey(properties.IsPrivateKeyExportable, properties.KeyBitLength);
            byte[]   rawData  = properties.Name.RawData;
            GCHandle gCHandle = GCHandle.Alloc(rawData, GCHandleType.Pinned);

            Win32Native.CryptKeyProviderInformation keyProviderInfo = new Win32Native.CryptKeyProviderInformation
            {
                ContainerName = this.ContainerName,
                KeySpec       = 1,
                ProviderType  = (int)ProviderTypes.PROV_RSA_FULL
            };

            IntPtr intPtr = Win32Native.CertCreateSelfSignCertificate(this.handle, new Win32Native.CryptoApiBlob(rawData.Length, gCHandle.AddrOfPinnedObject()), 0, keyProviderInfo, IntPtr.Zero, this.ToSystemTime(properties.ValidFrom), this.ToSystemTime(properties.ValidTo), IntPtr.Zero);

            gCHandle.Free();

            if (IntPtr.Zero == intPtr)
            {
                Win32ErrorHelper.ThrowExceptionIfGetLastErrorIsNotZero();
            }

            X509Certificate2 result = new X509Certificate2(intPtr);

            if (!Win32Native.CertFreeCertificateContext(intPtr))
            {
                Win32ErrorHelper.ThrowExceptionIfGetLastErrorIsNotZero();
            }
            return(result);
        }
예제 #2
0
        public static byte[] CreateX509Certificate(string name, string password, DateTime validTo)
        {
            X509Certificate2         tempCert = null;
            SelfSignedCertProperties props    = new SelfSignedCertProperties
            {
                IsPrivateKeyExportable = true,
                KeyBitLength           = 1024,
                Name      = new X500DistinguishedName("CN=" + name),
                ValidFrom = DateTime.Now,
                ValidTo   = validTo
            };

            using (CryptContext ctx = new CryptContext())
            {
                ctx.Open();
                tempCert = ctx.CreateSelfSignedCertificate(props);
            }
            return(tempCert.Export(X509ContentType.Pfx, password));
        }