Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi everybody, someone knows how i can get a certificate from usb token using cryptoapi calls in c#, recently I could to get just for certificate store, but now I want to get from any usb token or card reader, without install the certificate, in advance thanks...

What I have tried:

public class MyCerts
{

static int CERT_STORE_PROV_SYSTEM = 10;
private static int CERT_SYSTEM_STORE_CURRENT_USER = (1 << 16);
//private static int CERT_SYSTEM_STORE_LOCAL_MACHINE = (2 << 16);

[DllImport("CRYPT32", EntryPoint = "CertOpenStore", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CertOpenStore(
int storeProvider, int encodingType,
int hcryptProv, int flags, string pvPara);

[DllImport("CRYPT32", EntryPoint = "CertEnumCertificatesInStore", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CertEnumCertificatesInStore(
IntPtr storeProvider,
IntPtr prevCertContext);

[DllImport("CRYPT32", EntryPoint = "CertCloseStore", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertCloseStore(
IntPtr storeProvider,
int flags);

X509Certificate2Collection m_certs;


public MyCerts()
{
m_certs = new X509Certificate2Collection();
}

public string Init()
{
try
{
IntPtr storeHandle;
storeHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_CURRENT_USER, "MY");
IntPtr currentCertContext;
currentCertContext = CertEnumCertificatesInStore(storeHandle, (IntPtr)0);
int i = 0;
while (currentCertContext != (IntPtr)0)
{
m_certs.Insert(i++, new X509Certificate2(currentCertContext));
currentCertContext = CertEnumCertificatesInStore(storeHandle, currentCertContext);

}
CertCloseStore(storeHandle, 0);
return "Cantidad de certificados encontrados: " + m_certs.Count.ToString();
}
catch (Exception ex)
{
return ex.ToString();
}


}

public List<infofirma> getCollection_Name()
{
List<infofirma> lista_certificados = new List<infofirma>();
int cont = 0;
foreach (var col in m_certs)
{
InfoFirma cer = new InfoFirma();
cer.nombre_cert = col.GetNameInfo(X509NameType.SimpleName, true);
cer.nume_cert = cont;
lista_certificados.Add(cer);
cont++;
}

return lista_certificados;
}

public X509Certificate2 getCert(int pos)
{

return m_certs[pos];
}



public X509Certificate2 this[int index]
{
get
{
// Check the index limits.
if (index < 0 || index > m_certs.Count)
return null;
else
return m_certs[index];
}
}
Posted
Comments
Member 10299249 6-Feb-18 1:05am    
here what is infofirma
Member 11836800 2-Apr-20 14:41pm    
Hi, Have you got solution? if yes please send me solution amreshn2000@gmail.com

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900