I am trying to encrypt and decrypt the data with RSA 2048.
We have one public key and private key and will be using same throughout. but the problem is, when I decrypt, I am getting javax.crypto.BadPaddingException: Data must start with zero
File file = new File("C:\\temp-ldi\\pubkey.txt");
FileWriter writer = new FileWriter(file);
file.createNewFile();
encryptedText = RSACrypto.encrypt("PLAIN TEXT"); //no argument of pub-key, generate key pair
writer.write(new BASE64Encoder().encode(RSACrypto.pubKeyToBytes(RSACrypto.publicKey)));
writer.close();
file = new File("C:\\temp-ldi\\privkey.txt");
writer = new FileWriter(file);
file.createNewFile();
writer.write(new BASE64Encoder().encode(RSACrypto.privKeyToBytes(RSACrypto.privateKey)));
writer.close();
then I am using below code to decrypt the data
File privfile = new File("C:\\temp-ldi\\privkey.txt");
File pubfile = new File("C:\\temp-ldi\\pubkey.txt");
FileReader reader = new FileReader(pubfile);
// file.createNewFile();
BufferedReader br = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String s;
while ((s = br.readLine()) != null) {
sb.append(s);
}
br.close();
reader.close();
this.encryptedText = RSACrypto.encrypt("PLAIN TEXT", sb.toString());
reader = new FileReader(privfile);
br = new BufferedReader(reader);
sb = new StringBuilder();
while ((s = br.readLine()) != null) {
sb.append(s);
}
br.close();
reader.close();
System.out.println(RSACrypto.decrypt(this.encryptedText, sb.toString()));
all the encryption/decryption string will return in Base64Encoder/Base64Decoder format.
How do I pass the private key from file/simple string so that the key is not modified.
Update RSACrypto class : http://sebsauvage.net/paste/?83517f2b3db94d24#Sdu12/vXPuxa5AxO95FPgKSF6N40R2DzD6lwQkvroyE=
OK, problem in RSACrypto. When you encrypt file, it creates every time new keypair (in
encrypt
). Just remove new keypair generation from encrypt, callnewKeyPair
direcly, when you need it. And that static variables does no good for multi-thread environment.I'll suggest to throw RSACrypto class, or rewrite it at least. I don't know why you so afraid of using byte[] type and why you need everything be BASE64 encoded. Code will a lot simple without additional encoding/decoding.
Here is working example (without RSACrypto), you can use it as template: