java.math.BigInteger Java Examples

The following examples show how to use java.math.BigInteger. 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 File: StatusMessageTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void serializeDeserializeWithForkId() {
  final int version = EthProtocol.EthVersion.V64;
  final BigInteger networkId = BigInteger.ONE;
  final Difficulty td = Difficulty.of(1000L);
  final Hash bestHash = randHash(1L);
  final Hash genesisHash = randHash(2L);
  final ForkId forkId = new ForkId(Bytes.fromHexString("0xa00bc334"), 0L);

  final MessageData msg =
      StatusMessage.create(version, networkId, td, bestHash, genesisHash, forkId);

  final StatusMessage copy = new StatusMessage(msg.getData());

  assertThat(copy.protocolVersion()).isEqualTo(version);
  assertThat(copy.networkId()).isEqualTo(networkId);
  assertThat(copy.totalDifficulty()).isEqualTo(td);
  assertThat(copy.bestHash()).isEqualTo(bestHash);
  assertThat(copy.genesisHash()).isEqualTo(genesisHash);
  assertThat(copy.forkId()).isEqualTo(forkId);
}
 
Example #2
Source File: BloggerLoginController.java    From BlogSystem with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/way=name", method = RequestMethod.POST)
public ResultBean loginWithUserName(HttpServletRequest request,
                                    @RequestParam("username") String userName,
                                    @RequestParam("password") String password) throws NoSuchAlgorithmException {
    // update 使用shiro

    BloggerAccount account = accountService.getAccount(userName);

    // 用户不存在
    if (account == null) {
        throw exceptionManager.getUnknownBloggerException(new RequestContext(request));
    }

    // 密码错误
    if (!account.getPassword().equals(new BigInteger(StringUtils.toSha(password)).toString())) {
        throw exceptionManager.getLoginFailException(new RequestContext(request), true);
    }

    HttpSession session = request.getSession();
    session.setAttribute(bloggerProperties.getSessionNameOfBloggerId(), account.getId());
    session.setAttribute(bloggerProperties.getSessionNameOfBloggerName(), account.getUsername());
    session.setAttribute(bloggerProperties.getSessionBloggerLoginSignal(), "login");

    // 成功登录
    return new ResultBean<>("");
}
 
Example #3
Source File: KeyGeneratorCli.java    From protect with MIT License 6 votes vote down vote up
public static KeyPair convertFromPaillier(final PaillierKeyPair paillierKeyPair)
		throws InvalidKeySpecException, NoSuchAlgorithmException {
	// Get keys
	final PaillierPrivateKey paillierPrivateKey = paillierKeyPair.getPrivateKey();
	final PaillierPublicKey paillierPublicKey = paillierKeyPair.getPublicKey();

	// Get fields
	final BigInteger n = paillierPublicKey.getN(); // treat as 'N'
	final BigInteger e = paillierPublicKey.getG(); // treat as 'e'
	final BigInteger d = paillierPrivateKey.getLambda(); // treat as 'd'

	// Represent them as RSA keys
	final RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(n, d);
	final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(n, e);

	// Convert to key pair
	final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	final PublicKey rsaPublic = keyFactory.generatePublic(pubKeySpec);
	final PrivateKey rsaPrivate = keyFactory.generatePrivate(privKeySpec);

	return new KeyPair(rsaPublic, rsaPrivate);
}
 
Example #4
Source File: AbstractStatisticsHandlerNumeric.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
protected final void addValue (final long nValue)
{
  // Better performance when done manually
  m_aRWLock.writeLock ().lock ();
  try
  {
    m_nInvocationCount++;
    if (m_nMin == CGlobal.ILLEGAL_ULONG || nValue < m_nMin)
      m_nMin = nValue;
    if (m_nMax == CGlobal.ILLEGAL_ULONG || nValue > m_nMax)
      m_nMax = nValue;
    m_aSum = m_aSum.add (BigInteger.valueOf (nValue));
  }
  finally
  {
    m_aRWLock.writeLock ().unlock ();
  }
}
 
Example #5
Source File: BigIntegerNotTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * andNot for two negative numbers; the first is longer
 */
