Answer the question
In order to leave comments, you need to log in
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");
}
}
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question