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:org.springframework.bus.firehose.integration.support.TupleFactory.java

/**
 * Needed due dropsonde decision to use uint64 and little endianess
 * @param uuid/*from   w  w w . j  a v a 2 s .c  o  m*/
 * @return
 */
public static String parseUUID(UuidFactory.UUID uuid) {

    String uuidStr = null;

    try {
        BigInteger low = new BigInteger(String.valueOf(uuid.getLow()));
        BigInteger high = new BigInteger(String.valueOf(uuid.getHigh()));
        byte[] lowBytes = reverse(low.toByteArray());
        byte[] highBytes = reverse(high.toByteArray());
        byte[] data1 = new byte[lowBytes.length + highBytes.length];
        System.arraycopy(lowBytes, 0, data1, 0, lowBytes.length);
        System.arraycopy(highBytes, 0, data1, lowBytes.length, highBytes.length);

        StringBuilder builder = new StringBuilder(Hex.encodeHexString(data1));
        uuidStr = builder.insert(8, "-").insert(13, "-").insert(18, "-").insert(23, "-").toString();
    } catch (Exception ex) {

    }

    return uuidStr;

}

From source file:tor.TorCrypto.java

/**
 * BigInteger to byte array, stripping leading zero if applicable (e.g. unsigned data only)
 *
 * @param in BigInteger//from   w  w  w.  j  a v  a2s .  co m
 * @return
 */
public static byte[] BNtoByte(BigInteger in) {
    byte[] intmp = in.toByteArray();
    if (intmp[0] != 0)
        return intmp;

    byte intmp2[] = new byte[intmp.length - 1];
    System.arraycopy(intmp, 1, intmp2, 0, intmp2.length);
    return intmp2;
}

From source file:de.decoit.visa.net.IPAddress.java

/**
 * Static utility function to translate a provided bit mask into the IP
 * version specific string notation./*from ww w.j av  a2s  .  c  o m*/
 *
 * @param pMask Object containing the bit mask of the address to translate
 * @param pVersion Version of the Internet Protocol which will be used for
 *            the address
 * @return The string notation of the provided IP address
 */
private static String bitmaskToString(BigInteger pMask, IPVersion pVersion) {
    byte[] maskBytes = pMask.toByteArray();
    StringBuilder rv = new StringBuilder();
    boolean ignoreFirstByte;

    if (pVersion == IPVersion.V4) {
        // If array length is 5 it contains a sign byte we have to ignore
        ignoreFirstByte = (maskBytes.length == 5);

        for (int i = 0; i < maskBytes.length; i++) {
            if (ignoreFirstByte) {
                // Skip the first byte, it's the sign byte
                i++;
                ignoreFirstByte = false;
            }

            rv.append(maskBytes[i] & 0xFF);

            // Only append the '.' if this is not the last segment
            if (i < maskBytes.length - 1) {
                rv.append(".");
            }
        }
    } else if (pVersion == IPVersion.V6) {
        // If array length is 17 it contains a sign byte we have to ignore
        ignoreFirstByte = (maskBytes.length == 17);

        for (int i = 0; i < maskBytes.length; i += 2) {
            if (ignoreFirstByte) {
                // Skip the first byte
                i++;
                ignoreFirstByte = false;
            }

            // Notation segments are made of 2 bytes in IPv6
            rv.append(String.format("%02X", maskBytes[i]));
            rv.append(String.format("%02X", maskBytes[i + 1]));

            // Only append the ':' if this is not the last segment
            if (i < maskBytes.length - 2) {
                rv.append(":");
            }
        }
    } else {
        throw new IllegalStateException("Unsupported IP version detected");
    }

    return rv.toString();
}

From source file:org.picketbox.json.key.RSAKey.java

public static RSAKey convert(RSAPublicKey publicKey) throws ProcessingException {
    BigInteger modulus = publicKey.getModulus();
    BigInteger exponent = publicKey.getPublicExponent();

    RSAKey rsaKey = new RSAKey();
    rsaKey.setMod(PicketBoxJSONUtil.b64Encode(modulus.toByteArray()));
    rsaKey.setExp(PicketBoxJSONUtil.b64Encode(exponent.toByteArray()));
    return rsaKey;
}

From source file:org.forgerock.openam.openid.provider.Codec.java

public static String encodeBigInteger(BigInteger value) {
    if (value == null) {
        return null;
    }// ww w .  jav a  2  s .  c om

    return encodeBytes(value.toByteArray());
}

