3

Is java java.security.PrivateKey thread safe? I have to verify digital singature for every request, so I was thinking, once I load the private key file from a physical location, after converting it to java.security.PrivateKey, is it okay to cache it so that I do not have to create the Private every time.

private PrivateKey privateKey;
private PrivateKey getPrivateKey(byte[] keyFileBytes) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyFileBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        this.privateKey=kf.generatePrivate(spec);
    }
mac
  • 543
  • 1
  • 6
  • 17
  • 2
    `PrivateKey` is an interface so you should rather ask if concrete implementation of PrivateKey is thread safe, however it might depend on security provider you are using. – Michał Krzywański Jun 26 '19 at 18:39
  • [This](https://stackoverflow.com/questions/43758503/is-keyfactory-thread-safe) might be helpful. – Michał Krzywański Jun 26 '19 at 18:42
  • Is creating the key really that slow? Or is it really the reading of the `keyFileBytes` from a file that is slow? Did you try caching the bytes and see if you still have a performance issue? The bytes would definitely be thread-safe, right? – Andreas Jun 26 '19 at 18:45
  • 2
    As others have commented, it depends on the implementation. All the implementations I have seen are basically immutable and so thread-safe. However, the contract does not guarantee this so in fact you should assume not and use locking to ensure serialized access. However, for performance you might instead chose to create one copy per thread, this eliminates any possibly of contention. – President James K. Polk Jun 26 '19 at 19:52
  • Thanks Michalk, Andreas and James. I have kept the Privatekey as instance variable, but made the sign method as synchronised to avoid any issues. – mac Jun 27 '19 at 08:51

0 Answers0