import java.security.*;
import java.security.KeyStore.*;
import java.security.cert.X509Certificate;
import java.security.cert.Certificate;
import com.safenetinc.luna.*;
import java.io.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.security.*;
public class SignPdfUsingLuna{
private static String keyAlias = null;
private static String slotPin = null;
private static int slotId;
private static String inputFile = null;
private static String outputFile = null;
private static KeyStore ks = null;
private static PrivateKeyEntry prKE = null;
private static void usage(){
System.out.println("Command usage :-");
System.out.println("java SignPdfUsingLuna <SlotNumber> <SlotPassword> <KeyAlias> <InputFile>");
}
public static void main(String args[]){
try{
slotId = Integer.parseInt(args[0]);
slotPin = args[1];
keyAlias = args[2];
inputFile = args[3];
ks = KeyStore.getInstance("Luna");
ks.load(new ByteArrayInputStream(("slot:"+slotId).getBytes()),slotPin.toCharArray());
ProtectionParameter param = new PasswordProtection("abcd".toCharArray());
prKE = (PrivateKeyEntry)ks.getEntry(keyAlias,param);
X509Certificate cert = (X509Certificate)ks.getCertificate(keyAlias);
Certificate[] certchain = (Certificate[]) ks.getCertificateChain(keyAlias);
PdfReader readPdf = new PdfReader(inputFile);
FileOutputStream outFile = new FileOutputStream("Signed"+inputFile);
PdfStamper stamp = PdfStamper.createSignature(readPdf, outFile, '\0');
PdfSignatureAppearance psa = stamp.getSignatureAppearance();
psa.setReason("Signed by :- Sam Paul");
psa.setLocation("India");
Image img = Image.getInstance("Logo.jpg");
psa.setImage(img);
psa.setVisibleSignature(new Rectangle(100, 100, 300, 200), 1, "Signature");
ExternalDigest dgst = new BouncyCastleDigest();
Provider prod = ks.getProvider();
PrivateKey pk = prKE.getPrivateKey();
ExternalSignature sign = new PrivateKeySignature(pk,DigestAlgorithms.SHA256,prod.getName());
MakeSignature.signDetached(psa, dgst, sign, certchain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);
stamp.close();
}catch(ArrayIndexOutOfBoundsException aio){
usage();
}catch(NumberFormatException nfe){
System.out.println("Please enter a valid slot number");
usage();
}catch(Exception e){
e.printStackTrace();
}
}
希望這有助於。
Sam。