Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode a String into a BigInteger then decode back to String

I found an answer that almost solves my problem: https://stackoverflow.com/a/5717191/1065546

This answer demonstrates how to encode a BigInteger into a String then back into a BigInteger using Base64 encodings which uses Apache commons-codec.

Is there a way of encoding technique/method for a String to a BigInteger then back to a String? if so would someone please explain how to use it?

      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);

Print:

      hello world
      830750578058989483904581244
      hello world

(The output is just an example and hello world doesn't have to decode to that BigInteger)

EDIT

More specific:

I am writing a RSA algorithm and I need to convert a message into a BigInteger so that I can then encrypt the message with the public key (send message) and then decrypt the message with the private key and then convert the number back into a String.

I would like a method of conversion that could produce the smallest BigInteger as I was planning on using binary until I realised how ridiculouslybig the number would be.

like image 640
Jake Graham Arnold Avatar asked Feb 29 '12 15:02

Jake Graham Arnold


People also ask

How do you increment a BigInteger?

You can have it like this. for(BigInteger a = BigInteger. ONE; a. compareTo(someBigInteger); a=a.

What is the difference between BigInteger and integer?

The int data type is the primary integer data type in SQL Server. The bigint data type is intended for use when integer values might exceed the range that is supported by the int data type. bigint fits between smallmoney and int in the data type precedence chart.


1 Answers

I don't understand why you want to go through complicated methods, BigInteger already is compatible with 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);

** Edit **

But why do you need BigInteger while you can work directly with the bytes, like DNA said?

like image 127
Yanick Rochon Avatar answered Oct 06 '22 20:10

Yanick Rochon