有个需求,说要在生成PDF文件时加上signature。
操作PDF容易,用:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.1.3</version>
</dependency>
加个signature可以用这个方法:
public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion){..}
然后我用PdfStamper对象.getSignatureAppearance()获得一个PdfSignatureAppearance再给他setCrypto...
/**
* Sets the cryptographic parameters.
* @param privKey the private key
* @param certChain the certificate chain
* @param crlList the certificate revocation list. It may be null
* @param filter the cryptographic filter type. It can be SELF_SIGNED, VERISIGN_SIGNED or WINCER_SIGNED
*/
public void setCrypto(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, PdfName filter) {
this.privKey = privKey;
this.certChain = certChain;
this.crlList = crlList;
this.filter = filter;
}
参数列表的前两个东西我需要从KeyStore中得到....
KeyStore...java.security.KeyStore...
String mypassword = "hehe";
KeyStore ks_ = KeyStore.getInstance("JKS");
ks_.store(new FileOutputStream("papa.keystore"),mypassword.toCharArray());
但是却提示:
Exception in thread "main" java.security.KeyStoreException: Uninitialized keystore
那怎么才算initialized?
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
我们需要一个文件!
public final void load(InputStream stream, char[] password) throws IOException,NoSuchAlgorithmException, CertificateException {
keyStoreSpi.engineLoad(stream, password);
initialized = true;
}
在此记录一下windows下生成keystore文件的方法...
先到我的JDK的bin目录下找keytool
输入keytool -genkey -alias hehe.keystore -keystore hehe.keystore,然后按提示走:
按提示再输入两次口令后发现生成了一个.keystore,可以拿来用了。
String PASSWORD = "papa";
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream("hehe.keystore"), PASSWORD.toCharArray());
String alias = (String)ks.aliases().nextElement();
PrivateKey key = (PrivateKey)ks.getKey(alias, PASSWORD.toCharArray());
Certificate[] chain = ks.getCertificateChain(alias);