Example usage for java.math BigInteger toByteArray

List of usage examples for java.math BigInteger toByteArray

Introduction

In this page you can find the example usage for java.math BigInteger toByteArray.

Prototype

public byte[] toByteArray() 

Source Link

Document

Returns a byte array containing the two's-complement representation of this BigInteger.

Usage

From source file:Main.java

/**
 * <p>Treats the input as the MSB representation of a number, and discards
 * leading zero elements. For efficiency, the input is simply returned if no
 * leading zeroes are found.</p>//from  w w w . j ava 2 s.c  om
 *
 * @param n the {@link BigInteger} to trim.
 * @return the byte array representation of the designated {@link BigInteger}
 * with no leading 0-bytes.
 */
public static final byte[] trim(BigInteger n) {
    byte[] in = n.toByteArray();
    if (in.length == 0 || in[0] != 0) {
        return in;
    }
    int len = in.length;
    int i = 1;
    while (in[i] == 0 && i < len) {
        ++i;
    }
    byte[] result = new byte[len - i];
    System.arraycopy(in, i, result, 0, len - i);
    return result;
}

From source file:mitm.common.util.MiscArrayUtils.java

/**
 * Converts the input string which is encoded in MAX_RADIX to a byte array (this function 
 * is the complement of ArrayUtils#toMaxRadix) 
 *///  w  w  w .java2  s  .  co m
public static byte[] fromMaxRadix(String inputMaxRadix) {
    Check.notNull(inputMaxRadix, "inputMaxRadix");

    BigInteger bigInt = new BigInteger(inputMaxRadix, Character.MAX_RADIX);

    byte[] bytes = bigInt.toByteArray();

    /*
     * We need to remove the first byte added by toMaxRadix.
     */
    return ArrayUtils.subarray(bytes, 1, bytes.length);
}

From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java

/**
 * Return the passed in value as an unsigned byte array.
 * //from   w w  w.  j av a  2  s. c o m
 * @param value value to be converted.
 * @return a byte array without a leading zero byte if present in the signed encoding.
 */
public static byte[] asUnsignedByteArray(BigInteger value) {
    byte[] bytes = value.toByteArray();

    if (bytes[0] == 0) {
        byte[] tmp = new byte[bytes.length - 1];

        System.arraycopy(bytes, 1, tmp, 0, tmp.length);

        return tmp;
    }

    return bytes;
}

From source file:it.zero11.acme.utils.JWKUtils.java

private static byte[] toIntegerBytes(final BigInteger bigInt) {
    int bitlen = bigInt.bitLength();
    // round bitlen
    bitlen = ((bitlen + 7) >> 3) << 3;
    final byte[] bigBytes = bigInt.toByteArray();

    if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
        return bigBytes;
    }/*  w w w  .j  a  v  a2 s  .co m*/
    // set up params for copying everything but sign bit
    int startSrc = 0;
    int len = bigBytes.length;

    // if bigInt is exactly byte-aligned, just skip signbit in copy
    if ((bigInt.bitLength() % 8) == 0) {
        startSrc = 1;
        len--;
    }
    final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
    final byte[] resizedBytes = new byte[bitlen / 8];
    System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
    return resizedBytes;
}

From source file:org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKeyHelper.java

public static JsonWebKey fromPEMPrivateKey(String key) {
    KeyPair pair = KeyInfo.parseKeyPair(key);
    RSAPublicKey rsaKey = (RSAPublicKey) pair.getPublic();
    BigInteger modulus = rsaKey.getModulus();
    BigInteger exponent = rsaKey.getPublicExponent();
    Map<String, Object> properties = new HashMap();
    properties.put("n", base64.encodeAsString(modulus.toByteArray()));
    properties.put("e", base64.encodeAsString(exponent.toByteArray()));
    properties.put("kty", "RSA");
    properties.put("use", sig.name());
    properties.put("value", KeyInfo.pemEncodePublicKey(rsaKey));
    return new JsonWebKey(properties);
}

From source file:org.opentravel.schemacompiler.security.GenerateEncryptionKeys.java

/**
 * Saves the content of the given byte array to the indicated file location.
 * //from   ww w .  j av  a 2 s  .  co m
 * @param file
 *            the file to which the byte contents should be written
 * @param modulus
 *            the modulus of the encryption key
 * @param exponent
 *            the exponent of the encryption key
 * @throws IOException
 *             thrown if the file cannot be created
 */
private static void writeKeyFile(File file, BigInteger modulus, BigInteger exponent) throws IOException {
    PrintStream out = null;
    try {
        out = new PrintStream(new FileOutputStream(file));
        out.println(Base64.encodeBase64String(modulus.toByteArray()));
        out.println(Base64.encodeBase64String(exponent.toByteArray()));

    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Throwable t) {
        }
    }
}

From source file:com.swdouglass.joid.Crypto.java

/**
 * Converts a big integer to string./* ww  w  .j  a v a 2  s  . c  om*/
 *
 * @param b the big integer to convert.
 * @return the base 64 encoded string.
 */
public static String convertToString(BigInteger b) {
    return convertToString(b.toByteArray());
}

From source file:org.keycloak.jose.jwk.JWKBuilder.java

/**
 * Copied from org.apache.commons.codec.binary.Base64
 *///w  w w.  j  ava2s. c  o m
