在前面的章节中介绍了如何利用KeyTool工具生成keyStore:。
但是很多时候,在javaWeb项目中,比如给每个用户加上独特的数字签名,那么我们需要在创建用户的时候,给其生成独一无二的keystore。我现在主要的功能是,给每个用户下载pdf的时候加上数字签名。
下面说一下生成keystore的主要思想:借助keyTool中的生成keyStore的方法。主要利用sun.security.tools.keytool包文件来处理。
import java.io.FileOutputStream;import java.io.IOException;import java.security.GeneralSecurityException;import java.security.KeyStore;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.PrivateKey;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.Date;import sun.security.tools.keytool.CertAndKeyGen;import sun.security.x509.X500Name;/** * 主要用于创建keyStore文件,保存起来 * * @author Xia * */public class KeyStoreCreate2 { public static String filePath = "src/main/resources/pdf0090createEncrypt/new_KeyStore.keystore"; private static final int keysize = 1024; private static final String commonName = "www.ctbri.com"; private static final String organizationalUnit = "IT"; private static final String organization = "test"; private static final String city = "beijing"; private static final String state = "beijing"; private static final String country = "beijing"; private static final long validity = 1096; // 3 years private static final String alias = "tomcat"; private static final char[] keyPassword = "123456".toCharArray(); public static void main(String[] args) throws GeneralSecurityException { try { KeyStore ks = KeyStore.getInstance("pkcs12");// char[] password = "123456".toCharArray(); ks.load(null, null); CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null); X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country); keypair.generate(keysize); PrivateKey privateKey = keypair.getPrivateKey(); X509Certificate[] chain = new X509Certificate[1]; chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long)validity*24*60*60); // store away the key store FileOutputStream fos = new FileOutputStream(filePath); ks.setKeyEntry(alias, privateKey, keyPassword, chain); ks.store(fos, keyPassword); fos.close(); System.out.println("create Success"); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }