I am trying to sign a pdf document in java using a USB e-token.I want to read the signature from USB token safenet (alladin etoken pro 72 k(Java)) and attach to pdf using java code.I have done digital signature signing using a key stored in my local machine.But i want to know how the same can be done using a USB e-token.
Reading a pfx file from usb token with java
12.7k views Asked by user3914864 AtThere are 3 answers
Try this code
import com.lowagie.text.pdf.*;
import com.lowagie.text.Rectangle;
//import com.lowagie.text.pdf.pdfSignatureAppearance;
//import com.lowagie.text.pdf.pdfStamper;
import java.security.*;
import java.io.*;
import java.awt.*;
import java.security.cert.*;
import java.lang.*;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertPath;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
public class pdfsign1{
public static void main(String args[]) {
try {
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray());
String alias = (String)ks.aliases().nextElement();
PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray());
Certificate[] chain = ks.getCertificateChain(alias);[/b]
PdfReader reader = new PdfReader("original.pdf");
FileOutputStream fout = new FileOutputStream("signed.pdf");
PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
PdfSignatureAppearance sap = stp.getSignatureAppearance();
//sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
sap.setReason("I'm the author");
sap.setLocation("Lisbon");
// comment next line to have an invisible signature
sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
stp.close();
}
catch(Exception e) {}
}
}
The whole point of a USB token for signing is, that nobody can read the secret key from that device. So you sent the hash to the token and the token will send you the signature back.
For this to work you need a JCE provider which can talk to the token. This is typically done either by PKCS#11 (the token delivers a library for this) or the token delivers a MSCAPI driver (under windows).
Both can be used under Java, the PKCS#11 way might be a bit more complicated to setup, but in my experience it is better for automated signing because in the MSCAPI case you often need to enter the token PIN manually.
If your token is recognized by windows the following command should see and list its key:
keytool -list -storetype Windows-MY
The Windows Keystore can then be used to get a handle of the key for signing, but you can also use it to export a copy of the public key.
You can use SUN PKCS11 provider to refer the keys in the Etoken.You can just try the below code