Problem trying to encrypt and decrypt using RSA

1

Hello, I'm doing a program that encrypts a user-generated file and then decrypts the encrypted file showing the original message. It's like the RSA implementation code of Bouncing Castle but saving the files.

I'm just not able to pass encrypted data from the user-generated file. It is empty.

package br.com.rsa;

import java.security.*;
import java.io.*;
import java.util.*;
import javax.crypto.*;

public class Geracao {



    public static void main(String[] args) throws IOException {

        //Gerando um arquivo que será encriptado e descriptografado.
        Scanner entrada1 = new Scanner(System.in);

        System.out.println("Digite qualquer coisa: ");
        String entrada = entrada1.nextLine();

        System.out.println("Arquivo criado.");

        FileOutputStream saida = new FileOutputStream("arquivo.txt");
        PrintStream imprimir = new PrintStream(saida);
        System.setOut(imprimir);
        System.out.println(entrada);
        saida.close();

        //Gerando as chaves publica e privada.
        try {       
        KeyPairGenerator chave = KeyPairGenerator.getInstance("RSA");
        chave.initialize(1024);

        KeyPair chaves = chave.generateKeyPair();

        PrivateKey privada = chaves.getPrivate();
        PublicKey publica = chaves.getPublic();

        Base64.Encoder cripto = Base64.getEncoder();

        System.out.println("Chave privada: " + cripto.encodeToString(privada.getEncoded()));
        System.out.println("");
        System.out.println("Chave publica: " + cripto.encodeToString(publica.getEncoded()));
        System.out.println("");


            //Salvando as chaves publica e privada.
            try (FileOutputStream s_prv = new FileOutputStream("privada" + ".key")){

                s_prv.write(chaves.getPrivate().getEncoded());

            }

            try (FileOutputStream s_pub = new FileOutputStream("publica" + ".key")){

                s_pub.write(chaves.getPublic().getEncoded());
            }

            Criptografar(chaves, null);
            //Descriptografar(chaves, null);
        }

        //Qualquer erro dentro da geração das chaves
        catch (Exception e){

            System.out.println(e);
        }
    }

    //TODO - Comentario
     static private void processFile(Cipher cifra, InputStream entrada_arq_c, OutputStream saida_arq_c){
           try {
            byte[] ibuf = new byte[1024];
            int len;
            while ((len = entrada_arq_c.read(ibuf)) != -1) {
                byte[] obuf = cifra.update(ibuf, 0, len);
                if ( obuf != null ) saida_arq_c.write(obuf);
            }
            byte[] obuf = cifra.doFinal();
            if ( obuf != null ) saida_arq_c.write(obuf);
           }
          catch(Exception e) {

              System.out.println("Problema no manuseio do arquivo.");
          }
    }

    //Metodo para criptografar.
     static private void Criptografar(KeyPair chaves, Cipher ci){
        try {
            PublicKey publica = chaves.getPublic();
            Cipher cifra = Cipher.getInstance("RSA");
            cifra.init(Cipher.ENCRYPT_MODE, publica);

            FileInputStream entrada_arq_c = new FileInputStream("arquivo.txt");
            FileOutputStream saida_arq_c = new FileOutputStream("criptografado.txt");
            processFile(ci, entrada_arq_c, saida_arq_c);

        }
        catch(Exception e){

            System.out.println("Erro ao criptografar.");
        }
    }

    //Metodo para descriptografar.
     static private void Descriptografar(KeyPair chaves, Cipher ci){

        try {
            PrivateKey privada = chaves.getPrivate();
            Cipher cifra = Cipher.getInstance("RSA");
            cifra.init(Cipher.DECRYPT_MODE, privada);

            FileInputStream entrada_arq_c = new FileInputStream("criptografado.txt");
            FileOutputStream saida_arq_c = new FileOutputStream("descriptografado.txt");
            processFile(ci, entrada_arq_c, saida_arq_c);
        }
        catch(Exception e){

            System.out.println("Erro ao descriptografar.");
        }
    }
}
    
asked by anonymous 11.11.2018 / 23:05

1 answer

1

I got a response to the problem. I asked the same question in the English part of the site and I just needed to replace this

processFile(cifra, entrada_arq_c, saida_arq_c);

It was necessary to replace ci with cipher . An extra line was also added in the Exception of the processfile method.

And finally, an extra line was added where the file was saved, adding

PrintStream defaultOutStream = System.out;
System.setOut(defaultOutStream);

In order for the user to finish saving the file, it will resume after the exit.close (); call to print on the screen.

For those who want to see a more detailed version of the solution, I'll post the link.

a>

    
12.11.2018 / 19:20