Signing a pdf file with javasign
Following an example of use of javasign api to sign a pdf file. It's necessary to have the itext library in classpath.
////////////////////////////////////////////////////
////////////////////////////////////////////////////
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.cert.Certificate;
import org.javasign.operators.CryptokiGenerator;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfPKCS7;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfSignatureAppearance;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfString;
/*
* Created on 20-may-2009
*/
/**
* @author raffaello bindi
*/
public class JavaSignSigner {
public static void main(String[] args) {
String driver="incryptoki2.dll";
//String driver="bit4opki.dll";
String KEY_LABEL="DSPrivateKey#0";
//String KEY_LABEL="Firma_CNS";
String PIN="123456";
String SIGN_PIN="000000";
try {
CryptokiGenerator p7genSC = new CryptokiGenerator(driver,KEY_LABEL,PIN,SIGN_PIN);
Certificate[] certs = new Certificate[1];
//BelpicCard scd = new BelpicCard("");
//certs[0] = scd.getNonRepudiationCertificate();
certs[0] = p7genSC.getCertificate();
PdfReader reader = new PdfReader("unsigned.pdf");
FileOutputStream fout = new FileOutputStream("signed.pdf");
PdfStamper stamper = PdfStamper.createSignature(reader, fout, '\0');
PdfSignatureAppearance sap = stamper.getSignatureAppearance();
sap.setCrypto(
null, certs, null, PdfSignatureAppearance.SELF_SIGNED);
sap.setReason("How to use iText and Javasign with an Italian smart card");
sap.setLocation("Italy");
sap.setVisibleSignature(new Rectangle(30, 750, 500, 565), 1, null);
sap.setExternalDigest(new byte[128], new byte[20], "RSA");
sap.preClose();
PdfPKCS7 sig = sap.getSigStandard().getSigner();
byte[] content = streamToByteArray(sap.getRangeStream());
//byte[] hash = MessageDigest.getInstance("SHA-1").digest(content);
//byte[] signatureBytes = scd.generateNonRepudiationSignature(hash);
byte[] signatureBytes =p7genSC.buildSignature(content);
sig.setExternalDigest(signatureBytes, null, "RSA");
PdfDictionary dic = new PdfDictionary();
dic.put(PdfName.CONTENTS,
new PdfString(sig.getEncodedPKCS1()).setHexWriting(true));
sap.close(dic);
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] streamToByteArray(InputStream is) throws IOException{
byte[] buff = new byte[512];
int read=-1;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((read=is.read(buff))>=0){
bos.write(buff,0,read);
}
bos.close();
return bos.toByteArray();
}
}
