我正在尝试使用我自己的 Java RSA 实现来加密和解密一个字符串,并最终加密和解密一个包含明文的文件。我尝试过在SO和网络上遵循无数的例子,人们使用内置的Java RSA函数或他们自己的算法实现,但无法让它们中的任何一个工作,因为解密的文本永远不会与原始字符串匹配。
我不知道我在文本编码/解码方面是否做错了什么,已尝试在 java.xml.*
中使用默认的 UTF-8 和 Base64 编码器,但也没有运气。我没有使用任何填充,我不知道这对于它的工作是否有必要,而且我只是使用任意 key 长度,我尝试改变它的大小,并且也不能让事情工作。这只是我自己的一个练习,没有人的信息会受到此或任何东西的保护。但我不确定问题是什么,所以这是我的代码,它尝试加密/解密一个简单的字符串:
BigInteger ONE = new BigInteger("1");
SecureRandom rand = new SecureRandom();
BigInteger d;
BigInteger e;
BigInteger n;
BigInteger p = BigInteger.probablePrime(10, rand); // 10 is arbitrary, have tried different numbers
BigInteger q = BigInteger.probablePrime(10, rand);
BigInteger phi = (p.subtract(ONE)).multiply(q.subtract(ONE));
n = p.multiply(q); //10 bits * 10 bits = ??? bits for key length
e = new BigInteger("65537"); //public key exponent
d = e.modInverse(phi); //private key exponent
String string = "this is a test";
byte[] bytes = string.getBytes();
BigInteger plainText = new BigInteger(bytes);
BigInteger cipherText = plainText.modPow(e, n);
BigInteger originalMessage = cipherText.modPow(d, e);
System.out.println(string.getBytes());
System.out.println(cipherText);
System.out.println(originalMessage);
每次我运行程序时,所有三件事的输出都有不同的值: 但它们总是具有相同的相对形式:
[B@52d85409
157529
24312
最佳答案
几点说明:
- 您的模数(示例中的
n
)需要至少与您要加密的信息量一样长。这是 RSA 的注意事项之一,这就是为什么 AES 之类的东西更适合文件等较长的流。下面我选择了128
作为p
和q
的范围,而不是10
,其他值也可以工作. - 它是
cipherText.modPow(d, n)
- 您必须将 BigInteger 转换回字符串才能正确打印它,因此:
new String(originalMessage.toByteArray())
把它们放在一起:
BigInteger ONE = new BigInteger("1");
SecureRandom rand = new SecureRandom();
BigInteger d, e, n;
BigInteger p = BigInteger.probablePrime(128, rand);
BigInteger q = BigInteger.probablePrime(128, rand);
BigInteger phi = (p.subtract(ONE)).multiply(q.subtract(ONE));
n = p.multiply(q);
e = new BigInteger("65537");
d = e.modInverse(phi);
String string = "this is a test";
BigInteger plainText = new BigInteger(string.getBytes());
BigInteger cipherText = plainText.modPow(e, n);
BigInteger originalMessage = cipherText.modPow(d, n);
String decrypted = new String(originalMessage.toByteArray());
System.out.println("original: " + string);
System.out.println("decrypted: " + decrypted);
关于java - 使用自己的 RSA 实现加密纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594387/