public void GetAllCertificatesTest() { using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) { List <byte[]> allCerts = pkcs11RsaSignature.GetAllCertificates(); Assert.IsTrue(allCerts != null && allCerts.Count > 0); bool signingCertFound = false; foreach (byte[] cert in allCerts) { if (ConvertUtils.BytesToBase64String(cert) == _certificate) { signingCertFound = true; return; } } if (!signingCertFound) { Assert.Fail("Signing certificate is not present in the list of all certificates"); } } }
public void Pkcs11RsaSignatureReuseTest() { using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) { byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate(); List <byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates(); ICollection <X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates); for (int i = 0; i < 100; i++) { string unsignedPdfPath = GetTempDocPath(); string signedPdfPath = GetTempDocPath(); try { GenerateRandomPdf(unsignedPdfPath); using (PdfReader pdfReader = new PdfReader(unsignedPdfPath)) using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create)) using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', GetTempDocPath(), true)) MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); Assert.IsTrue(1 == VerifySignatureIntegrity(signedPdfPath)); } finally { File.Delete(unsignedPdfPath); File.Delete(signedPdfPath); } } } }
public void ConstructorLibraryPathTest() { // Existing PKCS#11 library using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) Assert.IsTrue(pkcs11RsaSignature != null); // Non-existing PKCS#11 library try { Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_incorrectString, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm); pkcs11RsaSignature.Dispose(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is UnmanagedException); } // Unspecified PKCS#11 library try { Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(null, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm); pkcs11RsaSignature.Dispose(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentNullException); } }
public void SignWithSHA256Test() { using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, HashAlgorithm.SHA256)) { byte[] signature = pkcs11RsaSignature.Sign(ConvertUtils.Utf8StringToBytes("Hello world")); Assert.IsTrue(pkcs11RsaSignature.GetEncryptionAlgorithm() == "RSA"); Assert.IsTrue(pkcs11RsaSignature.GetHashAlgorithm() == "SHA256"); Assert.IsTrue(ConvertUtils.BytesToBase64String(signature) == @"TL4ZfPMONv5EFO1cI8ni8YuOkPB/0XXjCQPSHH7r3NejQpNCWD0P4OHRIIYYOMYjJwwRbstS+zX5YigR7Wo8j3OrNs5/H3e9k0OcIidM4WFVz7h5frMmaLo+kbVwnA8zGAaYiXAxgQGHH1Qr31pYkVifWx6/Wq+/J4iKVLXFr25mrIwg/Ccfar587HMi3KzPYYNtKIglkqTTTqrzxBv+VW9Ty2TB+YbTJ/3FsBz6+PWHLPCrECizvCKZyT56EOj6QkJ6bZSMt6N42ng187ZgnatwjYJd3HitX146qNpoR5Hp2yjPSBgxxww/U66O2v1SQV1fBz/bGpQ/t6JLODkAmA=="); } }
public void SignWithSHA384Test() { using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, HashAlgorithm.SHA384)) { byte[] signature = pkcs11RsaSignature.Sign(ConvertUtils.Utf8StringToBytes("Hello world")); Assert.IsTrue(pkcs11RsaSignature.GetEncryptionAlgorithm() == "RSA"); Assert.IsTrue(pkcs11RsaSignature.GetHashAlgorithm() == "SHA384"); Assert.IsTrue(ConvertUtils.BytesToBase64String(signature) == @"cuI+JqxscNrX1ZK/PtyTTJmWsRttSivokif2RkbhiAcgXS/6VxDGup83BGMwy+Yttv9miqrPY/dp0GB4TcAbWoYsXhKB+zTs3BlCAvHrDobpvz/wkhLry7AsAjCFUt9ax2ySfAU3PyUkKRkD2WwlDV3DVwAdKZhfkElL8ocYfoAod5u2X8/78HDVod9umUf8Yj1MI0xPdtaOTO1YLWS3Pd9TgXI0IuzbtY/QYO79PVaaalzZYROIy+kwJkkE/N9nQMRg2BVxSEvkd29/Vv98Z/OMDDVFga26BsYhhS9KUw8lKnk7qk7QvSKbPDvhQmTMwNfL++Yi2E4Df8bVk2O1JA=="); } }
public void SignWithSHA512Test() { using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, HashAlgorithm.SHA512)) { byte[] signature = pkcs11RsaSignature.Sign(ConvertUtils.Utf8StringToBytes("Hello world")); Assert.IsTrue(pkcs11RsaSignature.GetEncryptionAlgorithm() == "RSA"); Assert.IsTrue(pkcs11RsaSignature.GetHashAlgorithm() == "SHA512"); Assert.IsTrue(ConvertUtils.BytesToBase64String(signature) == @"nfTYFqxGibgo6Gf5I9AYSVIHyZrCCN1xS8QQkaWVx1JE6pJS0p4urlDTE5RshYBNQ1xxoxTzKpKk5z1TBj0Bzmx0lvhjFpMELW/47xxkYNeBMbfauIIKy2wjvIAlZ1STEGOc622tyPNC9XS9phiJpnmtzOLzetIMwJM+/xCyqLWZmRPilE2luu63w2b60vnfHKSDFeeqtxCd5vvkXsp8iz1A2xLxqEVVrCyQR9qJMAKT5KrApuEHxTLuqqBPO9jV4oFoAu2a+nFlTXk//aU0YfDqsTBeuf2DzhnLAajV3wdCTuKxMlR6jhzXwANLvcq5N8L1Fr7gfj9VX/tuRfNgEw=="); } }
public void SignWithSHA1Test() { using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, HashAlgorithm.SHA1)) { byte[] signature = pkcs11RsaSignature.Sign(ConvertUtils.Utf8StringToBytes("Hello world")); Assert.IsTrue(pkcs11RsaSignature.GetEncryptionAlgorithm() == "RSA"); Assert.IsTrue(pkcs11RsaSignature.GetHashAlgorithm() == "SHA1"); Assert.IsTrue(ConvertUtils.BytesToBase64String(signature) == @"ANaql6sPuTp25Is2V6boFuTwIrBJ7eiM+z4OxcfHIHWiQ1SnBGfpFFdXfnpklTdwYenRpFxaHW6KlNYEIRk9Jkc0ZAJI83QYMmB99mdbnFLxVWqfpO9+41nOv08oe1RZxLp69pWUF0W1yFPwWmB/azH1x3wLkQlLTmxfCo7IEA7v+wlWZn5OosLVL2RjHMAKEcLBbcz9GuEC+BFAiFGRQCVZhWH0k5BgL38cG+Y0PMo+NH2LQy9Hh0neC+3VsQpQgHJM7n5H0/ck1Oay5jSv29I+PoiUMCmEg6txjElYvsrGEB6GwCuO1o5TwjqlADi+KeKqiH3BsIrTS0NTejLW9Q=="); } }
private void signPDF(int llx, int lly, int urx, int ury) { // Do something interesting with unsigned PDF document FileInfo unsignedPdfInfo = new FileInfo(unsignedPdfPath); //Assert.IsTrue(unsignedPdfInfo.Length > 0); // Specify path to the unmanaged PCKS#11 library string libraryPath = @"C:\Windows\System32\cvP11.dll"; // Specify serial number of the token that contains signing key. May be null if tokenLabel is specified. string tokenSerial = @"910e21b0da172e34"; // Specify label of of the token that contains signing key. May be null if tokenSerial is specified string tokenLabel = @"SuisseID"; // Specify PIN for the token string pin = "091011"; // Specify label (value of CKA_LABEL attribute) of the private key used for signing. May be null if ckaId is specified. string ckaLabel = null; // Specify hex encoded string with identifier (value of CKA_ID attribute) of the private key used for signing. May be null if ckaLabel is specified. string ckaId = "6D808CE0BF9C368FB0AD28E24366F646BA0B3F67"; // Specify hash algorihtm used for the signature creation HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256; // Create instance of Pkcs11Signature class that allows iText to create PKCS#1 v1.5 RSA signature with the private key stored on PKCS#11 compatible device using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(libraryPath, tokenSerial, tokenLabel, pin, ckaLabel, ckaId, HashAlgorithm.SHA256)) { // When signing certificate is stored on the token it can be usually read with GetSigningCertificate() method byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate(); // All certificates stored on the token can be usually read with GetAllCertificates() method List <byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates(); // Build certification path for the signing certificate ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates); // Read unsigned PDF document using (PdfReader pdfReader = new PdfReader(unsignedPdfPath)) { // Create output stream for signed PDF document using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create)) { // Create PdfStamper that applies extra content to the PDF document using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', Path.GetTempFileName(), true)) { // Sign PDF document PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; signatureAppearance.SignatureGraphic = iTextSharp.text.Image.GetInstance("logo_sign.png"); signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle((float)llx, (float)lly, (float)urx, (float)ury), 1, null); MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); //MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); } } } } // Do something interesting with the signed PDF document FileInfo signedPdfInfo = new FileInfo(signedPdfPath); //Assert.IsTrue(signedPdfInfo.Length > signedPdfPath.Length); }
public static byte[] SaferGetSigningCertificate(this Pkcs11RsaSignature signature) { for (var i = 0; i < TimesToTryFindSlot; i++) { try { return(signature.GetSigningCertificate()); } catch { Task.Delay(MillisecondsToWaitBetweenFindSlotsAttempts); // ignored } } return(null); }
public void ConstructorHashAlgorihtmTest() { // Defined hashAlgorihtm using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) Assert.IsTrue(pkcs11RsaSignature != null); // Undefined hashAlgorihtm try { Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, (HashAlgorithm)123456); pkcs11RsaSignature.Dispose(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } }
public void ConstructorPinTest() { // Correct PIN using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) Assert.IsTrue(pkcs11RsaSignature != null); // Incorrect PIN try { Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _incorrectString, _ckaLabel, _ckaId, _hashAlgorithm); pkcs11RsaSignature.Dispose(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is Pkcs11Exception); Assert.IsTrue(((Pkcs11Exception)ex).RV == CKR.CKR_PIN_INCORRECT); } }
public void ConstructorCkaLabelAndIdTest() { // Both ckaLabel and ckaId specified using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) Assert.IsTrue(pkcs11RsaSignature != null); // Only ckaLabel specified using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, null, _hashAlgorithm)) Assert.IsTrue(pkcs11RsaSignature != null); // Only ckaId specified using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, null, _ckaId, _hashAlgorithm)) Assert.IsTrue(pkcs11RsaSignature != null); // Both ckaLabel and ckaId unspecified try { Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, null, null, _hashAlgorithm); pkcs11RsaSignature.Dispose(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } // Both ckaLabel and ckaId incorrect try { Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _incorrectString, _incorrectString, _hashAlgorithm); pkcs11RsaSignature.Dispose(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is ObjectNotFoundException); } // Only ckaLabel incorrect try { Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _incorrectString, _ckaId, _hashAlgorithm); pkcs11RsaSignature.Dispose(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is ObjectNotFoundException); } // Only ckaId incorrect try { Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _incorrectString, _hashAlgorithm); pkcs11RsaSignature.Dispose(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is ObjectNotFoundException); } }
public void GetSigningCertificateTest() { // CKA_ID and CKA_LABEL of the temporary RSA key pair byte[] ckaId = null; string ckaLabel = null; // Generate temporary RSA key pair using (Pkcs11 pkcs11 = new Pkcs11(_libraryPath, false)) { Slot slot = FindSlot(pkcs11, _tokenSerial, _tokenLabel); if (slot == null) { throw new TokenNotFoundException(); } using (Session session = slot.OpenSession(false)) { session.Login(CKU.CKU_USER, _pin); ckaId = session.GenerateRandom(20); ckaLabel = Guid.NewGuid().ToString(); List <ObjectAttribute> publicKeyAttributes = new List <ObjectAttribute>(); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY_RECOVER, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_WRAP, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_MODULUS_BITS, 1024)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 })); List <ObjectAttribute> privateKeyAttributes = new List <ObjectAttribute>(); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN_RECOVER, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true)); ObjectHandle publicKeyHandle = null; ObjectHandle privateKeyHandle = null; session.GenerateKeyPair(new Mechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN), publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle); session.Logout(); } } // Test Pkcs11RsaSignature with RSA key pair associated with certificate present on the token using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) { byte[] cert = pkcs11RsaSignature.GetSigningCertificate(); Assert.IsTrue(cert != null); Assert.IsTrue(ConvertUtils.BytesToBase64String(cert) == _certificate); } // Test Pkcs11RsaSignature with temporary RSA key pair that is not associated with any certificate present on the token using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, ckaLabel, ConvertUtils.BytesToHexString(ckaId), _hashAlgorithm)) { try { pkcs11RsaSignature.GetSigningCertificate(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is ObjectNotFoundException); } } // Delete temporary RSA key pair using (Pkcs11 pkcs11 = new Pkcs11(_libraryPath, false)) { Slot slot = FindSlot(pkcs11, _tokenSerial, _tokenLabel); if (slot == null) { throw new TokenNotFoundException(); } using (Session session = slot.OpenSession(false)) { session.Login(CKU.CKU_USER, _pin); List <ObjectAttribute> objectAttributes = new List <ObjectAttribute>(); objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_RSA)); objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel)); objectAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId)); List <ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes); foreach (ObjectHandle foundObject in foundObjects) { session.DestroyObject(foundObject); } session.Logout(); } } }
public void GetSigningCertificateTest() { // CKA_ID and CKA_LABEL of the temporary RSA key pair byte[] ckaId = null; string ckaLabel = null; // Generate temporary RSA key pair using (Pkcs11 pkcs11 = new Pkcs11(_libraryPath, false)) { Slot slot = FindSlot(pkcs11, _tokenSerial, _tokenLabel); if (slot == null) throw new TokenNotFoundException(); using (Session session = slot.OpenSession(false)) { session.Login(CKU.CKU_USER, _pin); ckaId = session.GenerateRandom(20); ckaLabel = Guid.NewGuid().ToString(); List<ObjectAttribute> publicKeyAttributes = new List<ObjectAttribute>(); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY_RECOVER, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_WRAP, true)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_MODULUS_BITS, 1024)); publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 })); List<ObjectAttribute> privateKeyAttributes = new List<ObjectAttribute>(); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN_RECOVER, true)); privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true)); ObjectHandle publicKeyHandle = null; ObjectHandle privateKeyHandle = null; session.GenerateKeyPair(new Mechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN), publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle); session.Logout(); } } // Test Pkcs11RsaSignature with RSA key pair associated with certificate present on the token using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) { byte[] cert = pkcs11RsaSignature.GetSigningCertificate(); Assert.IsTrue(cert != null); Assert.IsTrue(ConvertUtils.BytesToBase64String(cert) == _certificate); } // Test Pkcs11RsaSignature with temporary RSA key pair that is not associated with any certificate present on the token using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, ckaLabel, ConvertUtils.BytesToHexString(ckaId), _hashAlgorithm)) { try { pkcs11RsaSignature.GetSigningCertificate(); Assert.Fail("Exception expected but not thrown"); } catch (Exception ex) { Assert.IsTrue(ex is ObjectNotFoundException); } } // Delete temporary RSA key pair using (Pkcs11 pkcs11 = new Pkcs11(_libraryPath, false)) { Slot slot = FindSlot(pkcs11, _tokenSerial, _tokenLabel); if (slot == null) throw new TokenNotFoundException(); using (Session session = slot.OpenSession(false)) { session.Login(CKU.CKU_USER, _pin); List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>(); objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_RSA)); objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, ckaLabel)); objectAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId)); List<ObjectHandle> foundObjects = session.FindAllObjects(objectAttributes); foreach (ObjectHandle foundObject in foundObjects) session.DestroyObject(foundObject); session.Logout(); } } }
public void SignPdfDocument() { // Specify path to the unsigned PDF that will be created by this code string unsignedPdfPath = @"c:\temp\unsigned.pdf"; // Specify path to the signed PDF that will be created by this code string signedPdfPath = @"c:\temp\signed.pdf"; // Create simple PDF document with iText using (Document document = new Document(PageSize.A4, 50, 50, 50, 50)) { using (FileStream outputStream = new FileStream(unsignedPdfPath, FileMode.Create)) { using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, outputStream)) { document.Open(); document.Add(new Paragraph("Hello World!")); document.Close(); } } } // Do something interesting with unsigned PDF document FileInfo unsignedPdfInfo = new FileInfo(unsignedPdfPath); Assert.IsTrue(unsignedPdfInfo.Length > 0); // Specify path to the unmanaged PCKS#11 library string libraryPath = @"siecap11.dll"; // Specify serial number of the token that contains signing key. May be null if tokenLabel is specified. string tokenSerial = null; // Specify label of of the token that contains signing key. May be null if tokenSerial is specified string tokenLabel = @"Pkcs11Interop"; // Specify PIN for the token string pin = @"11111111"; // Specify label (value of CKA_LABEL attribute) of the private key used for signing. May be null if ckaId is specified. string ckaLabel = @"John Doe"; // Specify hex encoded string with identifier (value of CKA_ID attribute) of the private key used for signing. May be null if ckaLabel is specified. string ckaId = null; // Specify hash algorihtm used for the signature creation HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256; // Create instance of Pkcs11Signature class that allows iText to create PKCS#1 v1.5 RSA signature with the private key stored on PKCS#11 compatible device using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(libraryPath, tokenSerial, tokenLabel, pin, ckaLabel, ckaId, hashAlgorithm)) { // When signing certificate is stored on the token it can be usually read with GetSigningCertificate() method byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate(); // All certificates stored on the token can be usually read with GetAllCertificates() method List <byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates(); // Build certification path for the signing certificate ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates); // Read unsigned PDF document using (PdfReader pdfReader = new PdfReader(unsignedPdfPath)) { // Create output stream for signed PDF document using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create)) { // Create PdfStamper that applies extra content to the PDF document using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', Path.GetTempFileName(), true)) { // Sign PDF document MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); } } } } // Do something interesting with the signed PDF document FileInfo signedPdfInfo = new FileInfo(signedPdfPath); Assert.IsTrue(signedPdfInfo.Length > signedPdfPath.Length); }
public void Pkcs11RsaSignatureReuseTest() { using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) { byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate(); List<byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates(); ICollection<X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates); for (int i = 0; i < 100; i++) { string unsignedPdfPath = GetTempDocPath(); string signedPdfPath = GetTempDocPath(); try { GenerateRandomPdf(unsignedPdfPath); using (PdfReader pdfReader = new PdfReader(unsignedPdfPath)) using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create)) using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', GetTempDocPath(), true)) MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); Assert.IsTrue(1 == VerifySignatureIntegrity(signedPdfPath)); } finally { File.Delete(unsignedPdfPath); File.Delete(signedPdfPath); } } } }
public void GetAllCertificatesTest() { using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm)) { List<byte[]> allCerts = pkcs11RsaSignature.GetAllCertificates(); Assert.IsTrue(allCerts != null && allCerts.Count > 0); bool signingCertFound = false; foreach (byte[] cert in allCerts) { if (ConvertUtils.BytesToBase64String(cert) == _certificate) { signingCertFound = true; return; } } if (!signingCertFound) Assert.Fail("Signing certificate is not present in the list of all certificates"); } }
public void SignPdfDocument() { // Specify path to the unsigned PDF that will be created by this code string unsignedPdfPath = @"c:\temp\unsigned.pdf"; // Specify path to the signed PDF that will be created by this code string signedPdfPath = @"c:\temp\signed.pdf"; // Create simple PDF document with iText using (Document document = new Document(PageSize.A4, 50, 50, 50, 50)) { using (FileStream outputStream = new FileStream(unsignedPdfPath, FileMode.Create)) { using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, outputStream)) { document.Open(); document.Add(new Paragraph("Hello World!")); document.Close(); } } } // Do something interesting with unsigned PDF document FileInfo unsignedPdfInfo = new FileInfo(unsignedPdfPath); Assert.IsTrue(unsignedPdfInfo.Length > 0); // Specify path to the unmanaged PCKS#11 library string libraryPath = @"siecap11.dll"; // Specify serial number of the token that contains signing key. May be null if tokenLabel is specified. string tokenSerial = null; // Specify label of of the token that contains signing key. May be null if tokenSerial is specified string tokenLabel = @"Pkcs11Interop"; // Specify PIN for the token string pin = @"11111111"; // Specify label (value of CKA_LABEL attribute) of the private key used for signing. May be null if ckaId is specified. string ckaLabel = @"John Doe"; // Specify hex encoded string with identifier (value of CKA_ID attribute) of the private key used for signing. May be null if ckaLabel is specified. string ckaId = null; // Specify hash algorihtm used for the signature creation HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256; // Create instance of Pkcs11Signature class that allows iText to create PKCS#1 v1.5 RSA signature with the private key stored on PKCS#11 compatible device using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(libraryPath, tokenSerial, tokenLabel, pin, ckaLabel, ckaId, hashAlgorithm)) { // When signing certificate is stored on the token it can be usually read with GetSigningCertificate() method byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate(); // All certificates stored on the token can be usually read with GetAllCertificates() method List<byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates(); // Build certification path for the signing certificate ICollection<Org.BouncyCastle.X509.X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates); // Read unsigned PDF document using (PdfReader pdfReader = new PdfReader(unsignedPdfPath)) { // Create output stream for signed PDF document using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create)) { // Create PdfStamper that applies extra content to the PDF document using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', Path.GetTempFileName(), true)) { // Sign PDF document MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); } } } } // Do something interesting with the signed PDF document FileInfo signedPdfInfo = new FileInfo(signedPdfPath); Assert.IsTrue(signedPdfInfo.Length > signedPdfPath.Length); }