Hi Andreas,

I know this is a very old post but im facing the same problem. What you are
trying to say in the paragraph below is not very clear to me. Pardon my
English and can you please explain me bit clearer. 

This is what I'm doing and i always get "Document has been altered since
signature was applied" message.

const string PublicKey =
"<RSAKeyValue><Modulus>**********</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            PdfReader srcReader = null;
            PdfStamper stamper = null;
            FileStream descStream = null;

            try
            {
                var actualCert = new X509Certificate2();
                var store = new X509Store(StoreName.My,
StoreLocation.LocalMachine);
                store.Open(OpenFlags.MaxAllowed);

                foreach (var x509 in store.Certificates)
                {
                    if
(x509.PublicKey.Key.ToXmlString(false).Equals(PublicKey))
                    {
                        actualCert = x509;
                        break;
                    }
                }

                ICollection<X509Certificate> chain = new
List<X509Certificate>();
                X509Chain x509chain = new X509Chain();
                x509chain.Build(actualCert);

                foreach (X509ChainElement x509ChainElement in
x509chain.ChainElements)
                {
                   
chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate));
                }

                const String SRC = "../../Docs/Sample_Unsigned.pdf";
                const String DEST = "../../Docs/Sample_Signed.pdf";
                string TEMP_PATH =
