0

I am a beginner with DSA and I want to implement its with java. In this code, key are generate random but I want to generate its with my password.
Because my goal want to verify key.
Please help! Thank you in advance.

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

public class MainClass {
  public static void main(String[] args) throws Exception {
    String alg = "DSA";
    KeyPairGenerator kg = KeyPairGenerator.getInstance(alg);
    KeyPair keyPair = kg.genKeyPair();

    byte[] signature = performSigning("test", alg, keyPair);
    performVerification(args[0], alg, signature, keyPair.getPublic());
  }

  static byte[] performSigning(String s, String alg, KeyPair keyPair) throws Exception {
    Signature sign = Signature.getInstance(alg);
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    sign.initSign(privateKey);
    sign.update(s.getBytes());
    return sign.sign();
  }

  static void performVerification(String s, String alg, byte[] signature, PublicKey publicKey)
      throws Exception {
    Signature sign = Signature.getInstance(alg);
    sign.initVerify(publicKey);
    sign.update(s.getBytes());
    System.out.println(sign.verify(signature));
  }
}

I want to input password:

String password = "123456";
Jony
  • 101
  • 5
  • Probably the best you can do is encrypt the private key with this password, using some algorithm like AES and decrypt it each time before signing. – Iakovos Jun 04 '18 at 10:48
  • You should also not be generating a new key pair each time, otherwise you will not be able to sign/verify once the code execution has finished. Instead, you should store the key pair (encrypting the private key if you want) in a file and import it each time. – Iakovos Jun 04 '18 at 10:55
  • Since the DSA secret key (`x`) is an integer, you could use [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) to generate it from the password. Java's DSAPrivateKey interface only returns `x`, so it is pretty trivial to write your own PBKDF2-based DSAPrivateKey class. See [DSAPrivateKey](https://docs.oracle.com/javase/7/docs/api/index.html?java/security/interfaces/DSAKeyPairGenerator.html) – lockcmpxchg8b Jun 11 '18 at 00:24
  • Use a PBKDF2-based random number generator. The password seeds the generator's state, and then the generator is used to create the key pair. You may need to create your own `java.util.Random`-derived class. But I believe DSA has its own requirements for generation. You should read [FIPS 186 | Appendix A.2](https://csrc.nist.gov/publications/detail/fips/186/4/final). – jww Jun 11 '18 at 15:23

0 Answers0