i’m trying to implement a mutating encryption algorithm (theoretically developed by me) and as part of the requirements i need to generate an RSA key pair and store it in the database so that it can be retrieved later as part of the encryption process(only used to encrypt a session key so that it can be sent securely with the encrypted message).
my attempt on generating an RSA key pair seem to work however it keeps generating the same values over and over again instead of giving new pairs everytime the code is ran. what did i do wrong?
also if those values are dependent on the machine itself (thus displaying the same values) is there a way to link the key pair generation to the email address provided so that every time a new email address is inputted a different RSA key pair will be outputted?
the following code is my attempt to generate the key pair:
import java.security.*;
import java.security.*;
/**
* @author Speedy gonzales
*/
public class test {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
StringBuffer retString1 = new StringBuffer();
retString1.append("[");
for (int puk = 0; puk < publicKey.length; ++puk) {
retString1.append(publicKey[puk]);
// retString1.append(", ");
}
retString1 = retString1.delete(retString1.length()-2,retString1.length());
retString1.append("]");
System.out.println(retString1);
byte[] privateKey = keyGen.genKeyPair().getPrivate().getEncoded();
StringBuffer retString2 = new StringBuffer();
retString2.append("[");
for (int pri = 0; pri < privateKey.length; ++pri) {
retString2.append(privateKey[pri]);
// retString2.append(", ");
}
retString2 = retString2.delete(retString2.length()-2,retString2.length());
retString2.append("]");
System.out.println(retString2);
}
}
thanks
Well, your first problem is:
You’re not saving the keypair, so you are generating public and private keys that don’t match. From the javadocs,
genKeyPair()behaves as follows:Secondly, getEncoded() just returns the key as a byte array. If your database can store binary values, just store it that way. Otherwise, you would probably have much better luck converting it to a String somehow. You could, for example, base 64 encode it with this neat little trick (probably more reliable that what you’re doing):
You can subsequently get the original bytes back with:
You say that you’re getting the same value every run (and make SURE you are before bothering with this), and I’m not 100% sure why. You should be able to access the algorithm parameters (you might have to cast the key to a different type), try printing those to see if they are the same. Someone mentioned checking your random number generator, that might be a good idea too.