我正在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 看起来标准输出的方式:
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