Can't sign a dig sig utilizing java / keytool
I have created a certificate basically straight from the keytool example page:
keytool -genkey -dname "cn=Anything, ou=Anything, o=Anything, c=US" -alias business -keypass kpi135 -keystore C:\mykeystore -storepass ab987c -validity 1095
I am trying to access this certificate and use the private key portion to digitally sign a portion of text to authenticate with a third party. Below is the code I'm attempting:
//Add bouncyCastle as a provider
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileIn开发者_开发问答putStream("C:\\mykeystore"), "ab987c".toCharArray());
Signature sig = Signature.getInstance("MD5withRSA", "BC");
PrivateKey privateKey = (PrivateKey)keystore.getKey("business", "kpi135".toCharArray()); //Exception here
sig.initSign(privateKey);
sig.update("myUID__myNonce".getBytes());
byte[] digitalSignature = sig.sign();
System.out.println("Signature Formulated: " + digitalSignature);
I get the following exception:
java.security.InvalidKeyException: Supplied key (sun.security.provider.DSAPrivat
eKey) is not a RSAPrivateKey instance
at org.bouncycastle.jce.provider.JDKDigestSignature.engineInitSign(Unkno
wn Source)
at java.security.Signature$Delegate.engineInitSign(Signature.java:1095)
at java.security.Signature.initSign(Signature.java:480)
at MainClass.<init>(MainClass.java:15)
at MainClass.main(MainClass.java:28)
I assume it's because I've somehow created the certificate with the wrong type of key, but I'm not sure I'm finding what I need by digging through the keytool page. It does mention that you can apparently generate a key using -keysig RSA and -sigalg RSA however when I try those flags when creating a certificate I get:
keytool error: java.security.NoSuchAlgorithmException: RSA Signature not availab
le
enter code here
Actually it seems you can add "-keyalg RSA" to the keygen command which alleviates the mismatch issue. I was incorrectly trying both -keyalg and -sigalg in the same keygen command. The code above now executes without exceptions.
精彩评论