Exception when calling MessageDigest.getInstance("SHA256")

kingston picture kingston · Sep 28, 2012 · Viewed 31.7k times · Source

I have code that works well on Android. When I ported it to my Windows 64-bit machine with JRE 1.6, the code did not work.

When I run the following line of code:

final MessageDigest digest = MessageDigest.getInstance("SHA256")

I get the following exception:

java.security.NoSuchAlgorithmException: SHA256 MessageDigest not available at sun.security.jca.GetInstance.getInstance(Unknown Source) at java.security.Security.getImpl(Unknown Source) at java.security.MessageDigest.getInstance(Unknown Source)

I found on Internet people claiming that it is possible to use SHA256 with the standard crypto provider that comes with Sun JRE and people saying that I need to use another provider like for example Bouncy Castle.

I would prefer not to use a different provider. Is it possible to make it working?

Answer

David Grant picture David Grant · Sep 28, 2012

When in doubt over what algorithms you can use for a JCA service, your first port of call should be the JCA Standard Algorithm Name Documentation. The algorithms guaranteed to be supported by the MessageDigest service in a JCA-compliant JVM are:

  • MD2
  • MD5
  • SHA-1
  • SHA-256
  • SHA-384
  • SHA-512

It's common for providers to supply aliases for these algorithms, which is why it'd probably work with Bouncy Castle, but you should stick to these if you can to maximise portability.

If you change your code to the following, it will work as expected:

final MessageDigest digest = MessageDigest.getInstance("SHA-256");