签名时,“签名算法的密钥太短”

时间:2013-10-13 11:15:09

标签: java rsa digital-signature

我正在尝试初始化Signature对象InvalidKeyException

java.security.InvalidKeyException: Key is too short for this signature algorithm

代码:

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

这就是我获取私钥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

这就是PrivateKey看起来stdout的方式:

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

如何让签名工作?

JDK 1.6

1 个答案:

答案 0 :(得分:1)

这是known bug。描述说:

  

签名算法,例如&#34; SHA384withRSA&#34;和&#34; SHA512withRSA&#34;,要求散列长度应小于密钥大小。如果RSA密钥大小为512位,则无法与SHA384和SHA512一起使用。

虽然有人报道过JDK 7,但我怀疑你也可能偶然发现这个bug。尝试生成更大尺寸的键(1024或更多)。