Converting Byte Sequences to Positive Integers

This section describes java.math.BigInteger methods that can be used to convert byte sequences into positive integers and convert back to byte sequences for RSA encryption and decryption operations.

From the previous tutorial, we learned that RSA keys generated from RsaKeyGenerator.java is working. Now we need to think about how to encrypt a byte sequences. We know this can be done by converting the byte sequence to positive integers, then applying the RSA encryption operation on the converted integers.

So we need to learn how to convert a byte sequence into a positive integer for the encryption purpose.

Similarly, we also need to learn how to convert a positive integer into a byte sequence after applying the RSA decryption operation to recover the original byte sequence.

For converting byte sequences into integers, the java.math.BigInteger class has offered 3 methods based the Java documentation:

• public BigInteger(byte[] val) - Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.
• public BigInteger(int signum, byte[] magnitude) - Translates the sign-magnitude representation of a BigInteger into a BigInteger. The sign is represented as an integer signum value: -1 for negative, 0 for zero, or 1 for positive. The magnitude is a byte array in big-endian byte-order: the most significant byte is in the zeroth element.
• public byte[] toByteArray() - Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)).

Obviously, the best choice of converting a byte sequence into a positive integer is to use the BigInteger(int signum, byte[] magnitude) constructor as: "new BigInteger(1,byteArray)". This avoids getting negative numbers when the first bit of the byte sequence is a negative sign.

For converting a positive integer back to a byte sequence, we have to use toByteArray(). There are no other choices. But you may get an extra byte in the resulting byte sequence because of the extra sign bit added in the result. For example, the follow Java code will show that "barSignConverted" has 3 bytes, not 2 types.

```byte[] barSign = {(byte)0xfe,(byte)0x31}; // 2 bytes of a Unicode text
BigInteger value = new BigInteger(1,barSign);  // 65073
byte[] barSignConverted = value.toByteArray();
System.out.println("Length: "+barSignConverted.length);
```

However, we can safely drop the first byte, if an extra byte is added for the sign bit, because it will contain the sign bit only, and we don't need the sign anyway.

Last update: 2013.