Search code examples
javacryptographydigital-signaturejcejca

Signing with javax.crypto.Cipher vs java.security.Signature


I'm working on some old piece of code that needs to be updated to use another crypto provider. I'm no Java expert. I'm trying to understand what is the difference between signing a hash with javax.crypto.Cipher and java.security.Signature.

The existing code looks similar to this:

  Cipher cipher = Cipher.getInstance(CFG_ALGO);
  cipher.init(Cipher.DECRYPT_MODE, privateKey);
  byte[] signature = cipher.doFinal(payload);

The sample snippet I have received that uses the new provider looks like this:

  final Signature sign = Signature.getInstance("RSA", SIGNATURE_PROVIDER);
  sign.initSign(keystore.getPrivateKey(keyName, keyPass));
  sign.update(data);
  byte[] signature = sign.sign();

Is there any difference between the two if I will use the same provider for both? Is one way generally preferred over another?


Solution

  • Cipher is for encryption & decryption; Signature is for signing and verifying.

    The only reason why Cipher may also be used in the signing context under certain circumstances, is that certain signing schemes work by encrypting a fingerprint with a private key so that others with access to the corresponding public key can decrypt the data and so verify.

    This is not the case for all signing schemes, though, e.g. DSA and ECDSA work entirely differently.

    Even if you currently use only RSA signatures, therefore, you should use Signature for the sake of later maintainability.