I would like like to check if the public key corresponds to the private key - is it correct.
There is also no provider called BC. I have this implementation but i don't know what Utils.createFixedRandom() suppose to do. I don't have such a library and method.
Besides if you have an raw implementation without java.security it would be awesome.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Signature;
public class BasicDSAExample {
public static void main(String[] args) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "BC");
keyGen.initialize(512, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
Signature signature = Signature.getInstance("DSA", "BC");
signature.initSign(keyPair.getPrivate(), Utils.createFixedRandom() );
byte[] message = new byte[] { (byte) 'a', (byte) 'b', (byte) 'c' };
signature.update(message);
byte[] sigBytes = signature.sign();
signature.initVerify(keyPair.getPublic());
signature.update(message);
if (signature.verify(sigBytes)) {
System.out.println("pow");
} else {
System.out.println("nie");
}
}
}
You can't encrypt and decrypt using DSA, it's a digital signature algorithm. Digital signatures are created by encrypting a hash of the message using the signer's private key, so that it can be verified using their public key. But because it is hashed, the message cannot be recovered.
Following your edit:
If you have a private and a public key, the public key can be derived from the private one anyway, no need to use the key and verify anything. The private key contains all the information to construct a KeyPair
, and then the getPublic()
method will retrieve the equivalent public key. If you want to see if a given public key is correct, just compare with this.