public void testAndNotNegNegFirstLonger() {
    byte aBytes[] = {-128, 9, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, -117, 23, 87, -25, -75};
    byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23};
    int aSign = -1;
    int bSign = -1;        
    byte rBytes[] = {73, -92, -48, 4, 12, 6, 4, 32, 48, 64, 0, 8, 2};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.andNot(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 #6
Source File: TronscanAPI.java    From cashuwallet with MIT License 6 votes vote down vote up
@Override
public Object custom(String name, Object arg) {
    if (name.equals("block")) {
        try {
            String url = baseUrl + "block/latest";
            JSONObject data = new JSONObject(Network.urlFetch(url));
            dict fields = new dict();
            fields.put("hash", data.getString("hash"));
            fields.put("height", BigInteger.valueOf(data.getLong("number")));
            fields.put("timestamp", BigInteger.valueOf(data.getLong("timestamp")));
            return fields;
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}
 
Example #7
Source File: BigRealTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testConstructor() {
    assertEquals(1.625, new BigReal(new BigDecimal("1.625")).doubleValue(), 1.0e-15);
    assertEquals(-5.0, new BigReal(new BigInteger("-5")).doubleValue(), 1.0e-15);
    assertEquals(-5.0, new BigReal(new BigInteger("-5"), MathContext.DECIMAL64).doubleValue(), 1.0e-15);
    assertEquals(0.125, new BigReal(new BigInteger("125"), 3).doubleValue(), 1.0e-15);
    assertEquals(0.125, new BigReal(new BigInteger("125"), 3, MathContext.DECIMAL64).doubleValue(), 1.0e-15);
    assertEquals(1.625, new BigReal(new char[] { '1', '.', '6', '2', '5' }).doubleValue(), 1.0e-15);
    assertEquals(1.625, new BigReal(new char[] { 'A', 'A', '1', '.', '6', '2', '5', '9' }, 2, 5).doubleValue(), 1.0e-15);
    assertEquals(1.625, new BigReal(new char[] { 'A', 'A', '1', '.', '6', '2', '5', '9' }, 2, 5, MathContext.DECIMAL64).doubleValue(), 1.0e-15);
    assertEquals(1.625, new BigReal(new char[] { '1', '.', '6', '2', '5' }, MathContext.DECIMAL64).doubleValue(), 1.0e-15);
    assertEquals(1.625, new BigReal(1.625).doubleValue(), 1.0e-15);
    assertEquals(1.625, new BigReal(1.625, MathContext.DECIMAL64).doubleValue(), 1.0e-15);
    assertEquals(-5.0, new BigReal(-5).doubleValue(), 1.0e-15);
    assertEquals(-5.0, new BigReal(-5, MathContext.DECIMAL64).doubleValue(), 1.0e-15);
    assertEquals(-5.0, new BigReal(-5l).doubleValue(), 1.0e-15);
    assertEquals(-5.0, new BigReal(-5l, MathContext.DECIMAL64).doubleValue(), 1.0e-15);
    assertEquals(1.625, new BigReal("1.625").doubleValue(), 1.0e-15);
    assertEquals(1.625, new BigReal("1.625", MathContext.DECIMAL64).doubleValue(), 1.0e-15);
}
 
Example #8
Source File: RationalChap14Quiz19.java    From BUPTJava with Apache License 2.0 6 votes vote down vote up
private static BigInteger gcd1(BigInteger n, BigInteger d) {
    BigInteger n1 = n.abs();
    BigInteger n2 = d.abs();
    BigInteger temp;
    if(n1.equals(new BigInteger("0"))){ // 分子为0, 直接返回1即可
        return  new BigInteger("1");
    }
    if(n1.compareTo(n2) <= 0) { // 确保n1 > n2
        temp = n1;
        n1 = n2;
        n2 = temp;
    }

    temp = n1.mod(n2);
    while(!temp.equals(new BigInteger("0"))){
        n1 = n2;
        n2 = temp;
        temp = n1.mod(n2);
    }
    return n2;
}
 
Example #9
Source File: BigFractionFormat.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Formats an object and appends the result to a StringBuffer.
 * <code>obj</code> must be either a  {@link BigFraction} object or a
 * {@link BigInteger} object or a {@link Number} object. Any other type of
 * object will result in an {@link IllegalArgumentException} being thrown.
 *
 * @param obj the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 * @throws MathIllegalArgumentException if <code>obj</code> is not a valid type.
 */
@Override
public StringBuffer format(final Object obj,
                           final StringBuffer toAppendTo, final FieldPosition pos) {

    final StringBuffer ret;
    if (obj instanceof BigFraction) {
        ret = format((BigFraction) obj, toAppendTo, pos);
    } else if (obj instanceof BigInteger) {
        ret = format(new BigFraction((BigInteger) obj), toAppendTo, pos);
    } else if (obj instanceof Number) {
        ret = format(new BigFraction(((Number) obj).doubleValue()),
                     toAppendTo, pos);
    } else {
        throw new MathIllegalArgumentException(LocalizedFormats.CANNOT_FORMAT_OBJECT_TO_FRACTION);
    }

    return ret;
}
 
Example #10
Source File: CobolDoubleType.java    From legstar-core2 with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <D extends Number> D valueOf(Class < D > clazz, Double value) {
    if (clazz.equals(Double.class)) {
        return (D) value;
    } else if (clazz.equals(Float.class)) {
        return (D) Float.valueOf(value.floatValue());
    } else if (clazz.equals(Short.class)) {
        return (D) Short.valueOf(value.shortValue());
    } else if (clazz.equals(Integer.class)) {
        return (D) Integer.valueOf(value.intValue());
    } else if (clazz.equals(Long.class)) {
        return (D) Long.valueOf(value.longValue());
    } else if (clazz.equals(BigDecimal.class)) {
        return (D) new BigDecimal(value);
    } else if (clazz.equals(BigInteger.class)) {
        return (D) BigInteger.valueOf(value.longValue());
    }
    throw new IllegalArgumentException("Unsupported java type " + clazz);
}
 
Example #11
Source File: DerEncoder.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
static byte[] encode(byte[] signature) {
  // expect the signature to be 64 bytes long
  Preconditions.checkState(signature.length == 64);

  byte[] int1 = new BigInteger(1, Arrays.copyOfRange(signature, 0, 32)).toByteArray();
  byte[] int2 = new BigInteger(1, Arrays.copyOfRange(signature, 32, 64)).toByteArray();
  byte[] der = new byte[6 + int1.length + int2.length];

  // Mark that this is a signature object
  der[0] = DER_TAG_SIGNATURE_OBJECT;
  der[1] = (byte) (der.length - 2);

  // Start ASN1 integer and write the first 32 bits
  der[2] = DER_TAG_ASN1_INTEGER;
  der[3] = (byte) int1.length;
  System.arraycopy(int1, 0, der, 4, int1.length);

  // Start ASN1 integer and write the second 32 bits
  int offset = int1.length + 4;
  der[offset] = DER_TAG_ASN1_INTEGER;
  der[offset + 1] = (byte) int2.length;
  System.arraycopy(int2, 0, der, offset + 2, int2.length);

  return der;
}
 
Example #12
Source File: Expression.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Coerces an integral value (BigInteger) to its corresponding signed
 * representation, if the target type of this expression is signed.
 * @param  b  The BigInteger to be coerced.
 * @return  the value of an integral type coerced to its corresponding
 *  signed integral type, if the target type of this expression is
 *  signed.
 **/
protected BigInteger toSignedTarget (BigInteger b)
{
  if (type ().equals ("short"))
  {
    if (b != null && b.compareTo (sMax) > 0)
      return b.subtract (twoPow16);
  }
  else if (type ().equals ("long"))
  {
    if (b != null && b.compareTo (lMax) > 0)
      return b.subtract (twoPow32);
  }
  else if (type ().equals ("long long"))
  {
    if (b != null && b.compareTo (llMax) > 0)
      return b.subtract (twoPow64);
  }
  return b;
}
 
Example #13
Source File: ProcessDescriptionDecoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private BigInteger decodeSupportedFormats(ComplexDescription.Builder<?, ?> builder, JsonNode node)
        throws DecodingException {
    JsonNode formatsNode = node.path(JSONConstants.FORMATS);
    BigInteger maximumMegabytes = null;
    Format defaultFormat = null;
    List<Format> formats = new ArrayList<>(formatsNode.size());
    for (JsonNode formatNode : formatsNode) {
        Format format = decodeFormat(formatNode);
        formats.add(format);
        if (formatNode.path(JSONConstants.DEFAULT).asBoolean(false)) {
            defaultFormat = format;
        }
        maximumMegabytes = getMaximumMegabytes(maximumMegabytes, formatNode);
    }

    if (defaultFormat == null && !formats.isEmpty()) {
        defaultFormat = formats.iterator().next();
    }
    if (defaultFormat == null) {
        throw new DecodingException("missing default format");
    }
    builder.withDefaultFormat(defaultFormat);
    builder.withSupportedFormat(formats);
    return maximumMegabytes;
}
 
Example #14
Source File: RepLodsdTranslatorTest.java    From binnavi with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadQword() throws InternalTranslationException, InterpreterException {
  interpreter.setRegister("eax", BigInteger.valueOf(0x12345678), OperandSize.DWORD,
      ReilRegisterStatus.DEFINED);
  interpreter.setRegister("esi", BigInteger.valueOf(0x1000), OperandSize.DWORD,
      ReilRegisterStatus.DEFINED);
  interpreter.setRegister("ecx", BigInteger.valueOf(0x2), OperandSize.DWORD,
      ReilRegisterStatus.DEFINED);
  interpreter.setRegister("DF", BigInteger.valueOf(0), OperandSize.BYTE,
      ReilRegisterStatus.DEFINED);

  interpreter.getMemory().store(0x1000, 0x98765432, 4);
  interpreter.getMemory().store(0x1004, 0x55555555, 4);

  final MockInstruction instruction =
      new MockInstruction("rep lodsd", new ArrayList<MockOperandTree>());

  translator.translate(environment, instruction, instructions);

  interpreter.interpret(TestHelpers.createMapping(instructions), BigInteger.valueOf(0x100));

  assertEquals(5, TestHelpers.filterNativeRegisters(interpreter.getDefinedRegisters()).size());

  assertEquals(BigInteger.valueOf(0x55555555), interpreter.getVariableValue("eax"));
  assertEquals(BigInteger.valueOf(0x1008), interpreter.getVariableValue("esi"));
  assertEquals(BigInteger.ZERO, interpreter.getVariableValue("ecx"));

  assertEquals(BigInteger.valueOf(8L), BigInteger.valueOf(interpreter.getMemorySize()));
}
 
Example #15
Source File: JsonRpc2_0RxTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testReplayBlocksObservable() throws Exception {

    List<EthBlock> ethBlocks = Arrays.asList(createBlock(0), createBlock(1), createBlock(2));

    OngoingStubbing<EthBlock> stubbing =
            when(web3jService.send(any(Request.class), eq(EthBlock.class)));
    for (EthBlock ethBlock : ethBlocks) {
        stubbing = stubbing.thenReturn(ethBlock);
    }

    Observable<EthBlock> observable = web3j.replayBlocksObservable(
            new DefaultBlockParameterNumber(BigInteger.ZERO),
            new DefaultBlockParameterNumber(BigInteger.valueOf(2)),
            false);

    CountDownLatch transactionLatch = new CountDownLatch(ethBlocks.size());
    CountDownLatch completedLatch = new CountDownLatch(1);

    List<EthBlock> results = new ArrayList<>(ethBlocks.size());
    Subscription subscription = observable.subscribe(
            result -> {
                results.add(result);
                transactionLatch.countDown();
            },
            throwable -> fail(throwable.getMessage()),
            () -> completedLatch.countDown());

    transactionLatch.await(1, TimeUnit.SECONDS);
    assertThat(results, equalTo(ethBlocks));

    subscription.unsubscribe();

    completedLatch.await(1, TimeUnit.SECONDS);
    assertTrue(subscription.isUnsubscribed());
}
 
Example #16
Source File: PasteGradientDescentPfunc.java    From OSPREY3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void init(ConfSearch scoreConfs, ConfSearch energyConfs, BigInteger numConfsBeforePruning, double targetEpsilon, double targetEnergy, PastePartitionFunction.Result wtResult, boolean useWindowCriterion) {

	if (targetEpsilon <= 0.0 || targetEnergy < 0) {
		throw new IllegalArgumentException("target epsilon and target energy must be greater than zero");
	}

	this.useWindowCriterion = useWindowCriterion;
	this.wtResult = wtResult;
	this.energyConfs = energyConfs;
	this.targetEpsilon = targetEpsilon;
	this.targetEnergy = targetEnergy;

	// init state
	status = Status.Estimating;
	state = new State(numConfsBeforePruning);
	values = Values.makeFullRange();
	// don't explicitly check the pruned confs, just lump them together with the un-enumerated confs
	values.pstar = BigDecimal.ZERO;

	hasEnergyConfs = true;
	hasScoreConfs = true;
	numEnergyConfsEnumerated = 0;
	numScoreConfsEnumerated = 0;

	this.scoreConfs = scoreConfs;
}
 
Example #17
Source File: DatatypeFactory.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Constructor of value spaces that a
 * <code>java.util.GregorianCalendar</code> instance would need to convert to an
 * <code>XMLGregorianCalendar</code> instance.</p>
 *
 * <p><code>XMLGregorianCalendar eon</code> and
 * <code>fractionalSecond</code> are set to <code>null</code></p>
 *
 * <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.</p>
 *
 * @param year of <code>XMLGregorianCalendar</code> to be created.
 * @param month of <code>XMLGregorianCalendar</code> to be created.
 * @param day of <code>XMLGregorianCalendar</code> to be created.
 * @param hour of <code>XMLGregorianCalendar</code> to be created.
 * @param minute of <code>XMLGregorianCalendar</code> to be created.
 * @param second of <code>XMLGregorianCalendar</code> to be created.
 * @param millisecond of <code>XMLGregorianCalendar</code> to be created.
 * @param timezone of <code>XMLGregorianCalendar</code> to be created.
 *
 * @return <code>XMLGregorianCalendar</code> created from specified values.
 *
 * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
 *   as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
 *   or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
 *   as determined by {@link XMLGregorianCalendar#isValid()}.
 */
public XMLGregorianCalendar newXMLGregorianCalendar(
        final int year,
        final int month,
        final int day,
        final int hour,
        final int minute,
        final int second,
        final int millisecond,
        final int timezone) {

        // year may be undefined
        BigInteger realYear = (year != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) year) : null;

        // millisecond may be undefined
        // millisecond must be >= 0 millisecond <= 1000
        BigDecimal realMillisecond = null; // undefined value
        if (millisecond != DatatypeConstants.FIELD_UNDEFINED) {
                if (millisecond < 0 || millisecond > 1000) {
                        throw new IllegalArgumentException(
                                                "javax.xml.datatype.DatatypeFactory#newXMLGregorianCalendar("
                                                + "int year, int month, int day, int hour, int minute, int second, int millisecond, int timezone)"
                                                + "with invalid millisecond: " + millisecond
                                                );
                }

                realMillisecond = BigDecimal.valueOf((long) millisecond).movePointLeft(3);
        }

        return newXMLGregorianCalendar(
                realYear,
                month,
                day,
                hour,
                minute,
                second,
                realMillisecond,
                timezone
        );
}
 
Example #18
Source File: Group.java    From GDH with MIT License 5 votes vote down vote up
/**
 * Initiate a group with a Configuration and a collection of Nodes
 * 
 * @param conf
 *            The Configuration of this Group
 * @param nodes
 *            The participants of this Group
 */
private void initGroup(Configuration conf, Collection<Node> nodes) {
    treeNodes = new TreeSet<>();
    for (Node n : nodes)
        treeNodes.add(n);

    generator = new BigInteger(conf.getGenerator(), 16);
    prime = new BigInteger(conf.getPrime(), 16);
    groupId = hashCode();
}
 
Example #19
Source File: SymmetricRangeTests.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void testToString(String msg, int radix, BigInteger bi, int length, String startsWith, char c) {
    String s = bi.toString(radix);
    if (s.length() != length) {
        throw new RuntimeException(msg + ".length=" + s.length());
    }
    if (!s.startsWith(startsWith)) {
        throw new RuntimeException(msg + "[0]=" + s.substring(0, startsWith.length()));
    }
    for (int i = startsWith.length(); i < s.length(); i++) {
        if (s.charAt(i) != c) {
            throw new RuntimeException(msg + "[" + i + "]='" + s.charAt(i) + "'");
        }
    }
}
 
Example #20
Source File: BNParams.java    From protect with MIT License 5 votes vote down vote up
/**
 * Compute the quadratic character of a, i.e. the legendre symbol of a
 *
 */
private static BigInteger chi_q(BigInteger a, BNParams bn) {

	BigInteger arg = a.mod(bn.p);
	if (arg.equals(BigInteger.ZERO)) {
		System.out.println("argument is zero in F_p!");
		return _0;
	}
	return bn.legendre(arg) == 1 ? _1 : _1.negate();
}
 
Example #21
Source File: CryptoManagerImpl.java    From BiglyBT with GNU General Public License v2.0 5 votes vote down vote up
private
SRPParametersImpl(
	byte[]		_salt,
	BigInteger	_verifier )
{
	salt		= _salt;
	verifier	= _verifier;
}
 
Example #22
Source File: ECKey.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a signature for the supplied contents using the private key
 *
 * @param contents
 *            Contents to be signed
 * @return ECDSA signature
 * @throws ECException
 *             Unable to create signature
 */
public ECDSASignature createSignature(byte[] contents) throws ECException {
	if (privKey == null)
		throw new IllegalStateException("No private key available");
	//
	// Get the double SHA-256 hash of the signed contents
	//
	byte[] contentsHash = Helper.doubleDigest(contents);
	//
	// Create the signature
	//
	BigInteger[] sigs;
	try {
		ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
		ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(privKey, ecParams);
		signer.init(true, privKeyParams);
		sigs = signer.generateSignature(contentsHash);
	} catch (RuntimeException exc) {
		throw new ECException("Exception while creating signature", exc);
	}
	//
	// Create a canonical signature by adjusting the S component to be less
	// than or equal to
	// half the curve order.
	//
	if (sigs[1].compareTo(HALF_CURVE_ORDER) > 0)
		sigs[1] = ecParams.getN().subtract(sigs[1]);
	return new ECDSASignature(sigs[0], sigs[1]);
}
 
Example #23
Source File: BigIntegers.java    From TorrentEngine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return a random BigInteger not less than 'min' and not greater than 'max'
 * 
 * @param min the least value that may be generated
 * @param max the greatest value that may be generated
 * @param random the source of randomness
 * @return a random BigInteger value in the range [min,max]
 */
public static BigInteger createRandomInRange(
    BigInteger      min,
    BigInteger      max,
    SecureRandom    random)
{
    int cmp = min.compareTo(max);
    if (cmp >= 0)
    {
        if (cmp > 0)
        {
            throw new IllegalArgumentException("'min' may not be greater than 'max'");
        }

        return min;
    }

    if (min.bitLength() > max.bitLength() / 2)
    {
        return createRandomInRange(ZERO, max.subtract(min), random).add(min);
    }

    for (int i = 0; i < MAX_ITERATIONS; ++i)
    {
        BigInteger x = new BigInteger(max.bitLength(), random);
        if (x.compareTo(min) >= 0 && x.compareTo(max) <= 0)
        {
            return x;
        }
    }

    // fall back to a faster (restricted) method
    return new BigInteger(max.subtract(min).bitLength() - 1, random).add(min);
}
 
Example #24
Source File: TlsDHUtils.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public static byte[] calculateDHBasicAgreement(DHPublicKeyParameters publicKey, DHPrivateKeyParameters privateKey)
{
    DHBasicAgreement basicAgreement = new DHBasicAgreement();
    basicAgreement.init(privateKey);
    BigInteger agreementValue = basicAgreement.calculateAgreement(publicKey);

    /*
     * RFC 5246 8.1.2. Leading bytes of Z that contain all zero bits are stripped before it is
     * used as the pre_master_secret.
     */
    return BigIntegers.asUnsignedByteArray(agreementValue);
}
 
Example #25
Source File: IPAddressSection.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
@Override
protected IPAddressSeqRangePrefixSpliterator<S> createSpliterator(
		S split, 
		boolean isLowest,
		Function<S, BigInteger> sizer,
		Predicate<S> downSizer,
		ToLongFunction<S> longSizer) {
	return new IPAddressSeqRangePrefixSpliterator<S>(split, splitter, (SeqRangeIteratorProvider<S, S>) iteratorProvider, isLowest, sizer, downSizer, longSizer);
}
 
Example #26
Source File: Crowdsale.java    From nuls with MIT License 5 votes vote down vote up
public Crowdsale(BigInteger rate, Address wallet, Address token) {
    require(rate != null && rate.compareTo(BigInteger.ZERO) > 0);
    require(wallet != null);
    require(token != null);

    this.rate = rate;
    this.wallet = wallet;
    this.token = token;
}
 
Example #27
Source File: RSAPublicKeyImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate a new RSAPublicKey from the specified type and components.
 * Used by SunPKCS11 provider.
 */
public static RSAPublicKey newKey(KeyType type,
        AlgorithmParameterSpec params, BigInteger n, BigInteger e)
        throws InvalidKeyException {
    AlgorithmId rsaId = RSAUtil.createAlgorithmId(type, params);
    return new RSAPublicKeyImpl(rsaId, n, e);
}
 
Example #28
Source File: PostgreSQLCommentNotificationParser.java    From binnavi with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the {@link PGNotification} notifications from the database back end for local
 * instruction comments by using a regular expression. If the regular expression matches the
 * supplied {@link PGNotification} notification, it is determined if the instruction in the
 * notification is currently loaded, and if a {@link CommentNotificationContainer} with the data
 * from the notification is returned.
 *
 * @param notification The {@link PGNotification} from the PostgreSQL database server.
 * @param provider The {@link SQLProvider} which is used to communicate with the database.
 */
static CommentNotification processNodeLocalInstructionCommentNotification(
    final PGNotification notification, final SQLProvider provider) {
  final Matcher instructionMatcher =
      INSTRUCTION_LOCAL_PATTERN.matcher(notification.getParameter());
  final boolean instructionMatchFound = instructionMatcher.find();

  if (!instructionMatchFound) {
    return null;
  }

  final Integer moduleId = Integer.parseInt(instructionMatcher.group(3));
  final Integer nodeId = Integer.parseInt(instructionMatcher.group(4));
  final BigInteger notificationInstructionAddress = new BigInteger(instructionMatcher.group(6));
  final Integer commentId = instructionMatcher.group(7).equals("null") ? null
      : Integer.parseInt(instructionMatcher.group(7));

  final INaviModule module = provider.findModule(moduleId);
  if ((module == null) || !module.isLoaded()) {
    return null;
  }
  final IAddress address = new CAddress(notificationInstructionAddress);
  final INaviInstruction instruction = InstructionCache.get(provider).getInstructionByAddress(
      address, module.getConfiguration().getId());
  if (instruction == null) {
    return null;
  }
  final INaviCodeNode codeNode = (INaviCodeNode) NodeCache.get(provider).getNodeById(nodeId);
  if (codeNode == null) {
    return null;
  }

  final CommentOperation operation =
      commentId == null ? CommentOperation.DELETE : CommentOperation.APPEND;

  return new InstructionCommentNotificationContainer(instruction, codeNode, operation,
      CommentScope.LOCAL, commentId);
}
 
Example #29
Source File: DefaultSensitiveStringCodec.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public String encode(String secret) throws Exception {
   SecretKeySpec key = new SecretKeySpec(internalKey, "Blowfish");

   Cipher cipher = Cipher.getInstance("Blowfish");
   cipher.init(Cipher.ENCRYPT_MODE, key);
   byte[] encoding = cipher.doFinal(secret.getBytes());
   BigInteger n = new BigInteger(encoding);
   return n.toString(16);
}
 
Example #30
Source File: BigIntegerGene.java    From jenetics with Apache License 2.0 5 votes vote down vote up
static ISeq<BigIntegerGene> seq(
	final BigInteger minimum,
	final BigInteger maximum,
	final int length
) {
	Requires.positive(length);

	final Random r = random();

	return MSeq.<BigIntegerGene>ofLength(length)
		.fill(() -> new BigIntegerGene(
			random.nextBigInteger(minimum, maximum, r), minimum, maximum))
		.toISeq();
}