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

/**
 *  http://download.oracle.com/javase/1.5.0/docs/guide/security/CryptoSpec.html
 *  Signature Format   ASN.1 sequence of two INTEGER values: r and s, in that order:
 *                                SEQUENCE ::= { r INTEGER, s INTEGER }
 *
 *  http://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One
 *  30 -- tag indicating SEQUENCE/*from w w  w  .  j ava  2s .  c  om*/
 *  xx - length in octets
 *
 *  02 -- tag indicating INTEGER
 *  xx - length in octets
 *  xxxxxx - value
 *
 *  Convert to BigInteger and back so we have the minimum length representation, as required.
 *  r and s are always non-negative.
 *
 *  Only supports sigs up to about 252 bytes. See code to fix BER encoding for this before you
 *  add a SigType with bigger signatures.
 *
 *  @throws IllegalArgumentException if too big
 *  @since 0.8.7, moved to SigUtil in 0.9.9
 */
private static byte[] sigBytesToASN1(byte[] sig) {
    //System.out.println("pre TO asn1\n" + net.i2p.util.HexDump.dump(sig));
    int len = sig.length;
    int sublen = len / 2;
    byte[] tmp = new byte[sublen];

    System.arraycopy(sig, 0, tmp, 0, sublen);
    BigInteger r = new BigInteger(1, tmp);
    byte[] rb = r.toByteArray();
    if (rb.length > 127)
        throw new IllegalArgumentException("FIXME R length > 127");
    System.arraycopy(sig, sublen, tmp, 0, sublen);
    BigInteger s = new BigInteger(1, tmp);
    byte[] sb = s.toByteArray();
    if (sb.length > 127)
        throw new IllegalArgumentException("FIXME S length > 127");
    int seqlen = rb.length + sb.length + 4;
    if (seqlen > 255)
        throw new IllegalArgumentException("FIXME seq length > 255");
    int totlen = seqlen + 2;
    if (seqlen > 127)
        totlen++;
    byte[] rv = new byte[totlen];
    int idx = 0;

    rv[idx++] = 0x30;
    if (seqlen > 127)
        rv[idx++] = (byte) 0x81;
    rv[idx++] = (byte) seqlen;

    rv[idx++] = 0x02;
    rv[idx++] = (byte) rb.length;
    System.arraycopy(rb, 0, rv, idx, rb.length);
    idx += rb.length;

    rv[idx++] = 0x02;
    rv[idx++] = (byte) sb.length;
    System.arraycopy(sb, 0, rv, idx, sb.length);

    //System.out.println("post TO asn1\n" + net.i2p.util.HexDump.dump(rv));
    return rv;
}

From source file:Main.java

/**
 * Convert a BigInteger to a byte-array, but treat the byte-array given from
 * the BigInteger as unsigned and removing any leading zero bytes; e.g. a
 * 1024 bit integer with its highest bit set will result in an 128 byte
 * array.//from w w  w .j  a  v a 2 s.  c  o m
 *
 * @param bigInteger The BigInteger to convert.
 * @return The byte-array representation of the BigInterger without
 *         signum-bit. null, if the BigInteger is null.
 * @preconditions
 * @postconditions
 */
public static byte[] unsignedBigIntergerToByteArray(BigInteger bigInteger) {
    if (bigInteger == null) {
        return null;
    }
    byte[] integerBytes = bigInteger.toByteArray();
    byte[] unsignedIntegerBytes;
    if ((integerBytes.length > 0) && (integerBytes[0] == 0x00)) {
        unsignedIntegerBytes = new byte[integerBytes.length - 1];
        for (int i = 0; i < unsignedIntegerBytes.length; i++) {
            unsignedIntegerBytes[i] = integerBytes[i + 1];
        }
    } else {
        unsignedIntegerBytes = integerBytes;
    }

    return unsignedIntegerBytes;
}

From source file:org.apache.synapse.commons.crypto.EncodeDecodeHelper.java

/**
 * Decodes the provided byte array using the specified decoding type.
 *
 * @param input  The byte array to decode
 * @param decodingType The decoding type to use
 * @return The decoded byte array//w  w w  .  j a  v a  2 s . com
 * @throws IllegalArgumentException if the specified decodingType is not supported
 */
public static byte[] decode(byte[] input, EncodeDecodeTypes decodingType) {
    switch (decodingType) {
    case BASE64:
        if (log.isDebugEnabled()) {
            log.debug("base64 decoding on input  ");
        }
        return Base64Utils.decode(new String(input));
    case BIGINTEGER16:
        if (log.isDebugEnabled()) {
            log.debug("BigInteger 16 decoding on output ");
        }
        BigInteger n = new BigInteger(new String(input), 16);
        return n.toByteArray();
    case HEX:
        if (log.isDebugEnabled()) {
            log.debug("Hex decoding on output ");
        }
        return Hex.decode(input);
    default:
        throw new IllegalArgumentException("Unsupported encoding type");
    }
}

From source file:de.upb.wdqa.wdvd.revisiontags.SHA1Converter.java

private static byte[] parseByte(int base, String sha1) {
    byte[] result = null;
    if (sha1 != null) {
        if (!sha1.equals("")) {
            try {
                BigInteger bi = new BigInteger(sha1, base);
                result = bi.toByteArray();

            } catch (Exception e) {
                logger.error("", e);
            }//from  ww w  .j a v a 2  s  . c o  m
        } else {
            result = new byte[0];
        }
    }
    return result;

}

