RSA密钥对生成和存储到密钥库

时间:2011-03-10 17:06:13

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

2 个答案:

答案 0 :(得分:1)

请参阅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);

答案 1 :(得分:-1)

如果在令牌内生成密钥,则无法读取私钥。 您需要创建一个虚拟证书(例如自签名)并使用别名存储它,密钥库模型依赖于可用的证书。