Java Code Examples for java.math.BigInteger#toByteArray()

The following examples show how to use java.math.BigInteger#toByteArray() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: GreenBits   File: Utils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @see Utils#decodeCompactBits(long)
 */
public static long encodeCompactBits(BigInteger value) {
    long result;
    int size = value.toByteArray().length;
    if (size <= 3)
        result = value.longValue() << 8 * (3 - size);
    else
        result = value.shiftRight(8 * (size - 3)).longValue();
    // The 0x00800000 bit denotes the sign.
    // Thus, if it is already set, divide the mantissa by 256 and increase the exponent.
    if ((result & 0x00800000L) != 0) {
        result >>= 8;
        size++;
    }
    result |= size << 24;
    result |= value.signum() == -1 ? 0x00800000 : 0;
    return result;
}
 
Example 2
Source Project: j2objc   File: BigIntegerSubtractTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Subtract two numbers of the same length and different signs.
 * The first is positive.
 * The first is greater in absolute value.
 */
public void testCase3() {
    byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30};
    byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3};
    int aSign = 1;
    int bSign = -1;        
    byte rBytes[] = {11, 22, 33, 44, 55, 66, 77, 11, 22, 33};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.subtract(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals(1, result.signum());
}
 
Example 3
Source Project: j2objc   File: BigIntegerAddTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add two numbers of the same length.
 * The first one is positive and the second is negative.
 * The first one is greater in absolute value.
 */
public void testCase3() {
    byte aBytes[] = {3, 4, 5, 6, 7, 8, 9};
    byte bBytes[] = {1, 2, 3, 4, 5, 6, 7};
    byte rBytes[] = {2, 2, 2, 2, 2, 2, 2};
    int aSign = 1;
    int bSign = -1;
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.add(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 1, result.signum());
}
 
Example 4
/**
 * @param in the BigInteger whose bytes to use for the String
 *      usually the output of 'createBigInteger()', above.
 * @return String-ified BigInteger.bytes[]
 * @throws SecretShareException on error
 */
public static String createHumanString(final BigInteger in)
{
    if (in != null)
    {
        try
        {
            byte[] b = in.toByteArray();
            String s = new String(b, UTF8);
            return s;
        }
        catch (UnsupportedEncodingException e)
        {
            // just can't happen, but if it does...
            throw new SecretShareException("UTF8 not found", e);
        }
    }
    else
    {
        return "null";
    }
}
 
Example 5
Source Project: snowblossom   File: BlockchainUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static ByteString targetBigIntegerToBytes(BigInteger target)
{
  ByteBuffer bb = ByteBuffer.allocate(Globals.TARGET_LENGTH);

  byte[] data = target.toByteArray();
  int zeros = Globals.TARGET_LENGTH - data.length;

  for (int i = 0; i < zeros; i++)
  {
    byte z = 0;
    bb.put(z);
  }
  bb.put(data);

  return ByteString.copyFrom(bb.array());
}
 
Example 6
Source Project: j2objc   File: BigIntegerSubtractTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Subtract two numbers of the same length and different signs.
 * The first is negative.
 * The first is greater in absolute value.
 */
public void testCase7() {
    byte aBytes[] = {10, 20, 30, 40, 50, 60, 70, 10, 20, 30};
    byte bBytes[] = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3};
    int aSign = -1;
    int bSign = 1;        
    byte rBytes[] = {-12, -23, -34, -45, -56, -67, -78, -12, -23, -33};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.subtract(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals(-1, result.signum());
}
 
Example 7
/**
 * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
 * No sign-bit is output.
 *
 * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
 * returns 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) {

    //round bitlen
    bitlen = ((bitlen + 7) >> 3) << 3;

    if (bitlen < big.bitLength()) {
        throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength"));
    }

    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;
}
 
Example 8
/**
 * Marshals a DER integer on the output stream.
 *
 * @param i the integer in the form of a BigInteger.
 */
public void putInteger(BigInteger i) throws IOException {
    write(DerValue.tag_Integer);
    byte[]    buf = i.toByteArray(); // least number  of bytes
    putLength(buf.length);
    write(buf, 0, buf.length);
}
 
