Problem when trying to encrypt and decrypt using RSA

Asked

Viewed 273 times

1

Hello, I’m making a program that encrypts a user-generated file and then decrypts the encrypted file showing the original message. Nor the RSA implementation code of Bouncing Castle but saving the files.

Except that I am not able to pass the encrypted data of 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.");
        }
    }
}
  • Which part of the algorithm is working correctly and which part is not ? Shows some error ? If yes which ?

  • The only problem is that when I call the encryption method, it even creates the file only it is empty.

  • You’re shutting down the streams (close()) after who wrote? In doubt makes a flush() also.

  • @Piovezan I got an answer!

1 answer

1


I got an answer to the problem. I asked the same question in the English part of the site and needed only to replace it

processFile(cifra, entrada_arq_c, saida_arq_c);

It was necessary to replace the ci for cipher. An additional line was also added in the method Exception processfile.

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

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

So that as soon as you finish saving the user file, it resume after the call from exit.(); to print on screen.

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

https://stackoverflow.com/questions/53254880/problem-with-encrypting-and-decrypting-using-rsa-on-java?answertab=active#tab-top

Browser other questions tagged

You are not signed in. Login or sign up in order to post.