// CS 1501 Summer 2006 // Handout to help you with your Digital Signature Assignment import java.math.*; import java.util.*; import java.io.*; public class ByteBigByte { public static void main (String [] args) throws Exception { byte [] orig1 = new byte[256]; byte [] orig2 = new byte[256]; for (int i = 0; i < orig1.length; i++) { orig1[i] = (byte) (i); // this will have a leading 0 byte orig2[i] = (byte) (255-i); // this have a leading negative byte } // Since byte values are signed in Java, values > 127 will have a leading // 1, and will be interpreted as negative values. This may look odd but, // as shown below, it should not cause any problems with your encryption // and decryption (since the overall number is used, not the individual // bytes. However, since we need our BigInteger to be non-negative, we // use the constructor shown below, which uses a "sign magnitude" // system -- the 1 indicates the sign will be positive, and the byte // array is used for the magnitude. System.out.println("Orig1. array: "); for (int i = 0; i < orig1.length; i++) System.out.print(orig1[i] + " "); System.out.println(); System.out.println("Orig2. array: "); for (int i = 0; i < orig2.length; i++) System.out.print(orig2[i] + " "); System.out.println(); BigInteger orig1Int = new BigInteger(1, orig1); BigInteger orig2Int = new BigInteger(1, orig2); System.out.println("First BigInt: " + orig1Int); System.out.println("Second BigInt: " + orig2Int); // When BigIntegers are created from byte arrays, any unnecessary // leading 0 bits are removed. Thus, if your original byte array had // a leading byte of all 0s that byte will be removed and will not // appear when the BigInteger is converted back to a byte array. This // can be handled by testing as shown below. // On the other hand, if an extra 0 bit was added to make the value // positive (the leading bit of the leftmost byte in the array was a 1), // when converted back to a byte array, an extra byte will be allocated // for that leading 0. In this case, you want index values 1-128 in the array, // rather than the normal 0-127. Make sure you handle this situation correctly, // as indicated below (in my code below, I KNOW what is in the arrays, but // you will need to test in your code) byte [] copy1 = orig1Int.toByteArray(); byte [] copy2 = orig2Int.toByteArray(); int copy1len = copy1.length; int copy2len = copy2.length; System.out.println("De-integerized array 1"); System.out.print("" + 0 + " "); // Indicate the 0 byte for (int i = 0; i < copy1.length; i++) // Print the array { System.out.print(copy1[i] + " "); } System.out.println(); System.out.println("De-integerized array 2"); for (int i = 1; i < copy2.length; i++) { System.out.print(copy2[i] + " "); } System.out.println(); } }