将String编码为BigInteger,然后解码回String

时间:2012-02-29 15:05:03

标签: java encoding base64

我找到了几乎解决了我的问题的答案: https://stackoverflow.com/a/5717191/1065546

这个答案演示了如何使用使用Apache commons-codec的Base64编码将BigInteger编码为String然后再编译回BigInteger。

有没有一种方法可以将String的技术/方法编码为BigInteger然后再返回String? 若有人请说明如何使用它?

      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的转换方法,因为我计划使用二进制文件,直到我意识到这个数字是多么荒谬。

1 个答案:

答案 0 :(得分:9)

我不明白你为什么想要复杂的方法,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说的那样?