Java RSA密钥对生成和存储到密钥库
我正在尝试生成RSA密钥对并将其存储在HSM密钥库中。我现在拥有的代码如下所示:Java RSA密钥对生成和存储到密钥库,java,keystore,pkcs#11,Java,Keystore,Pkcs#11,我正在尝试生成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'
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 ???
我尝试使用keyStore.setEntry方法,但问题是它需要一个证书链,我不知道如何获取此证书???如果在令牌中生成密钥,您应该无法读取私钥。 您需要创建一个虚拟证书(例如自签名证书)并将其与别名一起存储,密钥库模型取决于可用的证书。请参阅 保存公钥:
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);
加载公钥:
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);
加载私钥:
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);
不幸的是,当PKCS#11设备的私钥“不可读取”时,此解决方案不起作用
privateKey.getEncoded()
可能返回null