public static byte[] encodeMPI(BigInteger value,boolean includeLength){
  if (value.equals(BigInteger.ZERO)) {
    if (!includeLength)     return new byte[]{};
 else     return new byte[]{0x00,0x00,0x00,0x00};
  }
  boolean isNegative=value.signum() < 0;
  if (isNegative)   value=value.negate();
  byte[] array=value.toByteArray();
  int length=array.length;
  if ((array[0] & 0x80) == 0x80)   length++;
  if (includeLength) {
    byte[] result=new byte[length + 4];
    System.arraycopy(array,0,result,length - array.length + 3,array.length);
    uint32ToByteArrayBE(length,result,0);
    if (isNegative)     result[4]|=0x80;
    return result;
  }
 else {
    byte[] result;
    if (length != array.length) {
      result=new byte[length];
      System.arraycopy(array,0,result,1,array.length);
    }
 else     result=array;
    if (isNegative)     result[0]|=0x80;
    return result;
  }
}

public static byte [ ] encodeMPI ( BigInteger value , boolean includeLength ) { if ( value . equals ( BigInteger . ZERO ) ) { if ( ! includeLength ) return new byte [ ] { } ; else return new byte [ ] { 0x00 , 0x00 , 0x00 , 0x00 } ; } boolean isNegative = value . signum ( ) < 0 ; if ( isNegative ) value = value . negate ( ) ; byte [ ] array = value . toByteArray ( ) ; int length = array . length ; if ( ( array [ 0 ] & 0x80 ) == 0x80 ) length ++ ; if ( includeLength ) { byte [ ] result = new byte [ length + 4 ] ; System . arraycopy ( array , 0 , result , length - array . length + 3 , array . length ) ; uint32ToByteArrayBE ( length , result , 0 ) ; if ( isNegative ) result [ 4 ] |= 0x80 ; return result ; } else { byte [ ] result ; if ( length != array . length ) { result = new byte [ length ] ; System . arraycopy ( array , 0 , result , 1 , array . length ) ; } else result = array ; if ( isNegative ) result [ 0 ] |= 0x80 ; return result ; } }
mpi encoded numbers are produced by the openssl bn_bn2mpi function . they consist of a 4 byte big endian length field , followed by the stated number of bytes representing the number in big endian format ( with a sign bit ) .
