Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In need to port the following code to Delphi (XE5 up) and am stuck. Using JwaWinCrypt I can enumerate certificates etc. but haven't been able to work out if it's the one from the USB smart card token and that the token is actually present.
Is there someone whocan point me in the right direction?

C#
public static bool GetCertificateDNfromToken(out string distinuishedName)
{
    bool result = false;
    distinuishedName = "Unable to locate the HPI-I certificate.  Ensure that the USB token is connected!";
    string error = string.Empty;
    var smartCardCerts = new List<X509Certificate2>();
    X509Store myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    myStore.Open(OpenFlags.ReadOnly);
    foreach (X509Certificate2 cert in myStore.Certificates)
    {
        if (!cert.HasPrivateKey) continue; // not smartcard for sure
        try
        {
            var rsa = cert.PrivateKey as RSACryptoServiceProvider;
            if (rsa == null) continue; // not smart card cert again
            // need to check expiry date range here
            if (cert.NotBefore.CompareTo(DateTime.Now) > 0 || 0 > cert.NotAfter.CompareTo(DateTime.Now))
            {
                distinuishedName = string.Format("Certitificate cannot be used outside it's allowable date range {0} to {1}.", cert.NotBefore.ToShortDateString(), cert.NotAfter.ToShortDateString());
                break;
            }
            bool signingCert = false;
            foreach (X509Extension ext in cert.Extensions)
            {
                if (ext.Oid.FriendlyName == "Key Usage")
                {
                    X509KeyUsageExtension ex = (X509KeyUsageExtension)ext;
                    if ((ex.KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.DigitalSignature)
                    {
                        signingCert = true;
                        break;
                    }
                }
            }
            if (!signingCert)
            {
                distinuishedName = "The USB token does not contain a signing certificate!";
                break;
            }
            if (rsa.CspKeyContainerInfo.HardwareDevice) // sure - smartcard
            {
                // rsa.CspKeyContainerInfo.ProviderName , (smartcard provider = "SafeSign Standard Cryptographic Service Provider")
                distinuishedName = cert.Subject;
                //rsa.SignData(); // to confirm presence of private key - to finally authenticate
                result = true;
                break;
            }
        }
        catch { continue; }
    }
    myStore.Close();

    return result;
}
Posted

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