CQM
CQM

Reputation: 44278

Generate public and private key using a string

In Java I would like to generate a public and private key based on a string in my app.

I'm not going for security, I'm going for "Can I generate the same public and private key using this string".

How would I do that?

I was looking at these methods:

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

But I want to seed the key pair generator with my own string, which ideally will get hashed by these algorithms. KeyGen only takes the SecureRandom object. I want the same resulting key pair, anytime I pass that string.

Upvotes: 5

Views: 3431

Answers (1)

Charles Spencer
Charles Spencer

Reputation: 657

Try adding the following line after initializing random:

random.setSeed(myString.hasCode())

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

If you want to generate a hash that will be guaranteed to be the same during multiple executions of the program, or if you want to be sure that it's truly infeasible to find two String's that generate the same hash, try using something like MessageDigest instead of String.hashCode(). Like this:

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

Also, note that the String must always have the same character encoding each time in order for you to generate the same MessageDigest value and public and private key pair.

Upvotes: 5

Related Questions