RSA keypair generation and storing to keystore

value picture value · Mar 10, 2011 · Viewed 9.3k times · Source

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 ??

Answer

Braully Rocha picture Braully Rocha · Oct 26, 2012

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