B
B
barabash20902021-08-31 21:03:25
Java
barabash2090, 2021-08-31 21:03:25

How to decrypt ciphertext via KeyPairGenerator?

Good afternoon! Using the KeyPairGenerator technology, I encrypted the text. After it, you need to decipher with what difficulties arose.

public class Main {
    public static void main(String[] args) throws Exception {
        String text = "Lyubotin";

        System.out.println(text);


        byte[] encrypt = new Encrypt().processingOfEcryption(text);
        System.out.println(encrypt);

        String encryptString = new String(encrypt, "UTF8");
        System.out.println(encryptString);

        String deciphered = new Decrypt().processingOfDecryption(encrypt);
        System.out.println(deciphered);

        boolean cryptoData = encryptString.equals(deciphered) ? true : false;
        System.out.println("Совпадает ли? " + cryptoData);
    }
}

public class Encrypt {
    public byte[] processingOfEcryption(String text) throws Exception{
        Signature sign = Signature.getInstance("SHA256withRSA");
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(2048);
        KeyPair pair = keyPairGen.generateKeyPair();
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());
        byte[] input = text.getBytes();
        cipher.update(input);

        byte[] cipherText = cipher.doFinal();

        return cipherText;
    }
}

public class Decrypt {
    public String processingOfDecryption(byte[] text) throws Exception {
        Signature sign = Signature.getInstance("SHA256withRSA");
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(2048);
        KeyPair pair = keyPairGen.generateKeyPair();
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
        byte[] decipheredText = cipher.doFinal(text);

        return new String(decipheredText, "UTF8");
    }
}


The error occurs in the processingOfDecryption function in the Decrypt class, in the line byte[] decipheredText = cipher.doFinal(text);

Exception in thread "main" javax.crypto.BadPaddingException: Decryption error

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Roo, 2021-08-31
@barabash2090

The problem is that you, in order to encrypt and decrypt your string, use different keys, which you re-generate each time in the Encrypt / Decrypt classes.

D
Developer, 2021-08-31
@samodum

You use different keys

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question