Question

I am using java cryptography to generate public and private keys. I am using String.getBytes() to generate it. But While decrypting I am using the same String.getBytes() to get the keys. But I am not getting the same keys as same as previous. Please help. Below is the code sample.

KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom ss = null;
ss = new SecureRandom("ABCD".getBytes(UNICODE_FORMAT));
keyGenerator.initialize(512, ss);
KeyPair myKeyPair = keyGenerator.generateKeyPair();   

System.out.println(myKeyPair.getPrivate());
System.out.println(myKeyPair.getPublic());
Was it helpful?

Solution

Your code suggests you have a fundamental misunderstanding about how asymmetric cryptography is supposed to be used. Your sender and receiver should have their own, independent key pairs. The sender then encrypts data using the recipient's public key.

What you're doing is using a fixed string to generate the same key pair in two locations. That's not secure, as you've reduced your key space from 512 bits (which is already too small - use at least 1024-bits) down to the entropy associated with a (presumably short) string.

If you wish to have a "password" string used to derive keys at both ends, then use a symmetric algorithm (e.g. AES) and a password derivation function such as PBKDF2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top