I have the problem that when I write what I want to encrypt in my text file it "encrypts in a weird way" because I think the key is written and not the ciphertext. And when I go to decrypt it to show in the console the originally inserted text, what I assume is the key is shown.
This is what happens:
[![enter image description here][1]][1]
I'm not understanding what the hell is going on in my code ???
public class Start {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
// TODO Auto-generated method stub
String fich = "./ficheros/cifrador.txt", texto = "", string = "";
Scanner scan = new Scanner(System.in);
File fileEditar = new File(fich);
if (!fileEditar.exists()) {
System.out.println("El archivo no existe");
} else {
System.out.println("Introduzca el texto:");
texto = scan.next();
// CIFRADOR
KeyGenerator keygen = KeyGenerator.getInstance("DES");//GENERO LA KEY para DES
SecretKey key = keygen.generateKey(); //GENERO LA KEY
Cipher desCipher = Cipher.getInstance("DES"); //ACTIVO CIFRADOR AES
desCipher.init(Cipher.ENCRYPT_MODE, key); //METO LA KEY EN EL CIFRADOR
byte[] mensajeCifrado = desCipher.doFinal(texto.getBytes()); //LO CIFRO
System.out.println("El mensaje cifrado es: " + new String(mensajeCifrado));
Funciones.EscribirFichero(fich, mensajeCifrado, true);
System.out.println("Fichero editado");
// DESCIFRADOR
desCipher.init(Cipher.DECRYPT_MODE, key);
byte[] descifrar = desCipher.doFinal(mensajeCifrado);
BufferedReader br = new BufferedReader(new FileReader(fich));
while ((string = br.readLine()) != null)
System.out.println("Texto descifrado: " + string);
}
}
}
I hope this helps you, I also had to do this exercise, I understand you. he left you commented. I may be late than never