将一个字符串编码成一个大整数,然后再解码回字符串

5
我找到了一个几乎解决我的问题的答案:https://dev59.com/21bTa4cB1Zd3GeqP-F0z#5717191 这个答案演示了如何使用Base64编码将BigInteger编码为字符串,然后再将其解码回BigInteger,它使用了Apache commons-codec。
是否有一种将字符串编码为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

(The output is just an example and hello world doesn't have to decode to that BigInteger)
编辑:
更具体地说:
我正在编写RSA算法,需要将消息转换为BigInteger,以便我可以使用公钥加密消息(发送消息),然后使用私钥解密消息,然后将数字转换回字符串。
我希望有一种转换方法可以产生最小的BigInteger,因为我原计划使用二进制,直到意识到该数字会有多么巨大。

5
有没有一种将字符串编码为BigInteger,然后再返回字符串的方法/技术?:是的。 - Hovercraft Full Of Eels
1
我的意思是有无数种方法可以做到这一点,例如,您可以将字符串转换为其ASCII字节,然后再转换回来,或者通过许多其他更简单或更复杂的编码技术。您能具体说明一下吗? - Hovercraft Full Of Eels
1
你需要一个双射编码函数。 - m0skit0
我已经编辑了我的问题来解释它的目的,希望这可以帮助。 - Jake Graham Arnold
1
String.getBytes() 有什么问题吗?大多数加密实现接受字节数组而不是 BigIntegers,我认为。 - DNA
显示剩余3条评论
1个回答

13

我不明白为什么你要使用复杂的方法,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所说的那样直接使用字节呢?


Cipher_Text = bigInt.pow(Public_Key) % Modulus - Jake Graham Arnold
1
@RichardCypher 使用 bigInt.modPow(Public_Key,Modulus) 来保持中间的 BigInteger 适度小。 - Daniel Fischer
@YanickRochon 这个是否保证是唯一的?两个字符串能否被编码为相同的 BigInteger。我的直觉告诉我不行,但想确认一下。 - smk
1
@smk 当然!每个字符串都将是唯一的,因为 BigInteger 获取原始字节并简单地执行“二进制到十进制”的转换。如果您认为两个不同字符串的 BigInteger 可以具有相同的值,则在宇宙中的某个地方,有人忘记测试两个不同数字值的相等性 :) 此外,请不要混淆编码与加密 - Yanick Rochon
1
使用更大的基数可以获得更短的编码字符串。String str = "some cool test string with special characters!?%$%(*$^$";String encoded = new BigInteger(str.getBytes()).toString(22)和String decoded = new String (new BigInteger(encoded, 22).toByteArray())基数可以是2到36之间的任何值。 - user2683474
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接