I am tryng to generate RSA开发者_运维技巧 keypair and to store it on the HSM keystore. The code i have right 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 to use the keyStore.setEntry method but the problem is it requires a Certificate chain and I don't know how to get this certificate ??
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());
Load 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());
Load 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);
You should not be able to read the private key if you generate the key inside the token. you'll need to create a dummy certificate (for example self-signed) and store it with an alias, the keystore model depends on certificates to be usable.
精彩评论