【问题标题】:Encode a String into a BigInteger then decode back to String将字符串编码为 BigInteger,然后解码回字符串
【发布时间】:2012-02-29 15:05:02
【问题描述】:

我找到了一个几乎可以解决我的问题的答案: 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 的转换方法,因为我正计划使用二进制,直到我意识到这个数字会有多大。

【问题讨论】:

  • Is there a way of encoding technique/method for a String to a BigInteger then back to a String?: 是的。
  • 谢谢,你能告诉我怎么做吗?
  • 我的意思是有 aleph-null 方法可以做到这一点,例如,您可以将字符串转换为其 ascii 字节,然后再转换回来,或者通过许多其他更简单或更复杂的编码技术。你能稍微更具体一点吗?
  • 你需要一个双射编码函数。
  • String.getBytes() 有什么问题?我认为大多数加密实现都接受字节数组而不是 BigIntegers

标签: java encoding base64


【解决方案1】:

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

【讨论】:

  • 谢谢,我才刚刚开始使用 BigIntegers 我没有意识到你可以这样做 我的函数的下一步是: bigInt.pow(Public_Key) % Modulus
  • 好的。请注意,您可以通过提供不同的基数来获得更小的BigInteger 输出。例如,bigInt.toString(16)。仅供参考
  • @RichardCypher 使用bigInt.modPow(Public_Key,Modulus) 保持中间BigIntegers 适度小。
  • @smk 当然!每个字符串都是唯一的,因为BigInteger 采用原始字节并简单地进行“二进制到base10”转换。如果您认为两个BigIntegers 可以对两个不同的字符串具有相同的值,那么在宇宙的某个地方,有人忘记测试两个不同的数值是否相等:) 另外,不要混淆encoding with encryption
  • 使用更大的基数可以得到更短的编码字符串。 String str = "一些很酷的带有特殊字符的测试字符串!?%$%(*$^$"; String encoded = new BigInteger(str.getBytes()).toString(22) 和 String decoded = new String (new BigInteger(编码,22).toByteArray()) radix 可以是 2 到 36 之间的任何值。
猜你喜欢
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 2012-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多