Error decrypting (RSA) Java

1

I have a program that encrypts and decrypts, but decrypting gives me the error BadPaddingException: Decryption error. There are two methods that encrypt and decrypt the end of the code, the error it gives me when decrypting, in the line String messageDescifrado = new String (cipher.doFinal (Base64.getDecoder (). Decode (text)), "UTF- 8 ");

This is my code (I have omitted unnecessary code). Thanks.

public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {        
    // Generamos el keygen
    System.out.println("Obteniendo generador de claves con cifrado RSA");
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    // Generamos el par de claves
    System.out.println("Generando par de claves");
    // Generamos el cipher.
    KeyPair parejaClaves = keygen.generateKeyPair();
    System.out.println("Obteniendo objeto Cipher con cifrado RSA");
    Cipher rsaCipher = Cipher.getInstance("RSA");                  
}

/**
 * Función que cifra.
 * Recibe el texto leído del fichero y lo devuelve cifrado.
 */
public static String CifrarFichero(String texto, Cipher cipher, KeyPair claves) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException{
    System.out.println("Configurando Cipher");
    cipher.init(Cipher.ENCRYPT_MODE, claves.getPrivate());
    System.out.println("Cifrando mensaje");
    // Ciframos el mensaje.
    String mensajeCifrado = Base64.getEncoder().encodeToString(cipher.doFinal(texto.getBytes("UTF-8")));
    System.out.println("Cifrado");
    // Devolvemos el mensaje.
    return mensajeCifrado;
}

/**
 * Función que descifra 
 */
public static String DescifrarFichero(String texto, Cipher cipher, KeyPair claves) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException{        
    System.out.println("Configurando Cipher");
    cipher.init(Cipher.DECRYPT_MODE, claves.getPublic());
    // Desciframos el mensaje.
    System.out.println("Descifrando mensaje");
    String mensajeDescifrado = new String(cipher.doFinal(Base64.getDecoder().decode(texto)), "UTF-8");
    // Devolvemos el mensaje descifrado.
    return mensajeDescifrado;
}

}

    
asked by PacoPepe 02.03.2018 в 21:09
source

0 answers