I have already encrypted a file (plaintext.txt). Then I need to re-encrypted this file again. However, I'm not sure whether this is because the encrypted file is unreadable or not. So I want to convert it to binary file or some other readable file so that I can re-encrypt again.
Firstly, I have used this code(the public key and private have been generated) to encrypt a .txt file named encrypt.txt.
To try to see whether it can encrypt an encrypted file or not, now I wanna use the same code to re-encrypt "encrypt.txt" file, to generat a re-encrypted file "encrypt2.txt".
However, there is no information in "encrypt2.txt" file, also this file size is 0kb.
Therefore, what I'm asking is that whether this can be used to re-encrypt again or not?
If yes, how can it happen that no information exits in the "encrypt2.txt". Otherwise, how can I do this re-encryption?
Thank you for any illumination!
Following is my code.
public static void main(String[] args) throws Exception {
Security.addProvider(new FlexiCoreProvider());
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "FlexiCore");
Cipher cipher = Cipher.getInstance("RSA", "FlexiCore");
kpg.initialize(1024);
KeyPair keyPair = kpg.generateKeyPair();
PrivateKey privKey = keyPair.getPrivate();
PublicKey pubKey = keyPair.getPublic();
// Encrypt
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String cleartextFile = "cleartext.txt";
String ciphertextFile = "ciphertextRSA.txt";
FileInputStream fis = new FileInputStream(cleartextFile);
FileOutputStream fos = new FileOutputStream(ciphertextFile);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
byte[] block = new byte[32];
int i;
while ((i = fis.read(block)) != -1) {
cos.write(block, 0, i);
}
cos.close();
// Decrypt
String cleartextAgainFile = "cleartextAgainRSA.txt";
cipher.init(Cipher.DECRYPT_MODE, privKey);
fis = new FileInputStream(ciphertextFile);
CipherInputStream cis = new CipherInputStream(fis, cipher);
fos = new FileOutputStream(cleartextAgainFile);
while ((i = cis.read(block)) != -1) {
fos.write(block, 0, i);
}
fos.close();
}