It Devel Instalando certificado digital no windows com C#
Post
Cancel

Instalando certificado digital no windows com C#

Este post objetiva mostrar como realizar a instalação de um certificado digital na base de certificados pessoais do usuário através de um aplicativo C#.

Quando executado o aplicativo o certificado será instalado na base de certificados pessoais do usuário executor do aplicativo.

Segue o código:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace InstallCertificate
{
 class Program
 {
 public static void Main(string[] args)
 {
 try {
 InstallCertificate(args[0], args[1]);

 } catch (Exception ex) {
 Console.WriteLine( ex.Message);
 }

 Console.Write("");
 Console.Write("Press any key to continue . . . ");
 Console.ReadKey(true);
 }

 private static void InstallCertificate(string certificatePath, string certificatePassword)
 {
 try
 {
 var serviceRuntimeUserCertificateStore = new X509Store(StoreName.My);
 serviceRuntimeUserCertificateStore.Open(OpenFlags.ReadWrite);

 X509Certificate2 cert;

 try
 {
 cert = new X509Certificate2(certificatePath, certificatePassword);
 }
 catch(Exception ex)
 {
 Console.WriteLine("Failed to load certificate " + certificatePath + ": " + ex.Message);
 throw new Exception("Certificate appeared to load successfully but also seems to be null.", ex);
 }

 serviceRuntimeUserCertificateStore.Add(cert);
 serviceRuntimeUserCertificateStore.Close();
 Console.WriteLine("Installation OK!");
 }
 catch(Exception ex)
 {
 Console.WriteLine("Failed to install {0}. Check the certificate index entry and verify the certificate file exists.\n {1}", certificatePath, ex.Message);
 }
 }

 }
}