我尝试生成RSA密钥对并将其存储在HSM密钥库中.我现在的代码如下所示:
String configName = "C:\\eTokenConfig.cfg"; Provider p = new sun.security.pkcs11.SunPKCS11(configName); Security.addProvider(p); // Read the keystore form the smart card char[] pin = { 'p','4','s','w','0','r','d' }; KeyStore keyStore = KeyStore.getInstance("PKCS11",p); keyStore.load(null,pin); //generate keys KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",p); kpg.initialize(512); KeyPair pair = kpg.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); PublicKey publicKey = pair.getPublic(); // Save Keys How ???
我试图使用keyStore.setEntry方法,但问题是它需要一个证书链,我不知道如何获得此证书?
解决方法
见
http://docs.oracle.com/javase/tutorial/security/apisign/vstep2.html
保存公钥:
X509EncodedKeySpec x509ks = new X509EncodedKeySpec( publicKey.getEncoded()); FileOutputStream fos = new FileOutputStream(strPathFilePubKey); fos.write(x509ks.getEncoded());
加载公钥:
byte[] encodedKey = IoUtils.toByteArray(new FileInputStream(strPathFilePubKey)); KeyFactory keyFactory = KeyFactory.getInstance("RSA",p); X509EncodedKeySpec pkSpec = new X509EncodedKeySpec( encodedKey); PublicKey publicKey = keyFactory.generatePublic(pkSpec);
保存私钥:
PKCS8EncodedKeySpec pkcsKeySpec = new PKCS8EncodedKeySpec( privateKey.getEncoded()); FileOutputStream fos = new FileOutputStream(strPathFilePrivbKey); fos.write(pkcsKeySpec.getEncoded());
加载私钥:
byte[] encodedKey = IoUtils.toByteArray(new FileInputStream(strPathFilePrivKey)); KeyFactory keyFactory = KeyFactory.getInstance("RSA",p); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec( encodedKey); PrivateKey privateKey = keyFactory.generatePrivate(privKeySpec);