本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2.Export方法的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2.Export方法的具体用法?C# X509Certificate2.Export怎么用?C# X509Certificate2.Export使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.X509Certificates.X509Certificate2
的用法示例。
在下文中一共展示了X509Certificate2.Export方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetCertData
public static string GetCertData(string pfxPath, string password)
{
if (!string.IsNullOrEmpty(pfxPath))
{
var cert = new X509Certificate2();
cert.Import(pfxPath, password, X509KeyStorageFlags.Exportable);
return cert.HasPrivateKey
? Convert.ToBase64String(cert.Export(X509ContentType.Pfx, password))
: Convert.ToBase64String(cert.Export(X509ContentType.Pkcs12));
}
return null;
}
示例2: CreateCertFile
/// <summary>
/// Create .cer or .pfx file from an X509Certificate2 object
/// </summary>
/// <param name="cert">an X509Certificate2 object</param>
/// <param name="NewCerFile">name of generated .cer file</param>
/// <returns>full path of newly generated .cer file</returns>
public static string CreateCertFile(X509Certificate2 cert, string NewCertFile, CertFileType certFileType)
{
byte[] CerContents;
// Write the content to a local .cer file so that users can upload it into Azure
if (certFileType == CertFileType.Cer)
{
CerContents = cert.Export(X509ContentType.Cert);
}
else
{
CerContents = cert.Export(X509ContentType.Pfx, PasswordForCert);
}
using (FileStream fileStream = new FileStream(NewCertFile, FileMode.Create))
{
for (int i = 0; i < CerContents.Length; i++)
{
fileStream.WriteByte(CerContents[i]);
}
fileStream.Seek(0, SeekOrigin.Begin);
fileStream.Close();
}
return System.IO.Path.GetFullPath(NewCertFile);
}
示例3: GetCertificateData
public static byte[] GetCertificateData(X509Certificate2 cert, string password)
{
try
{
return cert.HasPrivateKey ? cert.Export(X509ContentType.Pfx, password) : cert.Export(X509ContentType.Pkcs12, password);
}
catch (CryptographicException)
{
return cert.HasPrivateKey ? cert.RawData : cert.Export(X509ContentType.Pkcs12, password);
}
}
示例4: AddServiceAndClientCertsToStore
/// <summary>
/// Adds the client and service certificate that the provisioning call returned to the local machine's certificate store.
/// Also, the certificates will be saved as files in the executable's folder, so that they can be installed
/// on other machines that need to connect to the newly provisioned Austin instance.
/// </summary>
/// <param name="response">Provisioning response including the certificates.</param>
private static void AddServiceAndClientCertsToStore(CreateResponse response)
{
// Remove existing certificates from store
string serviceName = ConfigurationManager.AppSettings["HostedServiceName"];
string clientCertName = string.Format("StreamInsight Client ({0})", serviceName);
string serviceCertName = string.Format("{0}.cloudapp.net", serviceName);
Console.WriteLine("Removing old certificates from local store...");
CertificateHelper.RemoveCertificate(clientCertName, StoreName.My, StoreLocation.CurrentUser);
CertificateHelper.RemoveCertificate(serviceCertName, StoreName.TrustedPeople, StoreLocation.CurrentUser);
// Add new certificates
Console.WriteLine("Adding certificates to local store...");
byte[] clientRawCert = Convert.FromBase64String(response.ClientCertificate);
byte[] serviceRawCert = Convert.FromBase64String(response.ServiceCertificate);
X509Certificate2 clientCert = new X509Certificate2(clientRawCert, response.ClientCertificatePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
X509Certificate2 serviceCert = new X509Certificate2(serviceRawCert);
CertificateHelper.AddCertificate(clientCert, StoreName.My, StoreLocation.CurrentUser);
CertificateHelper.AddCertificate(serviceCert, StoreName.TrustedPeople, StoreLocation.CurrentUser);
// Save certificates to file
string clientCertFileName = serviceName + "_client.pfx";
string serviceCertFileName = serviceName + "_service.cer";
File.WriteAllBytes(clientCertFileName, clientCert.Export(X509ContentType.Pfx, ConfigurationManager.AppSettings["ClientCertificatePassword"]));
File.WriteAllBytes(serviceCertFileName, serviceCert.Export(X509ContentType.Cert));
Console.WriteLine("Client Certificate also saved as {0}.", clientCertFileName);
Console.WriteLine("Service Certificate also saved as {0}.", serviceCertFileName);
}
示例5: GetPrivateKey
public static byte[] GetPrivateKey(string dir)
{
var fileName = CloudBackedStore.RootDir + "\\" + dir + "\\" + CertDir + "\\oidcertificate.cer";
var cert = new X509Certificate2(fileName);
var priv = cert.Export(X509ContentType.Pfx, "password");
return priv;
}
示例6: TesttMethod1
public void TesttMethod1()
{
var certificate = ConfigurationManager.AppSettings["SubscriptionCertificate"];
X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(certificate), "", X509KeyStorageFlags.Exportable);
File.WriteAllBytes(@"c:\users\skp\documents\cert.pfx", cert.Export(X509ContentType.Pfx));
}
示例7: GetCert
static public X509Certificate GetCert(string cn, TimeSpan expirationLength, string pwd = "", string filename = null)
{
// http://stackoverflow.com/questions/18339706/how-to-create-self-signed-certificate-programmatically-for-wcf-service
// http://stackoverflow.com/questions/21629395/http-listener-with-https-support-coded-in-c-sharp
// https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.storename(v=vs.110).aspx
// create DN for subject and issuer
System.Security.Cryptography.X509Certificates.X509Certificate cert = null;
if (filename != null && File.Exists(filename))
{
cert = new X509Certificate2(filename, pwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
}
else
{
var base64encoded = string.Empty;
base64encoded = CreateCertContent(cn, expirationLength, pwd);
cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(
System.Convert.FromBase64String(base64encoded), pwd,
// mark the private key as exportable (this is usually what you want to do)
// mark private key to go into the Machine store instead of the current users store
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
);
File.WriteAllBytes(filename, cert.Export(X509ContentType.Pfx, pwd));
}
// instantiate the target class with the PKCS#12 data (and the empty password)
return cert;
}
示例8: Client
public Client()
{
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var storeCertificates = store.Certificates.Cast<X509Certificate2>()
.Where(x => CertSubject.Parse(x.Subject).Get(CertSubject.KnownField.CanonicalName) == "www.teamlab.com")
.Where(x => x.HasPrivateKey)
.Where(x => x.NotAfter > DateTime.UtcNow)
.Where(x => x.NotBefore < DateTime.UtcNow)
.OrderByDescending(x=>x.NotBefore)
.ThenByDescending(x=>x.NotAfter);
_clientCertificate = storeCertificates.FirstOrDefault(x=>x.Verify());
if (_clientCertificate == null)
throw new LicenseCertificateException("Can't find valid TM cert");
if (!_clientCertificate.HasPrivateKey)
throw new LicenseCertificateException("Client certificate should conaint PK");
_export = _clientCertificate.Export(X509ContentType.Cert);
//Check
var test = new X509Certificate2(_export);
if (test.HasPrivateKey)
throw new LicenseCertificateException("Exported certificate shouldn't conaint PK");
_clientId = _clientCertificate.GetSerialNumber();
}
示例9: Main
static void Main(string[] args)
{
try
{
/*
* This program is used to change the csp name in a pfx file.
*/
PrintLine("Set correct CSP name in pfx file.");
PrintLine("\n\nEnter path to PFX file.");
var pfxPath = Prompt().Trim();
PrintLine("\n\nEnter password to the PFX file.");
var pfxPasswords = Prompt();
var file = new FileInfo(pfxPath);
if (!file.Exists || file.Directory == null)
{
PrintLine("\nCould not find pfx file.");
return;
}
var newPfxPath = file.Directory.FullName + "\\correctCsp" + file.Name;
PrintLine("New pfx file will be: " + newPfxPath);
var newFile = new FileInfo(newPfxPath);
if (newFile.Exists)
{
PrintLine("\nFile already exists.");
return;
}
var oldPfx = new X509Certificate2(pfxPath, pfxPasswords, X509KeyStorageFlags.Exportable);
var newPfx = new X509Certificate2(oldPfx);
var csp = (RSACryptoServiceProvider)oldPfx.PrivateKey;
var cspParams = new CspParameters();
cspParams.KeyContainerName = "somealias";
cspParams.ProviderType = 24; //Microsoft Enhanced RSA and AES Cryptographic Provider
var rsaAlg = new RSACryptoServiceProvider(oldPfx.PrivateKey.KeySize, cspParams);
rsaAlg.ImportParameters(csp.ExportParameters(true));
newPfx.PrivateKey = rsaAlg;
using (var fileStream = new FileStream(newPfxPath, FileMode.CreateNew))
{
using (var writer = new BinaryWriter(fileStream))
{
writer.Write(newPfx.Export(X509ContentType.Pfx, pfxPasswords));
}
}
}
catch (Exception e)
{
PrintLine(e.StackTrace);
Prompt();
}
}
示例10: Pkcs7EncryptionHandler
/// <summary>
/// Initialisiert eine neue Instanz der <see cref="Pkcs7EncryptionHandler"/> Klasse.
/// </summary>
/// <param name="senderCertificate">Das X509-Zertifikat des Absenders (PKCS#12)</param>
/// <param name="receiverCertificate">Das X509-Zertifikat des Empfängers</param>
/// <param name="oldSenderCertificates">Die abgelaufenen X509-Zertifikate des Absenders</param>
public Pkcs7EncryptionHandler(X509Certificate2 senderCertificate, X509Certificate2 receiverCertificate, IEnumerable<X509Certificate2> oldSenderCertificates = null)
{
#if NET45
_encryptionHandler = new NativePkcs7EncryptionHandler(senderCertificate, receiverCertificate, oldSenderCertificates);
#else
var senderCert = new Pkcs12Store(new MemoryStream(senderCertificate.Export(X509ContentType.Pkcs12)), new char[0]);
var receiverCert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(receiverCertificate.RawData);
var oldSenderCerts = oldSenderCertificates?.Select(cert => new Pkcs12Store(new MemoryStream(cert.Export(X509ContentType.Pkcs12)), new char[0]));
_encryptionHandler = new BouncyCastlePkcs7EncryptionHandler(senderCert, receiverCert, oldSenderCerts);
#endif
}
示例11: CreateSslCertificate
private ApplicationGatewaySslCertificate CreateSslCertificate(string sslCertName, string password)
{
X509Certificate2 cert = new X509Certificate2("ApplicationGatewayCertificate\\GW5000.pfx", password, X509KeyStorageFlags.Exportable);
ApplicationGatewaySslCertificate sslCert = new ApplicationGatewaySslCertificate()
{
Name = sslCertName,
Data = Convert.ToBase64String(cert.Export(X509ContentType.Pfx, password)),
Password = password
};
return sslCert;
}
示例12: ThirdPartyOAuth
public void ThirdPartyOAuth()
{
dynamic response = new ExpandoObject();
var userId = "users/ayende";
var certificate = new X509Certificate2();
var authorizedDatabases = new[] { "*" };
var key = certificate.Export(X509ContentType.Pkcs12);
#region authenticate_3
var token = AccessToken.Create(key, userId, authorizedDatabases);
response.Write(token.Serialize());
#endregion
}
示例13: CreatePfxFile
public void CreatePfxFile(RSAParameters key, string pathToCertificate, string password, string pathToPfx)
{
#if DNXCORE50
throw new PlatformNotSupportedException("pfx export is not supported on core clr");
#else
var csp = new CspParameters {KeyContainerName = "oocx-acme-temp"};
var rsa2 = new RSACryptoServiceProvider(csp);
rsa2.ImportParameters(key);
var certBytes = File.ReadAllBytes(pathToCertificate);
var certificate = new X509Certificate2(certBytes,password, X509KeyStorageFlags.Exportable) {PrivateKey = rsa2};
var pfxBtes = certificate.Export(X509ContentType.Pkcs12, password);
File.WriteAllBytes(pathToPfx, pfxBtes);
#endif
}
示例14: NewObject
public PSApplicationGatewayAuthenticationCertificate NewObject()
{
X509Certificate2 cert = new X509Certificate2(CertificateFile);
var authCertificate = new PSApplicationGatewayAuthenticationCertificate();
authCertificate.Name = this.Name;
authCertificate.Data = Convert.ToBase64String(cert.Export(X509ContentType.Cert));
authCertificate.Id =
ApplicationGatewayChildResourceHelper.GetResourceNotSetId(
this.NetworkClient.NetworkManagementClient.SubscriptionId,
Microsoft.Azure.Commands.Network.Properties.Resources.ApplicationGatewayAuthenticationCertificateName,
this.Name);
return authCertificate;
}
开发者ID:Azure,项目名称:azure-powershell,代码行数:16,代码来源:AzureApplicationGatewayAuthenticationCertificateBase.cs
示例15: NewObject
public PSApplicationGatewaySslCertificate NewObject()
{
X509Certificate2 cert = new X509Certificate2(CertificateFile, Password, X509KeyStorageFlags.Exportable);
var sslCertificate = new PSApplicationGatewaySslCertificate();
sslCertificate.Name = this.Name;
sslCertificate.Data = Convert.ToBase64String(cert.Export(X509ContentType.Pfx, Password));
sslCertificate.Password = this.Password;
sslCertificate.Id =
ApplicationGatewayChildResourceHelper.GetResourceNotSetId(
this.NetworkClient.NetworkResourceProviderClient.Credentials.SubscriptionId,
Microsoft.Azure.Commands.Network.Properties.Resources.ApplicationGatewaySslCertificateName,
this.Name);
return sslCertificate;
}