我找到了一个几乎可以解决我的问题的答案: https://stackoverflow.com/a/5717191/1065546
这个答案演示了如何使用使用 Apache commons-codec 的 Base64 编码将 BigInteger 编码为 String,然后再编码回 BigInteger。
是否有一种将字符串编码为 BigInteger 然后返回字符串的技术/方法? 如果是这样,有人可以解释一下如何使用它吗?
String s = "hello world";
System.out.println(s);
BigInteger encoded = new BigInteger( SOME ENCODING.(s));
System.out.println(encoded);
String decoded = new String(SOME DECODING.(encoded));
System.out.println(decoded);
打印:
hello world
830750578058989483904581244
hello world
(输出只是一个示例,hello world 不必解码为 BigInteger)
编辑
更具体:
我正在编写一个 RSA 算法,我需要将消息转换为 BigInteger,以便我可以使用公钥加密消息(发送消息),然后使用私钥解密消息,然后将数字转换回细绳。
我想要一种可以产生最小 BigInteger 的转换方法,因为我计划使用二进制,直到我意识到这个数字会有多大。
我不明白你为什么要经历复杂的方法,
BigInteger
已经与String
兼容:
// test string
String text = "Hello world!";
System.out.println("Test string = " + text);
// convert to big integer
BigInteger bigInt = new BigInteger(text.getBytes());
System.out.println(bigInt.toString());
// convert back
String textBack = new String(bigInt.toByteArray());
System.out.println("And back = " + textBack);
** 编辑 **
但是为什么你需要
BigInteger
,而你可以直接使用字节,就像DNA所说的那样?
按照
https://stackoverflow.com/a/9501964/955091中所述直接将字节传递到
new BigInteger
的方法会意外地丢弃起始 \0
。
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
String text = "\0\0Hello world!";
// Output: Test string = Hello world! (length = 14)
System.out.println("Test string = " + text + " (length = " + text.length() + ")");
// convert to big integer
BigInteger bigInt = new BigInteger(text.getBytes());
System.out.println(bigInt.toString());
// convert back
// Output: And back = Hello world! (length = 12)
String textBack = (new String(bigInt.toByteArray()));
System.out.println("And back = " + textBack + " (length = " + textBack.length() + ")");
}
}
您可以看到
text.length()
和 text.length()
是不同的。
为了保护起始的
\0
,我们可以在前面添加一个魔术头:
import java.math.BigInteger;
public class Main {
private static final String MAGIC = "MAGIC";
public static void main(String[] args) {
String text = "\0\0Hello world!";
System.out.println("Test string = " + text + "(length = " + text.length() + ")");
// convert to big integer
BigInteger bigInt = new BigInteger((MAGIC + text).getBytes());
System.out.println(bigInt.toString());
// convert back
String textBack = (new String(bigInt.toByteArray())).substring(MAGIC.length());
System.out.println("And back = " + textBack + "(length = " + textBack.length() + ")");
}
}