I need to connect to an external webservice from my Java application running on Tomcat 6. I have an SSL certificate for my domain purchased and installed on my server. Now I need to connect to an external service and use my certificate private key to digitally sign any data going to the service using SHA-256 hash and 128-bit salt length. How can I use the private key to create this signature? Can I pick any values for the salt? Will they be ab开发者_如何学运维le to decrypt it using my public key from the SSL certificate?
Can I use the Bouncy Castle library for this? Any code or tutorials on the subject would be appreciated.
The JCA documentation provides an example for using Signature
(under Generating and Verifying a Signature Using Generated Keys. You'd use SHA256withRSA
instead of SHA1withDSA
, as it's supported by the SunRsaSignProvider (assuming it's an RSA key). You shouldn't need BouncyCastle for this.
If you want to use BouncyCastle, you'd need to do something along these lines (I've haven't tried this particular code):
AsymmetricKeyParameter keyParam = PrivateKeyFactory.createKey(...);
// You might need to cast to private key to RSAPrivateKey
// and get its attributes manually here.
SHA256Digest digest = new SHA256Digest();
RSADigestSigner signer = new RSADigestSigner(digest);
signer.init(true, keyParam);
signer.update(... data to sign, start, length, ...);
byte[] signature = signer.generatedSignature();
(If you're doing this from within a webapp, you'd also need the webapp to be able to gain access to this private key, which may be a security risk should the webapp be compromised. It might be worth considering using a different key/certificate, even self-signed, if the remote party is willing to accept it.)
I would highly recommend using a webservice stack for this: For eg. an approach for WS-Security client using Apache CXF - http://cxf.apache.org/docs/ws-security.html
One more good reference: http://www.jroller.com/gmazza/entry/cxf_x509_profile
精彩评论