Discussion:
[iText-questions] PDFSignature - "Document has been altered since signature was applied"
AndreiGosman
2008-11-12 16:33:40 UTC
Permalink
Hi,

I was a very big problem using iTextSharp and Aladdin eToken for signing PDF
files. After I sign a pdf, Acrobat Reader gives the following message:

"The document has been altered or corrupted since teh Certification was
applied"

Here is my code:
Does someone know what is wrong?

X509Certificate2 card = GetCertificate(certSerial);
Org.BouncyCastle.X509.X509CertificateParser cp = new
Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new
Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData)
};

PdfReader reader = new PdfReader(fileToSign,
Encoding.ASCII.GetBytes(ownerPassword));
PdfStamper stp = PdfStamper.CreateSignature(reader, new
FileStream(signedFileName, FileMode.Create), '\0', null, true);
PdfSignatureAppearance sap = stp.SignatureAppearance;
sap.SignDate = signDate;
sap.SetCrypto(null, chain, null,
PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Location = location;
sap.Acro6Layers = true;
sap.Render =
PdfSignatureAppearance.SignatureRender.GraphicAndDescription;
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100,
250, 150), 1, null);
sap.Render =
PdfSignatureAppearance.SignatureRender.NameAndDescription;
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
PdfName.ADBE_PKCS7_DETACHED);
dic.Date = new PdfDate(sap.SignDate);
dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
if (sap.Reason != null)
dic.Reason = sap.Reason;
if (sap.Location != null)
dic.Location = sap.Location;
sap.CryptoDictionary = dic;
int csize = 4000;
Hashtable exc = new Hashtable();
exc[PdfName.CONTENTS] = csize * 2 +2;
sap.PreClose(exc);
//sap.PreClose();

HashAlgorithm sha = new SHA1CryptoServiceProvider();

Stream s = sap.RangeStream;
int read = 0;
byte[] buff = new byte[8192];
while ((read = s.Read(buff, 0, 8192)) > 0)
{
sha.TransformBlock(buff, 0, read, buff, 0);
}
sha.TransformFinalBlock(buff, 0, 0);
byte[] pk = SignMsg(sha.Hash, card,false);

byte[] outc = new byte[csize];

PdfDictionary dic2 = new PdfDictionary();
try
{
Array.Copy(pk, 0, outc, 0, pk.Length);
dic2.Put(PdfName.CONTENTS, new
PdfString(outc).SetHexWriting(true));
}
finally
{

sap.Close(dic2);
}

Regards
Andrei Gosman
--
View this message in context: http://www.nabble.com/PDFSignature---%22Document-has-been-altered-since-signature-was-applied%22-tp20463953p20463953.html
Sent from the iText - General mailing list archive at Nabble.com.
Paulo Soares
2008-11-12 17:13:16 UTC
Permalink
See http://itextpdf.sourceforge.net/howtosign.html#signextitextsharp2.

Paulo

________________________________________
From: AndreiGosman [***@magnet-software.com]
Sent: Wednesday, November 12, 2008 4:33 PM
To: itext-***@lists.sourceforge.net
Subject: [iText-questions] PDFSignature - "Document has been altered since signature was applied"

Hi,

I was a very big problem using iTextSharp and Aladdin eToken for signing PDF
files. After I sign a pdf, Acrobat Reader gives the following message:

"The document has been altered or corrupted since teh Certification was
applied"

Here is my code:
Does someone know what is wrong?

X509Certificate2 card = GetCertificate(certSerial);
Org.BouncyCastle.X509.X509CertificateParser cp = new
Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new
Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData)
};

PdfReader reader = new PdfReader(fileToSign,
Encoding.ASCII.GetBytes(ownerPassword));
PdfStamper stp = PdfStamper.CreateSignature(reader, new
FileStream(signedFileName, FileMode.Create), '\0', null, true);
PdfSignatureAppearance sap = stp.SignatureAppearance;
sap.SignDate = signDate;
sap.SetCrypto(null, chain, null,
PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Location = location;
sap.Acro6Layers = true;
sap.Render =
PdfSignatureAppearance.SignatureRender.GraphicAndDescription;
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100,
250, 150), 1, null);
sap.Render =
PdfSignatureAppearance.SignatureRender.NameAndDescription;
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
PdfName.ADBE_PKCS7_DETACHED);
dic.Date = new PdfDate(sap.SignDate);
dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
if (sap.Reason != null)
dic.Reason = sap.Reason;
if (sap.Location != null)
dic.Location = sap.Location;
sap.CryptoDictionary = dic;
int csize = 4000;
Hashtable exc = new Hashtable();
exc[PdfName.CONTENTS] = csize * 2 +2;
sap.PreClose(exc);
//sap.PreClose();