Example 9
Source Project: Qora   File: Base58.java    License: MIT License 5 votes vote down vote up
public static byte[] decode(String input) {
   if(input.length() == 0) {
     return null;
   }
   BigInteger decoded = decodeToBigInteger(input);
   if(decoded == null) {
      return null;
   }
   byte[] bytes = decoded.toByteArray();
   // We may have got one more byte than we wanted, if the high bit of the
   // next-to-last byte was not zero. This
   // is because BigIntegers are represented with twos-compliment notation,
   // thus if the high bit of the last
   // byte happens to be 1 another 8 zero bits will be added to ensure the
   // number parses as positive. Detect
   // that case here and chop it off.
   boolean stripSignByte = bytes.length > 1 && bytes[0] == 0 && bytes[1] < 0;
   // Count the leading zeros, if any.
   int leadingZeros = 0;
   for (int i = 0; i < input.length() && input.charAt(i) == ALPHABET.charAt(0); i++) {
      leadingZeros++;
   }
   // Now cut/pad correctly. Java 6 has a convenience for this, but Android
   // can't use it.
   byte[] tmp = new byte[bytes.length - (stripSignByte ? 1 : 0)
         + leadingZeros];
   System.arraycopy(bytes, stripSignByte ? 1 : 0, tmp, leadingZeros,
         tmp.length - leadingZeros);
   return tmp;
}
 
Example 10
Source Project: bitcoin-verde   File: ChainWork.java    License: MIT License 5 votes vote down vote up
static MutableChainWork fromBigInteger(final BigInteger bigInteger) {
    final byte[] bytes = bigInteger.toByteArray();
    final MutableChainWork mutableChainWork = new MutableChainWork();
    for (int i = 0; i < bytes.length; ++i) {
        mutableChainWork.setByte((32 - i -1), (bytes[bytes.length - i - 1]));
    }
    return mutableChainWork;
}
 
Example 11
/**
 * flipBit(int n) inside a negative number
 */
public void testFlipBitNegativeInside2() {
    byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26};
    int aSign = -1;
    int number = 45;
    byte rBytes[] = {-2, 127, -57, -101, 1, 75, -90, -14, -92, -4, 14, -36, -26};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger result = aNumber.flipBit(number);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", -1, result.signum());
}
 
Example 12
private static String handleCollision(byte[] hashedRepresentation) {
  hashedRepresentation = Arrays.copyOf(hashedRepresentation, RESOURCE_NAME_LENGTH);
  BigInteger bigInteger = new BigInteger(hashedRepresentation);
  byte[] newHashedRepresentation = bigInteger.toByteArray();
  if (newHashedRepresentation.length > RESOURCE_NAME_LENGTH) {
    newHashedRepresentation = new byte[6];
  }

  return Base64.getUrlEncoder().encodeToString(newHashedRepresentation);
}
 
Example 13
private static BigInteger hash64(String str) {
    BigInteger value = BigInteger.valueOf(HASH64_SEED);

    for (int cp, i = 0; i < str.length(); i += Character.charCount(cp)) {
        cp = str.codePointAt(i);
        value = value.add(BigInteger.valueOf(cp)).multiply(
            BigInteger.valueOf(HASH64_STEP));
    }
    byte[] valueBytes = value.toByteArray();
    byte[] longBytes = new byte[8];
    System.arraycopy(valueBytes, valueBytes.length - longBytes.length,
        longBytes, 0, longBytes.length);
    BigInteger hash = new BigInteger(1, longBytes);
    return hash;
}
 
Example 14
Source Project: scelight   File: RsaKeyPairGen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Saves a key to the specified file.
 * 
 * @param mod modulus part of the key to be saved
 * @param exp exponent part of the key to be saved
 * @param path path to save the key to
 * @throws Exception if some error occurs
 */
private static void saveKey( final BigInteger mod, final BigInteger exp, final Path path ) throws Exception {
	try ( final DataOutputStream out = new DataOutputStream( Files.newOutputStream( path ) ) ) {
		
		out.writeInt( RsaConsts.KEY_SIZE_BITS );
		
		byte[] buff = mod.toByteArray();
		out.writeInt( buff.length );
		out.write( buff );
		
		buff = exp.toByteArray();
		out.writeInt( buff.length );
		out.write( buff );
	}
}
 