From source file:com.cliqset.magicsig.util.KeyGen.java

/**
* Returns a byte-array representation of a <code>{@link BigInteger}<code>.
* No sign-bit is outputed./*from   w  w w . j a  va 2s .  c o m*/
*
* <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
* retunrs eventually longer arrays because of the leading sign-bit.
*
* @param big <code>BigInteger<code> to be converted
* @param bitlen <code>int<code> the desired length in bits of the representation
* @return a byte array with <code>bitlen</code> bits of <code>big</code>
*/
static final byte[] getBytes(BigInteger big) {
    int bitlen = big.bitLength();
    //round bitlen
    bitlen = ((bitlen + 7) >> 3) << 3;

    if (bitlen < big.bitLength()) {
        throw new IllegalArgumentException("Illegal bit len.");
    }

    byte[] bigBytes = big.toByteArray();

    if (((big.bitLength() % 8) != 0) && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
        return bigBytes;
    }

    // some copying needed
    int startSrc = 0; // no need to skip anything
    int bigLen = bigBytes.length; //valid length of the string

    if ((big.bitLength() % 8) == 0) { // correct values
        startSrc = 1; // skip sign bit

        bigLen--; // valid length of the string
    }

    int startDst = bitlen / 8 - bigLen; //pad with leading nulls
    byte[] resizedBytes = new byte[bitlen / 8];

    System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);

    return resizedBytes;
}

From source file:com.offbynull.peernetic.common.identification.Id.java

/**
 * Generates a limit that's {@code 2^n-1}. Another way to think of it is, generates a limit that successively {@code n = (n << 1) | 1}
 * for {@code n} times -- making sure you have a limit that's value is all 1 bits.
 * <p/>/*  www .  j av  a2s. c  o  m*/
 * Examples:
 * <ul>
 * <li>{@code n = 1, limit = 1 (1b)}<li/>
 * <li>{@code n = 2, limit = 3 (11b)}<li/>
 * <li>{@code n = 4, limit = 7 (111b)}<li/>
 * <li>{@code n = 8, limit = 15 (1111b)}<li/>
 * </ul>
 * @param exp exponent, such that the returned value is {@code 2^exp-1}
 * @return {@code 2^exp-1} as a byte array
 * @throws IllegalArgumentException if {@code exp <= 0}
 */
private static byte[] generatePowerOfTwoLimit(int exp) {
    Validate.inclusiveBetween(1, Integer.MAX_VALUE, exp);

    BigInteger val = BigInteger.ONE.shiftLeft(exp).subtract(BigInteger.ONE); // (1 << exp) - 1

    return val.toByteArray();
}

From source file:com.cyanogenmod.account.util.CMAccountUtils.java

public static String encodeHex(BigInteger integer) {
    return encodeHex(integer.toByteArray());
}

From source file:RandomUtil.java

public static BigInteger randomBitFlip(BigInteger n) {
    if (n.equals(BigInteger.ONE))
        return BigInteger.ONE;
    if (n.equals(BigInteger.ZERO))
        return BigInteger.ZERO;

    BigInteger toRet = BigInteger.ONE;
    while (toRet.equals(BigInteger.ONE) || toRet.equals(BigInteger.ZERO)) {
        byte[] bytes = n.toByteArray();
        getInstance().random.nextBytes(bytes);
        // could allow up to maxExclusive by converting and checking value
        // but this is faster, even if it doesn't give us full range
        bytes[0] = 0;/* ww w .  jav  a2  s  . c  o m*/
        toRet = new BigInteger(bytes);
    }
    return toRet;
}

From source file:watne.seis720.project.AES_Utilities.java

/**
 * Get the sequence of bytes represented by the given String. Code adapted
 * from <a//from   w  ww .ja  v a  2  s.  c o  m
 * href="http://www.exampledepot.com/egs/java.math/Bytes2Str.html">Parsing
 * and Formatting a Byte Array into Binary, Octal, and Hexadecimal (Java
 * Developers Almanac Example)</a>
 * @param hexString the hexadecimal representation of the number.
 * @return the sequence of bytes represented by the given String.
 */
public static byte[] getBytesFromHex(String hexString) {
    BigInteger bigInt = new BigInteger(hexString, 16); // Parse the string.
    byte[] hexBytes = bigInt.toByteArray();
    return hexBytes;
}