Frengerdany 0 Newbie Poster

Hi I have a problem with RSA encryption/decription of txt files,
I have one method to create a pair of RSA keys and save them into a file, then i made two methods, one for encryt and one for decrypt, encrypt method works fine, but when I want to decrypt it shows this exception javax.crypto.BadPaddingException: Data must start with zero, any help would be very apreciated.

Heres the code for create the RSA keypair into a file:

public void generateKeys() throws NoSuchAlgorithmException,    NoSuchProviderException, FileNotFoundException, IOException{
        
        int keysize = 1024;
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keyGen.initialize(keysize, random);
        KeyPair pair = keyGen.generateKeyPair();

        RSAPublicKey pub = (RSAPublicKey) pair.getPublic();
        
        RSAPrivateKey priv = (RSAPrivateKey) pair.getPrivate();

        //Saving public key into a file
        byte[] llavepub = pub.getEncoded();
        FileOutputStream fospub = new FileOutputStream("publickey");
        fospub.write(llavepub);
        fospub.close();

        //Saving private key into a file
        byte[] llavepriv = priv.getEncoded();
        FileOutputStream fospriv = new FileOutputStream("privatekey");
        fospriv.write(llavepriv);
        fospriv.close();
    }

Then the code for Encript a txt file with the previously generated private key:

public void encryptFile(String llaveprivada) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException, NoSuchProviderException{

        BASE64Encoder base64Encoder = new BASE64Encoder();

        //loading the private key to encrypt the txt file
        FileInputStream fispriv = new FileInputStream(llaveprivada);
        byte[] llavepriv = new byte[fispriv.available()];
        fispriv.read(llavepriv);
        fispriv.close();

        //decoding the data of the private key
        PKCS8EncodedKeySpec pkspriv = new PKCS8EncodedKeySpec(llavepriv);
        KeyFactory kfpriv = KeyFactory.getInstance("RSA");
        RSAPrivateKey priv = (RSAPrivateKey)kfpriv.generatePrivate(pkspriv);

        //Creating cipher instance
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        
        //opening the txt file with the plain text
        File archivo = new File("plano.txt");
        FileReader fr = new FileReader(archivo);
        BufferedReader br = new BufferedReader(fr);
        
        //Creating the txt file for the encrypted text
        FileWriter fw = new FileWriter("cifrado.txt");
        PrintWriter pw = new PrintWriter(fw);
        
        //initializing cipher for encrypt
        rsaCipher.init(Cipher.ENCRYPT_MODE, priv);
        
        //reading plain txt file line by line
        String plaintext;
        while((plaintext = br.readLine())!=null){
            
            byte[] cleartext = plaintext.getBytes();
            //encrypt text
            byte[] ciphertext = rsaCipher.doFinal(cleartext);
            //print encrypted text into a file
            pw.println(base64Encoder.encode(ciphertext));
        }
        pw.close();
    }

Everything works fine until this method, decrypt txt file:

public void decryptFile(String llavepublica) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException{

        BASE64Decoder base64Decoder = new BASE64Decoder();

        //loading public key to decrypt txt file
        FileInputStream fispub = new FileInputStream(llavepublica);
        byte[] llavepub = new byte[fispub.available()];
        fispub.read(llavepub);
        fispub.close();

        //decoding the data of public key
        X509EncodedKeySpec pkspub = new X509EncodedKeySpec(llavepub);
        KeyFactory kfpub = KeyFactory.getInstance("RSA");
        RSAPublicKey pub = (RSAPublicKey)kfpub.generatePublic(pkspub);

        //Creting cipher instance
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        
        //open txt file with the ciphertext
        File archivo = new File ("cifrado.txt");
        FileReader fr = new FileReader (archivo);
        BufferedReader br = new BufferedReader(fr);

        //creating the txt file for the decrypted text
        FileWriter fichero = new FileWriter("descifrado.txt");
        PrintWriter pw = new PrintWriter(fichero);

        //Initializing cipher for decrypt
        rsaCipher.init(Cipher.DECRYPT_MODE, pub);
        
        //reading txt file line by line
        String ciphertext;
        while((ciphertext = br.readLine())!=null){
            
            byte[] cipherbytes = ciphertext.getBytes();
            //decrypt ciphertext
            byte[] cleartext = rsaCipher.doFinal(cipherbytes);
            //print decrypted text into a file
            pw.println(base64Decoder.decodeBuffer(new String(cleartext)));
            }
        pw.close();
    }

It doesnt show me any syntax errors, only that exception is the problem, I hope that somebody can help me with this, thanks in advance.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.