Generating public and private keys using a string

In Java, I would like to create a string based public and private key in my application.

I'm not going to be safe, I'm going to "Can I generate the same public and private key using this string."

How should I do it?

I have considered these methods:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);

      

But I want to generate a key pair generator using my own string, which would ideally be hashed with these algorithms. KeyGen only accepts an object SecureRandom

. I want to get the same resulting key pair when I pass this string.

+3


source to share


1 answer


Try adding the following line after initialization random

:

random.setSeed(myString.hasCode())

The hash code value of your string will always be the same with the same string during one program execution, and it is considered unlikely to find two strings with the same hash code.



If you want to generate a hash that is guaranteed to be the same across multiple executions of the program, or if you want to be sure that it is really impossible to find two strings that generate the same hash, try using something like MessageDigest instead String.hashCode()

. Like this:

MessageDigest md = MessageDigest.getInstance("SHA-256");
random.setSeed(md.digest(myString.getBytes())

      

Also note that String must always have the same character encoding every time so that you can generate the same value MessageDigest

and public / private key pairs.

+3


source







All Articles