Я пытаюсь принять алгоритм RSA для шифрования объектов String, но кажется, что преобразования BigInteger -> String и String -> BigInteger не работают должным образом. Вот мой код:
public class RSAEncryptor {
private BigInteger n, d, e;
public RSAEncryptor(int bitlen) {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bitlen / 2, 100, r);
BigInteger q = new BigInteger(bitlen / 2, 100, r);
n = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
e = new BigInteger("3");
while (m.gcd(e).intValue() > 1) {
e = e.add(new BigInteger("2"));
}
d = e.modInverse(m);
}
public String encrypt(String message) {
BigInteger plaintext = new BigInteger(message.getBytes());
return new String(plaintext.modPow(e, n).toByteArray());
}
public String decrypt(String message) {
BigInteger plaintext = new BigInteger(message.getBytes());
return new String(plaintext.modPow(d, n).toByteArray());
}
}
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
RSAEncryptor encryptor = new RSAEncryptor(64);
String source = "1";
String crypted = encryptor.encrypt(source);
System.out.println(crypted);
String decrypted = encryptor.decrypt(crypted);
System.out.println(decrypted);
}
}
Он печатает не то, что ожидается, и странно то, что каждый раз, когда вывод отличается. Я делаю что-то неправильно? Спасибо