Java tutorial
//package com.java2s; import java.math.BigInteger; import java.security.InvalidKeyException; public class Main { /** * @param bi non-negative * @return array of exactly len bytes */ public static byte[] rectify(BigInteger bi, int len) throws InvalidKeyException { byte[] b = bi.toByteArray(); if (b.length == len) { // just right return b; } if (b.length > len + 1) throw new InvalidKeyException("key too big (" + b.length + ") max is " + (len + 1)); byte[] rv = new byte[len]; if (b.length == 0) return rv; if ((b[0] & 0x80) != 0) throw new InvalidKeyException("negative"); if (b.length > len) { // leading 0 byte if (b[0] != 0) throw new InvalidKeyException("key too big (" + b.length + ") max is " + len); System.arraycopy(b, 1, rv, 0, len); } else { // smaller System.arraycopy(b, 0, rv, len - b.length, b.length); } return rv; } }