HashAlgorithm sha = new SHA1CryptoServiceProvider();

Stream s = sap.RangeStream;
int read = 0;
byte[] buff = new byte[8192];
while ((read = s.Read(buff, 0, 8192)) > 0)
{
sha.TransformBlock(buff, 0, read, buff, 0);
}
sha.TransformFinalBlock(buff, 0, 0);
byte[] pk = SignMsg(sha.Hash, card,false);

byte[] outc = new byte[csize];

PdfDictionary dic2 = new PdfDictionary();
try
{
Array.Copy(pk, 0, outc, 0, pk.Length);
dic2.Put(PdfName.CONTENTS, new
PdfString(outc).SetHexWriting(true));
}
finally
{

sap.Close(dic2);
}

Regards
Andrei Gosman

Aviso Legal:
Esta mensagem � destinada exclusivamente ao destinat�rio. Pode conter informa��o confidencial ou legalmente protegida. A incorrecta transmiss�o desta mensagem n�o significa a perca de confidencialidade. Se esta mensagem for recebida por engano, por favor envie-a de volta para o remetente e apague-a do seu sistema de imediato. � proibido a qualquer pessoa que n�o o destinat�rio de usar, revelar ou distribuir qualquer parte desta mensagem.

Disclaimer:
This message is destined exclusively to the intended receiver. It may contain confidential or legally protected information. The incorrect transmission of this message does not mean the loss of its confidentiality. If this message is received by mistake, please send it back to the sender and delete it from your system immediately. It is forbidden to any person who is not the intended receiver to use, distribute or copy any part of this message.
AndreiGosman
2008-11-13 08:40:40 UTC
Permalink
Hi,

Thank you very much.
Problem is now solved

Andrei Gosman
Post by Paulo Soares
See http://itextpdf.sourceforge.net/howtosign.html#signextitextsharp2.
Paulo
________________________________________
Sent: Wednesday, November 12, 2008 4:33 PM
Subject: [iText-questions] PDFSignature - "Document has been altered since
signature was applied"
Hi,
I was a very big problem using iTextSharp and Aladdin eToken for signing PDF
"The document has been altered or corrupted since teh Certification was
applied"
Does someone know what is wrong?
X509Certificate2 card = GetCertificate(certSerial);
Org.BouncyCastle.X509.X509CertificateParser cp = new
Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new
Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData)
};
PdfReader reader = new PdfReader(fileToSign,
Encoding.ASCII.GetBytes(ownerPassword));
PdfStamper stp = PdfStamper.CreateSignature(reader, new
FileStream(signedFileName, FileMode.Create), '\0', null, true);
PdfSignatureAppearance sap = stp.SignatureAppearance;
sap.SignDate = signDate;
sap.SetCrypto(null, chain, null,
PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Location = location;
sap.Acro6Layers = true;
sap.Render =
PdfSignatureAppearance.SignatureRender.GraphicAndDescription;
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100,
250, 150), 1, null);
sap.Render =
PdfSignatureAppearance.SignatureRender.NameAndDescription;
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
PdfName.ADBE_PKCS7_DETACHED);
dic.Date = new PdfDate(sap.SignDate);
dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
if (sap.Reason != null)
dic.Reason = sap.Reason;
if (sap.Location != null)
dic.Location = sap.Location;
sap.CryptoDictionary = dic;
int csize = 4000;
Hashtable exc = new Hashtable();
exc[PdfName.CONTENTS] = csize * 2 +2;
sap.PreClose(exc);
//sap.PreClose();
HashAlgorithm sha = new SHA1CryptoServiceProvider();
Stream s = sap.RangeStream;
int read = 0;
byte[] buff = new byte[8192];
while ((read = s.Read(buff, 0, 8192)) > 0)
{
sha.TransformBlock(buff, 0, read, buff, 0);
}
sha.TransformFinalBlock(buff, 0, 0);
byte[] pk = SignMsg(sha.Hash, card,false);
byte[] outc = new byte[csize];
PdfDictionary dic2 = new PdfDictionary();
try
{
Array.Copy(pk, 0, outc, 0, pk.Length);
dic2.Put(PdfName.CONTENTS, new
PdfString(outc).SetHexWriting(true));
}
finally
{
sap.Close(dic2);
}
Regards
Andrei Gosman
Esta mensagem é destinada exclusivamente ao destinatário. Pode conter
informação confidencial ou legalmente protegida. A incorrecta transmissão
desta mensagem não significa a perca de confidencialidade. Se esta
mensagem for recebida por engano, por favor envie-a de volta para o
remetente e apague-a do seu sistema de imediato. É proibido a qualquer
pessoa que não o destinatário de usar, revelar ou distribuir qualquer
parte desta mensagem.
This message is destined exclusively to the intended receiver. It may
contain confidential or legally protected information. The incorrect
transmission of this message does not mean the loss of its
confidentiality. If this message is received by mistake, please send it
back to the sender and delete it from your system immediately. It is
forbidden to any person who is not the intended receiver to use,
distribute or copy any part of this message.
-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's
challenge
Build the coolest Linux based applications with Moblin SDK & win great
prizes
Grand prize is a trip for two to an Open Source event anywhere in the
world
http://moblin-contest.org/redirect.php?banner_id=100&url=/
_______________________________________________
iText-questions mailing list
https://lists.sourceforge.net/lists/listinfo/itext-questions
Buy the iText book: http://www.1t3xt.com/docs/book.php
--
View this message in context: http://www.nabble.com/PDFSignature---%22Document-has-been-altered-since-signature-was-applied%22-tp20463953p20476730.html
Sent from the iText - General mailing list archive at Nabble.com.
m***@sitmobile.com
2010-03-20 15:07:26 UTC
Permalink
I am also facing the same issue could u please elaborate on how u resolved it.


