Example #1
0
        /// <summary></summary>
        private void AddKeysToToken(ISlot Slot, PgpToken Token)
        {
            byte[] abExponent, abId, abModulus;
            bool   isEncrypt, isVerify;
            ulong  vKeyType;

            PgpKeyFlags.nFlags      eKeyFlags;
            ISlotInfo               SlotInfo;
            List <IObjectAttribute> ltAttributes, ltSearchTemplate;
            List <IObjectHandle>    ltPublicKeys;

            if (Slot != null)
            {
                SlotInfo = Slot.GetSlotInfo();

                using (ISession Session = Slot.OpenSession(SessionType.ReadOnly))
                {
                    ltSearchTemplate = new List <IObjectAttribute> {
                        Session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PUBLIC_KEY)
                    };
                    ltPublicKeys = Session.FindAllObjects(ltSearchTemplate);

                    foreach (IObjectHandle PublicKey in ltPublicKeys)
                    {
                        ltAttributes = Session.GetAttributeValue(PublicKey, new List <CKA> {
                            CKA.CKA_ENCRYPT, CKA.CKA_ID, CKA.CKA_KEY_TYPE, CKA.CKA_MODULUS, CKA.CKA_PUBLIC_EXPONENT, CKA.CKA_VERIFY
                        });

                        isEncrypt  = ltAttributes[0].GetValueAsBool();
                        abId       = ltAttributes[1].GetValueAsByteArray();
                        vKeyType   = ltAttributes[2].GetValueAsUlong();
                        abModulus  = ltAttributes[3].GetValueAsByteArray();
                        abExponent = ltAttributes[4].GetValueAsByteArray();
                        isVerify   = ltAttributes[5].GetValueAsBool();

                        if ((CKK)vKeyType == CKK.CKK_RSA)
                        {
                            if (!isEncrypt && isVerify)
                            {
                                eKeyFlags = PgpKeyFlags.nFlags.Certify | PgpKeyFlags.nFlags.Sign;
                            }
                            else if (isEncrypt && !isVerify)
                            {
                                eKeyFlags = PgpKeyFlags.nFlags.Encrypt;
                            }
                            else if (isEncrypt && isVerify)
                            {
                                eKeyFlags = PgpKeyFlags.nFlags.Authenticate;
                            }
                            else
                            {
                                eKeyFlags = PgpKeyFlags.nFlags.None;
                            }

                            Token.AddPublicKey(SlotInfo, abId, eKeyFlags, abModulus, abExponent);
                        }
                    }
                }
            }
        }
Example #2
0
        public Rv C_GetSlotInfo(UInt32 slotID, ref SlotInfo pInfo)
        {
            if (!App.IsInitialized)
            {
                return(Rv.CRYPTOKI_NOT_INITIALIZED);
            }

            ISlot slot = GetSlot(slotID);

            pInfo = slot.GetSlotInfo().Result;

            return(Rv.OK);
        }
Example #3
0
        public ActionResult GetAllCerts()
        {
            Pkcs11InteropFactories factories = new Pkcs11InteropFactories();

            using (IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, DllLibPath, AppType.MultiThreaded))
            {
                ISlot slot = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent).FirstOrDefault();

                if (slot is null)
                {
                    return(Ok("No slots found"));
                }



                ITokenInfo tokenInfo = slot.GetTokenInfo();

                ISlotInfo slotInfo = slot.GetSlotInfo();

                using (var session = slot.OpenSession(SessionType.ReadWrite))
                {
                    session.Login(CKU.CKU_USER, Encoding.UTF8.GetBytes(TokenPin));


                    var certificateSearchAttributes = new List <IObjectAttribute>()
                    {
                        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE),
                        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true),
                        session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509)
                    };

                    IObjectHandle certificate = session.FindAllObjects(certificateSearchAttributes).FirstOrDefault();

                    var certificateValue = session.GetAttributeValue(certificate, new List <CKA>
                    {
                        CKA.CKA_VALUE
                    });


                    var xcert = new X509Certificate2(certificateValue[0].GetValueAsByteArray());

                    return(Ok(

                               new
                    {
                        xcert.Thumbprint,
                        xcert.Subject,
                        xcert.IssuerName,
                        hasKeyNull = xcert.PrivateKey is null
                    }));
Example #4
0
 private Pkcs11SlotInfo ReadSlotInfo()
 {
     return(new Pkcs11SlotInfo(_slot.GetSlotInfo()));
 }
Example #5
0
        /// <summary>
        /// Constructs internal context for Pkcs11Slot class
        /// </summary>
        /// <param name="slot">High level PKCS#11 slot</param>
        /// <param name="storeContext">Internal context for Pkcs11X509Store class</param>
        /// <returns>Internal context for Pkcs11Slot class</returns>
        private Pkcs11SlotContext GetSlotContext(ISlot slot, Pkcs11X509StoreContext storeContext)
        {
            var slotInfo = new Pkcs11SlotInfo(slot.GetSlotInfo());

            return(new Pkcs11SlotContext(slot, slotInfo, storeContext));
        }
Example #6
0
    public string SignWithCMS(String serializedJson)
    {
        byte[] data = Encoding.UTF8.GetBytes(serializedJson);
        Pkcs11InteropFactories factories = new Pkcs11InteropFactories();

        using (IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, DllLibPath, AppType.MultiThreaded))
        {
            ISlot slot = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent).FirstOrDefault();

            if (slot is null)
            {
                return("No slots found");
            }

            ITokenInfo tokenInfo = slot.GetTokenInfo();

            ISlotInfo slotInfo = slot.GetSlotInfo();


            using (var session = slot.OpenSession(SessionType.ReadWrite))
            {
                session.Login(CKU.CKU_USER, Encoding.UTF8.GetBytes(TokenPin));

                var certificateSearchAttributes = new List <IObjectAttribute>()
                {
                    session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE),
                    session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true),
                    session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509)
                };

                IObjectHandle certificate = session.FindAllObjects(certificateSearchAttributes).FirstOrDefault();

                if (certificate is null)
                {
                    return("Certificate not found");
                }

                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.MaxAllowed);

                // find cert by thumbprint
                var foundCerts = store.Certificates.Find(X509FindType.FindByIssuerName, TokenCertificate, false);

                //var foundCerts = store.Certificates.Find(X509FindType.FindBySerialNumber, "2b1cdda84ace68813284519b5fb540c2", true);



                if (foundCerts.Count == 0)
                {
                    return("no device detected");
                }

                var certForSigning = foundCerts[0];
                store.Close();


                ContentInfo content = new ContentInfo(new Oid("1.2.840.113549.1.7.5"), data);


                SignedCms cms = new SignedCms(content, true);

                EssCertIDv2 bouncyCertificate = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier("1.2.840.113549.1.9.16.2.47")), this.HashBytes(certForSigning.RawData));

                SigningCertificateV2 signerCertificateV2 = new SigningCertificateV2(new EssCertIDv2[] { bouncyCertificate });


                CmsSigner signer = new CmsSigner(certForSigning);

                signer.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1");



                signer.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.UtcNow));
                signer.SignedAttributes.Add(new AsnEncodedData(new Oid("1.2.840.113549.1.9.16.2.47"), signerCertificateV2.GetEncoded()));


                cms.ComputeSignature(signer);

                var output = cms.Encode();

                return(Convert.ToBase64String(output));
            }
        }
    }