如何使用 BigInteger 加密字符串?

How do you encrypt a string with BigInteger?

我正在尝试获取一个字母数字字符串并使用大整数对其进行加密。当我使用十进制值(例如 10)初始化 BigInteger 时,我的加密和解密工作。但是,当我使用字符串初始化 BigInteger 时,解密不会 return 原始 BigInteger。 这是我用来生成密钥和 encrypt/decrypt.

的代码
public static void main(String args[]) {
    int keySize = 32;

    BigInteger prime1 = new BigInteger(keySize / 2, 100, new SecureRandom());
    BigInteger prime2 = new BigInteger(keySize / 2, 100, new SecureRandom());

    BigInteger n = prime1.multiply(prime2); 
    BigInteger totient = prime1.subtract(BigInteger.ONE).multiply(prime2.subtract(BigInteger.ONE));

    //create the private key
    BigInteger e;
    do e = new BigInteger(totient.bitLength(), new SecureRandom());
    while (e.compareTo(BigInteger.ONE) <= 0 || e.compareTo(totient) >= 0 || !e.gcd(totient).equals(BigInteger.ONE));

    //create public key
    BigInteger d = e.modInverse(totient);


    String original = "Hello World!";

    BigInteger enc = new BigInteger(original.getBytes());
    System.out.println("Original: " + enc.toString());

    //encrypt
    enc = enc.modPow(e, n);

    //decrypt
    BigInteger dec = enc;
    dec = dec.modPow(d, n);
    System.out.println("Result: " + dec.toString());
}

正如我所说,如果我将 enc 初始化为一个整数值,比如 10,我的结果将是...

Original: 10
Result: 10

然而,当我初始化为一个字符串时,如上面的代码,我的结果是这样的...

Original: 22405534230753928650781647905
Result: 1828948854

我是否实施了错误的加密,或者在将字符串转换为 BigInteger 进行加密时我是否遗漏了什么?

Did I implement my encryption wrong

是的。

看起来您正在使用 32 位 keySize 实现 RSA。这也将消息的大小限制为 32 位;您要加密的邮件比这大得多。