Regards
Martin-- AndreiGosman wrote :

Hi,

I was a very big problem using iTextSharp and Aladdin eToken for signing PDF
files. After I sign a pdf, Acrobat Reader gives the following message:

"The document has been altered or corrupted since teh Certification was
applied"

Here is my code:
Does someone know what is wrong?

X509Certificate2 card = GetCertificate(certSerial);
Org.BouncyCastle.X509.X509CertificateParser cp = new
Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new
Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData)
};

PdfReader reader = new PdfReader(fileToSign,
Encoding.ASCII.GetBytes(ownerPassword));
PdfStamper stp = PdfStamper.CreateSignature(reader, new
FileStream(signedFileName, FileMode.Create), '\0', null, true);
PdfSignatureAppearance sap = stp.SignatureAppearance;
sap.SignDate = signDate;
sap.SetCrypto(null, chain, null,
PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Location = location;
sap.Acro6Layers = true;
sap.Render =
PdfSignatureAppearance.SignatureRender.GraphicAndDescription;
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100,
250, 150), 1, null);
sap.Render =
PdfSignatureAppearance.SignatureRender.NameAndDescription;
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
PdfName.ADBE_PKCS7_DETACHED);
dic.Date = new PdfDate(sap.SignDate);
dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
if (sap.Reason != null)
dic.Reason = sap.Reason;
if (sap.Location != null)
dic.Location = sap.Location;
sap.CryptoDictionary = dic;
int csize = 4000;
Hashtable exc = new Hashtable();
exc[PdfName.CONTENTS] = csize * 2 +2;
sap.PreClose(exc);
//sap.PreClose();

HashAlgorithm sha = new SHA1CryptoServiceProvider();

Stream s = sap.RangeStream;
int read = 0;
byte[] buff = new byte[8192];
while ((read = s.Read(buff, 0, 8192)) > 0)
{
sha.TransformBlock(buff, 0, read, buff, 0);
}
sha.TransformFinalBlock(buff, 0, 0);
byte[] pk = SignMsg(sha.Hash, card,false);

byte[] outc = new byte[csize];

PdfDictionary dic2 = new PdfDictionary();
try
{
Array.Copy(pk, 0, outc, 0, pk.Length);
dic2.Put(PdfName.CONTENTS, new
PdfString(outc).SetHexWriting(true));
}
finally
{

sap.Close(dic2);
}

Regards
Andrei Gosman
--
View this message in context: http://www.nabble.com/PDFSignature---%22Document-has-been-altered-since-signature-was-applied%22-tp20463953p20463953.html
Sent from the iText - General mailing list archive at Nabble.com.


-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/
_______________________________________________
iText-questions mailing list
iText-***@list...
https://lists.sourceforge.net/lists/listinfo/itext-questions

Buy the iText book: http://www.1t3xt.com/docs/book.php


--
This message was sent on behalf of ***@sitmobile.com at openSubscriber.com
http://www.opensubscriber.com/message/itext-***@lists.sourceforge.net/10726249.html
Andreas Kuehne
2010-03-20 20:03:03 UTC
Permalink
Hi Mathew,

afaik the problem can not be solved, just circumvented.
You get one hash from a PDF, after storing and reopening you get another hash. The raesons for this are not an iText issue and are already discussed on this list in detail.

So how to get around :

