public static byte [ ] integerToBytes ( BigInteger s , int length ) { byte [ ] bytes = s . toByteArray ( ) ; if ( length < bytes . length ) { // The length is smaller than the byte representation. Truncate by // copying over the least significant bytes byte [ ] tmp = new byte [ length ] ; System . arraycopy ( bytes , bytes . length - tmp . length , tmp , 0 , tmp . length ) ; return tmp ; } else if ( length > bytes . length ) { // The length is larger than the byte representation. Copy over all // bytes and leave it prefixed by zeros. byte [ ] tmp = new byte [ length ] ; System . arraycopy ( bytes , 0 , tmp , tmp . length - bytes . length , bytes . length ) ; return tmp ; } return bytes ; }
Get a big integer as an array of bytes of a specified length