From source file:org.kuali.rice.core.api.criteria.CriteriaIntegerValue.java

/**
 * Since BigInteger is not technically immutable we defensively copy when needed.
 *
 * see Effective Java 2nd ed. page 79 for details.
 *
 * @param val the big integer to check//  w w  w. j av a  2 s  .co m
 * @return the safe BigInteger
 */
private static BigInteger safeInstance(BigInteger val) {
    if (val.getClass() != BigInteger.class) {
        return new BigInteger(val.toByteArray());
    }
    return val;
}

From source file:Main.java

public static void savePrivateKey(RSAPrivateKeySpec privateKey, Context context) {
    BigInteger privateModBI = privateKey.getModulus();
    BigInteger privateExpBI = privateKey.getPrivateExponent();

    byte[] privateModBA = privateModBI.toByteArray();// Base64.encodeInteger(pubModBI);
    // // for some
    // strange reason
    // this throws
    // NoSuchMethodError
    byte[] privateExpBA = privateExpBI.toByteArray();// Base64.encodeInteger(pubExpBI);

    try {/*  w ww.  jav a2 s  .c  om*/
        String privateModBase64Str = Base64.encodeToString(privateModBA, Base64.NO_WRAP);
        String privateExpBase64Str = Base64.encodeToString(privateExpBA, Base64.NO_WRAP);
        savePrivateKey(privateModBase64Str, privateExpBase64Str, context);

    } catch (NoSuchMethodError e) {
        Log.e(TAG, "Base64.encode() method not available", e);
    }
}

From source file:net.ftb.util.CryptoUtils.java

/**
 * Newer implementation available if possible use {@link #decrypt(String str, byte[] key)}
 * @param str string to decrypt/*from   ww  w  .  j a  v  a 2s . c om*/
 * @param key decryption key
 * @return decrypted string or "" if fails
 */
@Deprecated
public static String decryptLegacy(String str, byte[] key) {
    BigInteger in = new BigInteger(str, 16).xor(new BigInteger(1, key));
    try {
        return new String(in.toByteArray(), "utf8");
    } catch (UnsupportedEncodingException e) {
        return "";
    } catch (NumberFormatException e) {
        Logger.logError("Error occurred during legacy decryption");
        return "";
    }
}

From source file:org.wso2.securevault.EncodingHelper.java

/**
 * Decodes the provided InputStream using the specified encoding type.
 *
 * @param inputStream  The InputStream to decode
 * @param encodingType The encoding to use
 * @return The decoded InputStream//from w ww.  j  a va 2  s.  c  om
 * @throws java.io.IOException      If an error occurs decoding the input stream
 * @throws IllegalArgumentException if the specified encodingType is not supported
 */
public static InputStream decode(InputStream inputStream, EncodingType encodingType) throws IOException {

    InputStream decodedInputStream = null;
    switch (encodingType) {
    case BASE64:
        if (log.isDebugEnabled()) {
            log.debug("base64 decoding on input  ");
        }
        decodedInputStream = new ByteArrayInputStream(
                Base64Utils.decode(new String(MiscellaneousUtil.asBytes(inputStream))));
        break;
    case BIGINTEGER16:
        if (log.isDebugEnabled()) {
            log.debug("BigInteger 16 encoding on output ");
        }

        BigInteger n = new BigInteger(IOUtils.toString(inputStream), 16);
        decodedInputStream = new ByteArrayInputStream(n.toByteArray());
        break;
    default:
        throw new IllegalArgumentException("Unsupported encoding type");
    }

    return decodedInputStream;
}

From source file:HexUtil.java

/**
 * Turn a BigInteger into a hex string./*from ww w.ja  va 2s .co m*/
 * BigInteger.toString(16) NPEs on Sun JDK 1.4.2_05. :<
 * The bugs in their Big* are getting seriously irritating...
 */
public static String biToHex(BigInteger bi) {
    return bytesToHex(bi.toByteArray());
}

From source file:org.apache.synapse.commons.security.tool.EncodingHelper.java

/**
 * Decodes the provided InputStream using the specified encoding type.
 * /*from  w  w w  . j a v a 2 s  . c om*/
 * @param inputStream               The InputStream to decode
 * @param encodingType              The encoding to use
 * 
 * @throws IOException              If an error occurs decoding the input stream
 * @throws IllegalArgumentException if the specified encodingType is not supported
 * 
 * @return The decoded InputStream
 */
public static InputStream decode(InputStream inputStream, EncodingType encodingType) throws IOException {

    InputStream decodedInputStream = null;
    switch (encodingType) {
    case BASE64:
        if (log.isDebugEnabled()) {
            log.debug("base64 decoding on input  ");
        }
        decodedInputStream = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(inputStream));
        break;
    case BIGINTEGER16:
        if (log.isDebugEnabled()) {
            log.debug("BigInteger 16 encoding on output ");
        }

        BigInteger n = new BigInteger(IOUtils.toString(inputStream), 16);
        decodedInputStream = new ByteArrayInputStream(n.toByteArray());
        break;
    default:
        throw new IllegalArgumentException("Unsupported encoding type");
    }

    return decodedInputStream;
}