Шифрование сообщений в Java. Ошибка дешифровки
Не мой код конечно, но помогите исправить ошибки. Как видно, с шифрованием справилась программа успешно. А дешифрование началось с ошибок.
Person.java:
package com.company;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class Person {
private PrivateKey privateKey;
public PublicKey publicKey;
private final Map<String, PublicKey> contacts = new HashMap<>();
public Person() {
generateKeyPair();
}
private void generateKeyPair() {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
privateKey = pair.getPrivate();
publicKey = pair.getPublic();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public void addFriend(String name, PublicKey publicKey) {
contacts.put(name, publicKey);
}
public String sendMessage(String recipient, String message) {
PublicKey publicKey = contacts.get(recipient);
if (publicKey == null)
throw new RuntimeException("unknown recipient");
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] msgBytes = message.getBytes(StandardCharsets.UTF_8);
byte[] encrypted = cipher.doFinal(msgBytes);
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public String receiveMessage(String cipherText) {
byte[] encrypted = Base64.getDecoder().decode(cipherText);
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
App.java:
package com.company;
public class App {
public static void main( String[] args) {
Person mrSergey = new Person();
Person mrIvan = new Person();
mrIvan.addFriend("Сергей", mrSergey.publicKey);
String encryptedMessage = mrIvan.sendMessage("[email protected]", "Hello world");
System.out.println("Encrypted message: " + encryptedMessage);
String decryptedMessage = mrSergey.receiveMessage(encryptedMessage);
System.out.println("Decrypted message: " + decryptedMessage);
}
}
Ответы (1 шт):
Автор решения: Vadik
→ Ссылка
Чтобы Ивану зашифровать сообщение для Сергея, недостаточно знать его имя или email, нужен публичный ключ Сергея. Добавьте в метод addFriend() второй аргумент publicKey:
public void addFriend(String name, PublicKey publicKey) {
contacts.put(name, publicKey);
}
И сделайте проперти publicKey публичным у класса Person:
public PublicKey publicKey;
Тогда добавить друга можно будет так:
Person sergey = new Person();
Person ivan = new Person();
ivan.addFriend("Сергей", sergey.publicKey);
