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

标签 java keystore pkcs#11

我正在尝试生成 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/

相关文章:

java - 单击列表项后如何保存步骤

java - 存储桶是单个内存位置还是类似于内存位置数组?

android - “App_Name” 由于错误 (500) 无法下载?

android - 获取 "Cause: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded"

rsa - 使用 pkcs#11 api 使用 RSA 签署 sha256 哈希?

java - 在 Google App Engine 中提供没有 html 扩展名的静态文件

java - Lucene Porter Stemmer 未公开

java - Java keystore 中的 Lazysodium key

java - IAIK PKCS#11 包装器 : ECDH KeyAgreement Example

java - PKCS#11 keystore 在成功尝试输入密码后不验证密码