string.Format("../../Docs/Sample_Signed_{0}.pdf", Path.GetRandomFileName());

                //descStream = new FileStream(DEST, FileMode.OpenOrCreate);
                using (var srcStream = new FileStream(SRC, FileMode.Open))
                {
                    data = ServerSignature.ReadFully(srcStream);
                }
                srcReader = new PdfReader(SRC);
                using (var memStream = new MemoryStream())
                {
                    stamper = PdfStamper.CreateSignature(srcReader,
memStream, '\0', TEMP_PATH, false);

                    // Creating the appearance
                    var appearance = stamper.SignatureAppearance;
                    appearance.Reason = "Test cert reason";
                    appearance.Location = "Pavan gurukul";
                    appearance.CertificationLevel =
PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;
                    appearance.SetStamper(stamper);

                    IOcspClient ocspClient = new OcspClientBouncyCastle();
                    List<ICrlClient> crlList = new List<ICrlClient>();
                    crlList.Add(new CrlClientOnline(chain));

                    ITSAClient tsaClient = null;
                    foreach (X509Certificate cert in chain)
                    {
                        string tsaUrl = CertificateUtil.GetTSAURL(cert);
                        if (tsaUrl != null)
                        {
                            tsaClient = new TSAClientBouncyCastle(tsaUrl);
                        }
                    }

                    IExternalSignature es = new ServerSignature();
                    MakeSignature.SignDetached(appearance, es, chain,
crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES);


                    ServerSignature.SaveFully(memStream.ToArray(), DEST);
                }
                Console.WriteLine("Press to exit");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.Read();
            }
            finally
            {
                if (srcReader != null)
                    srcReader.Close();
                if (stamper != null)
                    stamper.Close();
                if (descStream != null)
                    descStream.Close();
            }
        }

        public class ServerSignature : IExternalSignature
        {
            public String GetHashAlgorithm()
            {
                return "SHA256";
            }

            public String GetEncryptionAlgorithm()
            {
                return "RSA";
            }

            public byte[] Sign(byte[] message)
            {
                // Creates a Cryptoki object related to the specific PKCS#11
native library 
                Cryptoki cryptoki = new
Cryptoki(@"~\SafeNet\LunaClient\cryptoki.dll");

                cryptoki.Initialize();

                // Prints all information relating to the native library
                CryptokiInfo info = cryptoki.Info;
                Console.WriteLine("1. Version: {0}", info.Version);
                Console.WriteLine("2. Manugacturer Id: {0}",
info.ManufacturerID);
                Console.WriteLine("3. Library Description: {0}",
info.LibDescription);

                // Reads the set of slots containing a token
                SlotList slots = cryptoki.Slots;
                if (slots.Count == 0)
                {
                    Console.WriteLine("No slot available");
                    return null;
                }

                // Gets the first slot available
                Slot slot = slots[0];

                // Prints all information relating to the slot
                SlotInfo sinfo = slot.Info;
                Console.WriteLine("4. Slot description: {0}",
sinfo.Description);
                Console.WriteLine("5. Slot Manugacturer Id: {0}",
sinfo.ManufacturerID);

                if (!slot.IsTokenPresent)
                {
                    Console.WriteLine("No token inserted in the slot: " +
slots[0].Info.Description);
                    return null;
                }

                // Gets the first token available
                Token token = slot.Token;

                // Prints all information relating to the token
                TokenInfo tinfo = token.Info;
                Console.WriteLine("7. Token Label: {0}", tinfo.Label);
                Console.WriteLine("8. Token Manufacturer Id: {0}",
tinfo.ManufacturerID);
                Console.WriteLine(tinfo.Model);
                Console.WriteLine(tinfo.SerialNumber);
                Console.WriteLine(tinfo.HardwareVersion);

                // Opens a read/write serial session
                Session session =
                    token.OpenSession(Session.CKF_SERIAL_SESSION |
Session.CKF_RW_SESSION,
                                      null,
                                      null);

                // Executes the login passing the user PIN
                int nRes = session.Login(Session.CKU_USER,
"****************");
                if (nRes != 0)
                {
                    Console.WriteLine("Wrong PIN");
                    return null;
                }

                Console.WriteLine("Logged in:" + session.IsLoggedIn);

                var bytes = Signer(session);

                // Logouts and closes the session
                session.Logout();
                session.Close();
                cryptoki.Finalize(IntPtr.Zero);

                return bytes;
            }

public class ServerSignature : IExternalSignature
        {
            public String GetHashAlgorithm()
            {
                return "SHA256";
            }

            public String GetEncryptionAlgorithm()
            {
                return "RSA";
            }

            public byte[] Sign(byte[] message)
            {
                // Creates a Cryptoki object related to the specific PKCS#11
native library 
                Cryptoki cryptoki = new Cryptoki(@"C:\Program
Files\SafeNet\LunaClient\cryptoki.dll");

                cryptoki.Initialize();

                // Prints all information relating to the native library
                CryptokiInfo info = cryptoki.Info;
                Console.WriteLine("1. Version: {0}", info.Version);
                Console.WriteLine("2. Manugacturer Id: {0}",
info.ManufacturerID);
                Console.WriteLine("3. Library Description: {0}",
info.LibDescription);

                // Reads the set of slots containing a token
                SlotList slots = cryptoki.Slots;
                if (slots.Count == 0)
                {
                    Console.WriteLine("No slot available");
                    return null;
                }

                // Gets the first slot available
                Slot slot = slots[0];

                // Prints all information relating to the slot
                SlotInfo sinfo = slot.Info;
                Console.WriteLine("4. Slot description: {0}",
sinfo.Description);
                Console.WriteLine("5. Slot Manugacturer Id: {0}",
sinfo.ManufacturerID);

                if (!slot.IsTokenPresent)
                {
                    Console.WriteLine("No token inserted in the slot: " +
slots[0].Info.Description);
                    return null;
                }

                // Gets the first token available
                Token token = slot.Token;

                // Prints all information relating to the token
                TokenInfo tinfo = token.Info;
                Console.WriteLine("7. Token Label: {0}", tinfo.Label);
                Console.WriteLine("8. Token Manufacturer Id: {0}",
tinfo.ManufacturerID);
                Console.WriteLine(tinfo.Model);
                Console.WriteLine(tinfo.SerialNumber);
                Console.WriteLine(tinfo.HardwareVersion);

                // Opens a read/write serial session
                Session session =
                    token.OpenSession(Session.CKF_SERIAL_SESSION |
Session.CKF_RW_SESSION,
                                      null,
                                      null);

                // Executes the login passing the user PIN
                int nRes = session.Login(Session.CKU_USER,
"Kw6dyNz8mCqJKPCD");
                if (nRes != 0)
                {
                    Console.WriteLine("Wrong PIN");
                    return null;
                }

                Console.WriteLine("Logged in:" + session.IsLoggedIn);

                var bytes = Signer(session);

                // Logouts and closes the session
                session.Logout();
                session.Close();
                cryptoki.Finalize(IntPtr.Zero);

                return bytes;
            }

            public static byte[] ReadFully(Stream input)
            {
                byte[] buffer = new byte[input.Length];
                using (MemoryStream ms = new MemoryStream())
                {
                    int read;
                    while ((read = input.Read(buffer, 0, buffer.Length)) >
0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    return ms.ToArray();
                }
            }

            public static void SaveToFile(string path, Stream ms)
            {
                using (FileStream file = new FileStream(path,
FileMode.Create, System.IO.FileAccess.Write))
                {
                    byte[] bytes = new byte[ms.Length];
                    ms.Read(bytes, 0, (int)ms.Length);
                    file.Write(bytes, 0, bytes.Length);
                    ms.Close();
                }
            }

            private static byte[] Signer(Session session)
            {
                Mechanism SHA256_RSA_PKCS = Mechanism.SHA1_RSA_PKCS;
                SHA256_RSA_PKCS.MechanismType = 64;

                var template = new CryptokiCollection();
                template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS,
CryptokiObject.CKO_PRIVATE_KEY));
                template.Add(new
ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
                CryptokiCollection objects = session.Objects.Find(template,
2);
                var privateKey1 = (RSAPrivateKey)objects[0];
                var privateKey2 = (RSAPrivateKey)objects[1];

                template = new CryptokiCollection();
                template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS,
CryptokiObject.CKO_PUBLIC_KEY));
                template.Add(new
ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
                objects = session.Objects.Find(template, 2);
                var publicKey1 = (RSAPublicKey)objects[0];
                var publicKey2 = (RSAPublicKey)objects[1];

                var signInit2 = session.SignInit(SHA256_RSA_PKCS,
privateKey2);
                var signInitiVerify2 = session.VerifyInit(SHA256_RSA_PKCS,
publicKey2);
                byte[] sign2 = session.Sign(data);
                var signVerify2 = session.Verify(data, sign2);
                Console.WriteLine("Init Verif2: {0}", signInitiVerify2 ==
0);
                Console.WriteLine("Verif2: {0}", signVerify2 == 0);
                return sign2;
            }
        }
}



--
View this message in context: 
http://itext.2136553.n4.nabble.com/PDFSignature-Document-has-been-altered-since-signature-was-applied-tp2157950p4660798.html
Sent from the iText mailing list archive at Nabble.com.

------------------------------------------------------------------------------
BPM Camp - Free Virtual Workshop May 6th at 10am PDT/1PM EDT
Develop your own process in accordance with the BPMN 2 standard
Learn Process modeling best practices with Bonita BPM through live exercises
http://www.bonitasoft.com/be-part-of-it/events/bpm-camp-virtual- event?utm_
source=Sourceforge_BPM_Camp_5_6_15&utm_medium=email&utm_campaign=VA_SF
_______________________________________________
iText-questions mailing list
iText-questions@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/itext-questions

iText(R) is a registered trademark of 1T3XT BVBA.
Many questions posted to this list can (and will) be answered with a reference 
to the iText book: http://www.itextpdf.com/book/
Please check the keywords list before you ask for examples: 
http://itextpdf.com/themes/keywords.php

Reply via email to