Example 15
private byte[] trimmedBigInteger(BigInteger n) {
  // Java can add a leading zero to make the number positive.
  byte[] t = n.toByteArray();
  if (t[0] == 0) {
    return Arrays.copyOfRange(t, 1, t.length);
  }
  return t;
}
 
Example 16
private void init(int opmode, Key key) throws InvalidKeyException {

        boolean encrypt;

        switch (opmode) {
        case Cipher.ENCRYPT_MODE:
        case Cipher.WRAP_MODE:
            paddingLength = PAD_PKCS1_LENGTH;
            encrypt = true;
            break;
        case Cipher.DECRYPT_MODE:
        case Cipher.UNWRAP_MODE:
            paddingLength = 0; // reset
            encrypt = false;
            break;
        default:
            throw new InvalidKeyException("Unknown mode: " + opmode);
        }

        if (!(key instanceof sun.security.mscapi.Key)) {
            if (key instanceof java.security.interfaces.RSAPublicKey) {
                java.security.interfaces.RSAPublicKey rsaKey =
                    (java.security.interfaces.RSAPublicKey) key;

                // Convert key to MSCAPI format

                BigInteger modulus = rsaKey.getModulus();
                BigInteger exponent =  rsaKey.getPublicExponent();

                // Check against the local and global values to make sure
                // the sizes are ok.  Round up to the nearest byte.
                RSAKeyFactory.checkKeyLengths(((modulus.bitLength() + 7) & ~7),
                    exponent, -1, RSAKeyPairGenerator.KEY_SIZE_MAX);

                byte[] modulusBytes = modulus.toByteArray();
                byte[] exponentBytes = exponent.toByteArray();

                // Adjust key length due to sign bit
                int keyBitLength = (modulusBytes[0] == 0)
                    ? (modulusBytes.length - 1) * 8
                    : modulusBytes.length * 8;

                byte[] keyBlob = RSASignature.generatePublicKeyBlob(
                    keyBitLength, modulusBytes, exponentBytes);

                try {
                    key = RSASignature.importPublicKey(keyBlob, keyBitLength);

                } catch (KeyStoreException e) {
                    throw new InvalidKeyException(e);
                }

            } else {
                throw new InvalidKeyException("Unsupported key type: " + key);
            }
        }

        if (key instanceof PublicKey) {
            mode = encrypt ? MODE_ENCRYPT : MODE_VERIFY;
            publicKey = (sun.security.mscapi.Key)key;
            privateKey = null;
            outputSize = publicKey.length() / 8;
        } else if (key instanceof PrivateKey) {
            mode = encrypt ? MODE_SIGN : MODE_DECRYPT;
            privateKey = (sun.security.mscapi.Key)key;
            publicKey = null;
            outputSize = privateKey.length() / 8;
        } else {
            throw new InvalidKeyException("Unknown key type: " + key);
        }

        bufOfs = 0;
        buffer = new byte[outputSize];
    }
 
Example 17
protected void engineInitVerify(PublicKey key)
    throws InvalidKeyException
{
    // This signature accepts only RSAPublicKey
    if ((key instanceof java.security.interfaces.RSAPublicKey) == false) {
        throw new InvalidKeyException("Key type not supported");
    }

    java.security.interfaces.RSAPublicKey rsaKey =
        (java.security.interfaces.RSAPublicKey) key;

    if ((key instanceof sun.security.mscapi.RSAPublicKey) == false) {

        // convert key to MSCAPI format

        BigInteger modulus = rsaKey.getModulus();
        BigInteger exponent =  rsaKey.getPublicExponent();

        // Check against the local and global values to make sure
        // the sizes are ok.  Round up to the nearest byte.
        RSAKeyFactory.checkKeyLengths(((modulus.bitLength() + 7) & ~7),
            exponent, -1, RSAKeyPairGenerator.KEY_SIZE_MAX);

        byte[] modulusBytes = modulus.toByteArray();
        byte[] exponentBytes = exponent.toByteArray();

        // Adjust key length due to sign bit
        int keyBitLength = (modulusBytes[0] == 0)
            ? (modulusBytes.length - 1) * 8
            : modulusBytes.length * 8;

        byte[] keyBlob = generatePublicKeyBlob(
            keyBitLength, modulusBytes, exponentBytes);

        try {
            publicKey = importPublicKey(keyBlob, keyBitLength);

        } catch (KeyStoreException e) {
            throw new InvalidKeyException(e);
        }

    } else {
        publicKey = (sun.security.mscapi.RSAPublicKey) key;
    }

    this.privateKey = null;
    resetDigest();
}
 