private static byte[] toIntegerBytes(final BigInteger bigInt) {
    int bitlen = bigInt.bitLength();
    // round bitlen
    bitlen = ((bitlen + 7) >> 3) << 3;
    final byte[] bigBytes = bigInt.toByteArray();

    if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
        return bigBytes;
    }
    // set up params for copying everything but sign bit
    int startSrc = 0;
    int len = bigBytes.length;

    // if bigInt is exactly byte-aligned, just skip signbit in copy
    if ((bigInt.bitLength() % 8) == 0) {
        startSrc = 1;
        len--;
    }
    final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
    final byte[] resizedBytes = new byte[bitlen / 8];
    System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
    return resizedBytes;
}

From source file:org.apache.spark.sql.execution.vectorized.ColumnVectorUtils.java

private static void appendValue(ColumnVector dst, DataType t, Object o) {
    if (o == null) {
        if (t instanceof CalendarIntervalType) {
            dst.appendStruct(true);/*from   w w  w .j  ava  2 s  .c o m*/
        } else {
            dst.appendNull();
        }
    } else {
        if (t == DataTypes.BooleanType) {
            dst.appendBoolean(((Boolean) o).booleanValue());
        } else if (t == DataTypes.ByteType) {
            dst.appendByte(((Byte) o).byteValue());
        } else if (t == DataTypes.ShortType) {
            dst.appendShort(((Short) o).shortValue());
        } else if (t == DataTypes.IntegerType) {
            dst.appendInt(((Integer) o).intValue());
        } else if (t == DataTypes.LongType) {
            dst.appendLong(((Long) o).longValue());
        } else if (t == DataTypes.FloatType) {
            dst.appendFloat(((Float) o).floatValue());
        } else if (t == DataTypes.DoubleType) {
            dst.appendDouble(((Double) o).doubleValue());
        } else if (t == DataTypes.StringType) {
            byte[] b = ((String) o).getBytes(StandardCharsets.UTF_8);
            dst.appendByteArray(b, 0, b.length);
        } else if (t instanceof DecimalType) {
            DecimalType dt = (DecimalType) t;
            Decimal d = Decimal.apply((BigDecimal) o, dt.precision(), dt.scale());
            if (dt.precision() <= Decimal.MAX_INT_DIGITS()) {
                dst.appendInt((int) d.toUnscaledLong());
            } else if (dt.precision() <= Decimal.MAX_LONG_DIGITS()) {
                dst.appendLong(d.toUnscaledLong());
            } else {
                final BigInteger integer = d.toJavaBigDecimal().unscaledValue();
                byte[] bytes = integer.toByteArray();
                dst.appendByteArray(bytes, 0, bytes.length);
            }
        } else if (t instanceof CalendarIntervalType) {
            CalendarInterval c = (CalendarInterval) o;
            dst.appendStruct(false);
            dst.getChildColumn(0).appendInt(c.months);
            dst.getChildColumn(1).appendLong(c.microseconds);
        } else if (t instanceof DateType) {
            dst.appendInt(DateTimeUtils.fromJavaDate((Date) o));
        } else {
            throw new NotImplementedException("Type " + t);
        }
    }
}

From source file:org.apache.spark.sql.execution.vectorized.ColumnVectorUtils.java

/**
 * Populates the entire `col` with `row[fieldIdx]`
 *///from  w  w w.  j a v  a 2s. c  o  m
public static void populate(ColumnVector col, InternalRow row, int fieldIdx) {
    int capacity = col.capacity;
    DataType t = col.dataType();

    if (row.isNullAt(fieldIdx)) {
        col.putNulls(0, capacity);
    } else {
        if (t == DataTypes.BooleanType) {
            col.putBooleans(0, capacity, row.getBoolean(fieldIdx));
        } else if (t == DataTypes.ByteType) {
            col.putBytes(0, capacity, row.getByte(fieldIdx));
        } else if (t == DataTypes.ShortType) {
            col.putShorts(0, capacity, row.getShort(fieldIdx));
        } else if (t == DataTypes.IntegerType) {
            col.putInts(0, capacity, row.getInt(fieldIdx));
        } else if (t == DataTypes.LongType) {
            col.putLongs(0, capacity, row.getLong(fieldIdx));
        } else if (t == DataTypes.FloatType) {
            col.putFloats(0, capacity, row.getFloat(fieldIdx));
        } else if (t == DataTypes.DoubleType) {
            col.putDoubles(0, capacity, row.getDouble(fieldIdx));
        } else if (t == DataTypes.StringType) {
            UTF8String v = row.getUTF8String(fieldIdx);
            byte[] bytes = v.getBytes();
            for (int i = 0; i < capacity; i++) {
                col.putByteArray(i, bytes);
            }
        } else if (t instanceof DecimalType) {
            DecimalType dt = (DecimalType) t;
            Decimal d = row.getDecimal(fieldIdx, dt.precision(), dt.scale());
            if (dt.precision() <= Decimal.MAX_INT_DIGITS()) {
                col.putInts(0, capacity, (int) d.toUnscaledLong());
            } else if (dt.precision() <= Decimal.MAX_LONG_DIGITS()) {
                col.putLongs(0, capacity, d.toUnscaledLong());
            } else {
                final BigInteger integer = d.toJavaBigDecimal().unscaledValue();
                byte[] bytes = integer.toByteArray();
                for (int i = 0; i < capacity; i++) {
                    col.putByteArray(i, bytes, 0, bytes.length);
                }
            }
        } else if (t instanceof CalendarIntervalType) {
            CalendarInterval c = (CalendarInterval) row.get(fieldIdx, t);
            col.getChildColumn(0).putInts(0, capacity, c.months);
            col.getChildColumn(1).putLongs(0, capacity, c.microseconds);
        } else if (t instanceof DateType) {
            Date date = (Date) row.get(fieldIdx, t);
            col.putInts(0, capacity, DateTimeUtils.fromJavaDate(date));
        }
    }
}