Note that there are some explanatory texts on larger screens.

plurals
  1. POJava asymmetric encryption: preferred way to store public/private keys
    primarykey
    data
    text
    <p>This code generates a pair of public/private keys:</p> <pre><code>KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair keypair = keyGen.genKeyPair(); PrivateKey privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); </code></pre> <p>What I'd like to know is how do you usually store the public key:</p> <p><strong>Option 1: store the bytes</strong></p> <pre><code>byte[] privateKeyBytes = privateKey.getEncoded(); byte[] publicKeyBytes = publicKey.getEncoded(); // ... write to file // convert bytes back to public/private keys KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); </code></pre> <p>What I don't like is to tie the code to concrete implementations such as <code>PKCS8EncodedKeySpec</code> and <code>X509EncodedKeySpec</code>.</p> <p><strong>Option 2: store the modulus and exponent</strong></p> <pre><code>KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = fact.getKeySpec(publicKey, RSAPublicKeySpec.class); RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,RSAPrivateKeySpec.class); // store modulus and exponent as BigIntegers BigInteger modulus = pub.getModulus()); BigInteger exponent = pub.getPublicExponent()); // ... write to file // recreate public key (the same applies to the private key) RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent); KeyFactory fact = KeyFactory.getInstance("RSA"); PublicKey pubKey = fact.generatePublic(keySpec); </code></pre> <p>The second option is easier to implement, but I don't know if it could be less performant.</p> <p>Any advise ?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload