gpt4 book ai didi

java - RSA key 对生成并存储到 keystore

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:01 27 4
gpt4 key购买 nike

我正在尝试生成 RSA key 对并将其存储在 HSM keystore 中。我现在拥有的代码如下所示:

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 方法,但问题是它需要证书链,但我不知道如何获得该证书??

最佳答案

参见 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);

关于java - RSA key 对生成并存储到 keystore ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5263156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com