Example 18
Source Project: incubator-tajo   File: Bytes.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Iterate over keys within the passed inclusive range.
 */
public static Iterable<byte[]> iterateOnSplits(
    final byte[] a, final byte[]b, final int num)
{  
  byte [] aPadded;
  byte [] bPadded;
  if (a.length < b.length) {
    aPadded = padTail(a, b.length - a.length);
    bPadded = b;
  } else if (b.length < a.length) {
    aPadded = a;
    bPadded = padTail(b, a.length - b.length);
  } else {
    aPadded = a;
    bPadded = b;
  }
  if (compareTo(aPadded,bPadded) >= 0) {
    throw new IllegalArgumentException("b <= a");
  }
  if (num <= 0) {
    throw new IllegalArgumentException("num cannot be < 0");
  }
  byte [] prependHeader = {1, 0};
  final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
  final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
  final BigInteger diffBI = stopBI.subtract(startBI);
  final BigInteger splitsBI = BigInteger.valueOf(num + 1);
  if(diffBI.compareTo(splitsBI) < 0) {
    return null;
  }
  final BigInteger intervalBI;
  try {
    intervalBI = diffBI.divide(splitsBI);
  } catch(Exception e) {
    LOG.error("Exception caught during division", e);
    return null;
  }

  final Iterator<byte[]> iterator = new Iterator<byte[]>() {
    private int i = -1;
    
    @Override
    public boolean hasNext() {
      return i < num+1;
    }

    @Override
    public byte[] next() {
      i++;
      if (i == 0) return a;
      if (i == num + 1) return b;
      
      BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
      byte [] padded = curBI.toByteArray();
      if (padded[1] == 0)
        padded = tail(padded, padded.length - 2);
      else
        padded = tail(padded, padded.length - 1);
      return padded;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }
    
  };
  
  return new Iterable<byte[]>() {
    @Override
    public Iterator<byte[]> iterator() {
      return iterator;
    }
  };
}
 
Example 19
/**
	 * Sets this to the given BigInteger N. This method must be called before any arithmetic operation.
	 * If a buffer has been passed to the constructor then it should be big enough to represent N.
	 * 
	 * @param N
	 */
	public void set(BigInteger N) {
		intLength = (N.bitLength()+31)>>5; // round up
		if (intLength > 0) {
			if (intArray == null || intArray.length < intLength) {
				// allocate new 0-initialized array
				intArray = new int[intLength];
			} else {
				// clear existing buffer
				for (int i=intLength-1; i>=0; i--) intArray[i] = 0; // TODO: use arrayCopy() ?
			}
			
			// bytes in big-endian order, i.e. the most significant byte is at index 0
			byte[] bytes = N.toByteArray();
			// convert byte[] to unsigned int[]
			//LOG.debug("#bytes = " + bytes.length + ", #ints = " + intLength);
			int i=0, j=0;
			for (int bPos=bytes.length-1; bPos>=0; bPos--) {
				int b = bytes[bPos] & 0xFF;
				intArray[i] |= b<<(j<<3);
				if (++j==4) {
					if (++i == intLength) {
						// The most significant byte of N.toByteArray() has a sign bit, which is 0 for unsigned integers.
						// But it may lead to another byte! -> skip that one...
						//LOG.debug("i has reached maximum value " + i);
						break;
					}
					j = 0;
				}
			}
		}
		
		if (DEBUG) {
//			try {
//				// compare with slower but safer implementation
//				int[] intArrayFromNShifts = safeConversion(N);
//				for (int i=0; i<intLength; i++) {
//					assertEquals(intArrayFromNShifts[i], intArray[i]);
//				}
//			} catch (AssertionError ae) {
//				LOG.debug("N              = " + N.toString(2));
//				LOG.debug("UnsignedBigInt = " + this.toBinaryString());
//				throw ae;
//			}
		}
	}
 
Example 20
/**
 * Pack the BigInteger into a OID subidentifier DER encoding
 */
private static int pack7Oid(BigInteger input, byte[] out, int ooffset) {
    byte[] b = input.toByteArray();
    return pack7Oid(b, 0, b.length, out, ooffset);
}