I am getting InvalidKeyException
trying to initialize a Signature object:
java.security.InvalidKeyException: Key is too short for this signature algorithm
The code:
String pkcs8 = 'MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEA34N+ujANvgJ0vc696v2T/L3QUxwNf5VEf9sO/NESOBx9ZNhTHKtmY3vdmW1LVmT07vxVlaMgRhxG90h/HKCD7wIDAQABAkB2kN2PzN/tVIYzDdGnLz7qipJRFAeBD2CX5k9sA0gD5PLtpV0IVxYvSw7rUAOR/GywklF+QWKYwfCqkhMkEJMRAiEA+8fQcNEajDWB/R2VgPPWA8indGQdZT8m9lvo0xYD97kCIQDjQmkd82+UPlRB+g7GwTJw9GIiRvdps3yIKZlCKfHc5wIhAJCDb7BRVNuFGscdY+JQEla5pOO5UuX6CXL97fS6fiyBAiBRFKKYUwAeLda161dWRhuO/UH95L/k8Gqf0eeiGYD3RQIgEiAhiX1quSuBL7LrLGISGyJVy0dw+IXosqFHYeutmEI='
KeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8.decodeBase64())
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign")
PrivateKey pk = keyFactory.generatePrivate(keySpec)
Signature signature = Signature.getInstance("SHA512withRSA", "SunRsaSign")
signature.initSign(pk) // <--- InvalidKeyException
This is how I got the private key pkcs8
:
# generate a private key just for this example
openssl genrsa 512 > mykey.pem
# convert it into pkcs8 format to be able to read it from Java later
openssl pkcs8 -topk8 -inform pem -in mykey.pem -outform pem -nocrypt -out file.pkcs8
This is how the PrivateKey looks stdout'ed:
Sun RSA private CRT key, 512 bits
modulus: 11706359850928035656926954612512379852454997399434114135854653766733637189933721115314465909375387122765789791657314272666480346477870633114913813167113199
public exponent: 65537
private exponent: 6209799048133316441293705496192881663344339603450371209133573984169170039947484349841188666943972061768383840284881642579217732240489331444594222111429393
prime p: 113883566165066111166981826386356612269934395331161452768365784963361173403577
prime q: 102792354025518497728065227780488381725246951885773034739853555051227644026087
prime exponent p: 65365278008836639419826790688453702902877034572485301544697611535190715149441
prime exponent q: 36673799866101187327427577642604625501620828371654868216232903920042186438469
crt coefficient: 8198401844921780663468999895368137692410993828212557924743840907863587133506
How to get that signing working?
JDK 1.6
This was a known bug. Descriptions says:
Signature algorithms, such as "SHA384withRSA" and "SHA512withRSA", require that the hash length should be less than the key size. If the RSA key size is 512 bits, it will not be able to use with the SHA384 and SHA512.
Though it was reported for JDK 7, I suspect you could stumble over this bug too. Try to generate a key of a bigger size (1024 and more).