RSA key generation and key storage

I am trying to create an RSA key pair and store it in the HSM key store. The code I have now looks like this:

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', '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 ??? 

I tried using the keyStore.setEntry method, but the problem is that this requires a certificate chain, and I don't know how to get this certificate

+7
source share
2 answers

See http://docs.oracle.com/javase/tutorial/security/apisign/vstep2.html

Save Public Key:

  X509EncodedKeySpec x509ks = new X509EncodedKeySpec( publicKey.getEncoded()); FileOutputStream fos = new FileOutputStream(strPathFilePubKey); fos.write(x509ks.getEncoded()); 

Download public key:

  byte[] encodedKey = IOUtils.toByteArray(new FileInputStream(strPathFilePubKey)); KeyFactory keyFactory = KeyFactory.getInstance("RSA", p); X509EncodedKeySpec pkSpec = new X509EncodedKeySpec( encodedKey); PublicKey publicKey = keyFactory.generatePublic(pkSpec); 

Save Private Key:

  PKCS8EncodedKeySpec pkcsKeySpec = new PKCS8EncodedKeySpec( privateKey.getEncoded()); FileOutputStream fos = new FileOutputStream(strPathFilePrivbKey); fos.write(pkcsKeySpec.getEncoded()); 

Download private key:

  byte[] encodedKey = IOUtils.toByteArray(new FileInputStream(strPathFilePrivKey)); KeyFactory keyFactory = KeyFactory.getInstance("RSA", p); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec( encodedKey); PrivateKey privateKey = keyFactory.generatePrivate(privKeySpec); 
+1
source

You cannot read the private key if you create the key inside the token. you need to create a dummy certificate (for example, self-signed) and save it with an alias, the key storage model depends on the suitability of the certificates used.

-one
source

All Articles