Don't store and reopen the PDF before applying the signature.
Or replace the signature in the stored PDF without using iText functionalities but low level file operations : Find the signature area in fuile, overwrite bytes x to y with the signature.

Hope this helps.

Andreas



----- Original Message ----
From: "***@sitmobile.com" <***@sitmobile.com>
To: itext-***@lists.sourceforge.net
Sent: Sat, March 20, 2010 4:07:26 PM
Subject: Re: [iText-questions] PDFSignature - "Document has been altered since signature was applied"

I am also facing the same issue could u please elaborate on how u resolved it.


Regards
Martin-- AndreiGosman wrote :

Hi,

I was a very big problem using iTextSharp and Aladdin eToken for signing PDF
files. After I sign a pdf, Acrobat Reader gives the following message:

"The document has been altered or corrupted since teh Certification was
applied"

Here is my code:
Does someone know what is wrong?

X509Certificate2 card = GetCertificate(certSerial);
Org.BouncyCastle.X509.X509CertificateParser cp = new
Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new
Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData)
};

PdfReader reader = new PdfReader(fileToSign,
Encoding.ASCII.GetBytes(ownerPassword));
PdfStamper stp = PdfStamper.CreateSignature(reader, new
FileStream(signedFileName, FileMode.Create), '\0', null, true);
PdfSignatureAppearance sap = stp.SignatureAppearance;
sap.SignDate = signDate;
sap.SetCrypto(null, chain, null,
PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Location = location;
sap.Acro6Layers = true;
sap.Render =
PdfSignatureAppearance.SignatureRender.GraphicAndDescription;
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100,
250, 150), 1, null);
sap.Render =
PdfSignatureAppearance.SignatureRender.NameAndDescription;
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
PdfName.ADBE_PKCS7_DETACHED);
dic.Date = new PdfDate(sap.SignDate);
dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
if (sap.Reason != null)
dic.Reason = sap.Reason;
if (sap.Location != null)
dic.Location = sap.Location;
sap.CryptoDictionary = dic;
int csize = 4000;
Hashtable exc = new Hashtable();
exc[PdfName.CONTENTS] = csize * 2 +2;
sap.PreClose(exc);
//sap.PreClose();

HashAlgorithm sha = new SHA1CryptoServiceProvider();

Stream s = sap.RangeStream;
int read = 0;
byte[] buff = new byte[8192];
while ((read = s.Read(buff, 0, 8192)) > 0)
{
sha.TransformBlock(buff, 0, read, buff, 0);
}
sha.TransformFinalBlock(buff, 0, 0);
byte[] pk = SignMsg(sha.Hash, card,false);

byte[] outc = new byte[csize];

PdfDictionary dic2 = new PdfDictionary();
try
{
Array.Copy(pk, 0, outc, 0, pk.Length);
dic2.Put(PdfName.CONTENTS, new
PdfString(outc).SetHexWriting(true));
}
finally
{

sap.Close(dic2);
}

Regards
Andrei Gosman
--
View this message in context: http://www.nabble.com/PDFSignature---%22Document-has-been-altered-since-signature-was-applied%22-tp20463953p20463953.html
Sent from the iText - General mailing list archive at Nabble.com.


-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/
_______________________________________________
iText-questions mailing list
iText-***@list...
https://lists.sourceforge.net/lists/listinfo/itext-questions

Buy the iText book: http://www.1t3xt.com/docs/book.php


--
This message was sent on behalf of ***@sitmobile.com at openSubscriber.com
http://www.opensubscriber.com/message/itext-***@lists.sourceforge.net/10726249.html

------------------------------------------------------------------------------
Download Intel® Parallel Studio Eval
Try the new software tools for yourself. Speed compiling, find bugs
proactively, and fine-tune applications for parallel performance.
See why Intel Parallel Studio got high marks during beta.
http://p.sf.net/sfu/intel-sw-dev
_______________________________________________
iText-questions mailing list
iText-***@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/itext-questions

Buy the iText book: http://www.1t3xt.com/docs/book.php
Check the site with examples before you ask questions: http://www.1t3xt.info/examples/
You can also search the keywords list: http://1t3xt.info/tutorials/keywords/
ptpavankumar
2015-04-18 15:24:10 UTC
Permalink
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-***@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
mkl
2015-04-20 07:28:42 UTC
Permalink
ptpavankumar,

your ServerSignature implementation of the method public byte[] Sign(byte[]
message) completely ignores the message argument. Thus, the generated
signature does not at all relate to the PDF in question.

Regards, Michael



--
View this message in context: http://itext.2136553.n4.nabble.com/PDFSignature-Document-has-been-altered-since-signature-was-applied-tp2157950p4660799.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-***@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
Loading...