public void sm2Verify(byte md[], ECPoint userKey, BigInteger r, BigInteger s, SM2Result sm2Result) { sm2Result.R = null; BigInteger e = new BigInteger(1, md); BigInteger t = r.add(s).mod(ecc_n); if (t.equals(BigInteger.ZERO)) { return; } else { ECPoint x1y1 = ecc_point_g.multiply(sm2Result.s); System.out.println("X0: " + x1y1.getX().toBigInteger().toString(16)); System.out.println("Y0: " + x1y1.getY().toBigInteger().toString(16)); System.out.println(""); x1y1 = x1y1.add(userKey.multiply(t)); System.out.println("X1: " + x1y1.getX().toBigInteger().toString(16)); System.out.println("Y1: " + x1y1.getY().toBigInteger().toString(16)); System.out.println(""); sm2Result.R = e.add(x1y1.getX().toBigInteger()).mod(ecc_n); System.out.println("R: " + sm2Result.R.toString(16)); return; } }
@SuppressWarnings("unchecked") @Override public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) { if (clazz == BigDecimal.class) { return (Codec<T>) bigDecimalCodec; } if (clazz == BigInteger.class) { return (Codec<T>) bigIntegerCodec; } if (clazz == InetAddress.class || clazz == Inet4Address.class || clazz == Inet6Address.class) { return (Codec<T>) inetAddressCodec; } if (clazz.isArray()) { return (Codec<T>) arrayCodec; } return null; }
/** * Experimental. Returns the value from a storage position at a given address * @param address Address * @param position Storage position * @return Value from storage position */ public String getStorageAt(String address, BigInteger position) { HttpGet get = new HttpGet(PUBLIC_URL + "?module=proxy&action=eth_getStorageAt&address=" + address + "&position=" + "0x" + position.toString(16) + "&tag=latest" + "&apikey=" + API_KEY); String response = null; try(CloseableHttpResponse httpResponse = httpClient.execute(get)) { HttpEntity httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity); } catch (IOException e) { e.printStackTrace(); } @SuppressWarnings("rawtypes") ArrayList<CustomNameValuePair<String, CustomNameValuePair>> a = Utility.evaluateExpression(response); for(int j = 0; j < a.size(); j++) if(a.get(j).getName().toString().equals("result")) return a.get(j).getValue().toString(); return null; // Null should not be expected when API is functional }
@Override public PrivateKey parsePrivateKey(byte[] encodedKey) throws GeneralSecurityException { long now = System.currentTimeMillis(); if (encodedKey.length != privateKeyBytes) throw new GeneralSecurityException(); BigInteger d = new BigInteger(1, encodedKey); // Positive signum // Verify that the private value is < n if (d.compareTo(params.getN()) >= 0) throw new GeneralSecurityException(); // Construct a private key from the private value and the params ECPrivateKeyParameters k = new ECPrivateKeyParameters(d, params); PrivateKey p = new Sec1PrivateKey(k, keyBits); long duration = System.currentTimeMillis() - now; if (LOG.isLoggable(INFO)) LOG.info("Parsing private key took " + duration + " ms"); return p; }
private BigInteger calculateE(BigInteger n, byte[] message) { if (n.bitLength() >= message.length * 8) { return new BigInteger(1, message); } else { byte[] trunc = new byte[n.bitLength() / 8]; System.arraycopy(message, 0, trunc, 0, trunc.length); return new BigInteger(1, trunc); } }
public void testItem_0798() { boolean caught; caught = false; try { rc_BigDecimal = new BigDecimal(new java.math.BigInteger("32"), 0, new MathContext("precision=1 roundingMode=UNNECESSARY")); } catch (java.lang.ArithmeticException e) { caught = true; } Assert.assertEquals("91.94630872483222%", true, caught); }
public ByzantiumConfig(BlockchainConfig parent) { super(parent); constants = new ConstantsAdapter(super.getConstants()) { private final BigInteger BLOCK_REWARD = new BigInteger("3000000000000000000"); @Override public BigInteger getBLOCK_REWARD() { return BLOCK_REWARD; } }; }
@GwtIncompatible // TODO @AndroidIncompatible // slow public void testDivNonZeroExact() { boolean isAndroid = System.getProperties().getProperty("java.runtime.name").contains("Android"); for (BigInteger p : NONZERO_BIGINTEGER_CANDIDATES) { for (BigInteger q : NONZERO_BIGINTEGER_CANDIDATES) { if (isAndroid && p.equals(BAD_FOR_ANDROID_P) && q.equals(BAD_FOR_ANDROID_Q)) { // https://code.google.com/p/android/issues/detail?id=196555 continue; } if (isAndroid && p.equals(BAD_FOR_GINGERBREAD_P) && q.equals(BAD_FOR_GINGERBREAD_Q)) { // Works fine under Marshmallow, so I haven't filed a bug. continue; } boolean dividesEvenly = p.remainder(q).equals(ZERO); try { BigInteger quotient = BigIntegerMath.divide(p, q, UNNECESSARY); BigInteger undone = quotient.multiply(q); if (!p.equals(undone)) { failFormat("expected %s.multiply(%s) = %s; got %s", quotient, q, p, undone); } assertTrue(dividesEvenly); } catch (ArithmeticException e) { assertFalse(dividesEvenly); } } } }
/** * This the slower miner version which uses only cache thus taking much less memory than * regular {@link #mine} method */ public long mineLight(long fullSize, final byte[][] cache, byte[] blockHeaderTruncHash, long difficulty) { BigInteger target = valueOf(2).pow(256).divide(valueOf(difficulty)); long nonce = new Random().nextLong(); while(!Thread.currentThread().isInterrupted()) { nonce++; Pair<byte[], byte[]> pair = hashimotoLight(fullSize, cache, blockHeaderTruncHash, longToBytes(nonce)); BigInteger h = new BigInteger(1, pair.getRight() /* ?? */); if (h.compareTo(target) < 0) break; } return nonce; }
@Override protected P11Identity generateRSAKeypair0(int keysize, BigInteger publicExponent, String label, P11NewKeyControl control) throws P11TokenException { KeyPair keypair; try { keypair = KeyUtil.generateRSAKeypair(keysize, publicExponent, random); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException ex) { throw new P11TokenException(ex.getMessage(), ex); } return saveP11Entity(keypair, label); }
public static void main(String[] args) { Scanner input = new Scanner(System.in); /* Plot Pascal triangle of given size */ // take the size of the triangle (max 100) int triangleSize = Integer.parseInt(input.nextLine()); // Make jagged array for the triangle of type BigInteger BigInteger[][] pascTriangle = new BigInteger[triangleSize][]; // Create the first element of the triangle pascTriangle[0] = new BigInteger[] {BigInteger.ONE}; for (int row = 1; row < triangleSize; row++) { // create next row with length +1 pascTriangle[row] = new BigInteger[row + 1]; // for current row create first element = 1 pascTriangle[row][0] = BigInteger.ONE; // find the middle of the row int middle = (pascTriangle[row].length - 1) /2; // loop to the end of the current row for (int col = 1; col < pascTriangle[row].length; col++) { // if the index is less or equal to the middle index if (col <= middle){ // sum the above row members and save result at current possition pascTriangle[row][col] = (pascTriangle[row - 1][col - 1]).add(pascTriangle[row - 1][col]); } else { // else, copy forward previous members // "row - col" is in fact "(length - 1) - col" or "(last index) - current iteration" pascTriangle[row][col] = pascTriangle[row][row - col]; } } } // print the triangle for (int row = 0; row < pascTriangle.length; row++) { for (int col = 0; col < pascTriangle[row].length; col++) { System.out.print(pascTriangle[row][col] + " "); } System.out.println(); } }
public static String getMD5(String val) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(val.getBytes("UTF-8")); byte[] magnitude = digest.digest(); BigInteger bi = new BigInteger(1, magnitude); return String.format("%0" + (magnitude.length << 1) + "x", bi); }
@Test public void toBigNumbers() throws IOException { final VPackBuilder builder = new VPackBuilder(); { builder.add(ValueType.OBJECT); builder.add("bi", BigInteger.valueOf(2)); builder.add("bd", BigDecimal.valueOf(3.75)); builder.close(); } final VPackSlice vpack = builder.slice(); final TestEntityBigNumber entity = mapper.readValue(vpack.getBuffer(), TestEntityBigNumber.class); assertThat(entity, is(notNullValue())); assertThat(entity.bi, is(BigInteger.valueOf(2))); assertThat(entity.bd, is(BigDecimal.valueOf(3.75))); }
@Override public Pair<Boolean, byte[]> execute(byte[] data) { if (data == null) return Pair.of(true, EMPTY_BYTE_ARRAY); int baseLen = parseLen(data, 0); int expLen = parseLen(data, 1); int modLen = parseLen(data, 2); BigInteger base = parseArg(data, ARGS_OFFSET, baseLen); BigInteger exp = parseArg(data, addSafely(ARGS_OFFSET, baseLen), expLen); BigInteger mod = parseArg(data, addSafely(addSafely(ARGS_OFFSET, baseLen), expLen), modLen); // check if modulus is zero if (isZero(mod)) return Pair.of(true, EMPTY_BYTE_ARRAY); byte[] res = stripLeadingZeroes(base.modPow(exp, mod).toByteArray()); // adjust result to the same length as the modulus has if (res.length < modLen) { byte[] adjRes = new byte[modLen]; System.arraycopy(res, 0, adjRes, modLen - res.length, res.length); return Pair.of(true, adjRes); } else { return Pair.of(true, res); } }
public static BigInteger decodeBigInteger(byte[] data, int index) { final int length = calculateLength(data, index); byte[] valueBytes = new byte[length]; System.arraycopy(data, index, valueBytes, 0, length); return new BigInteger(1, valueBytes); }
/** * @param number should be in form '0x34fabd34....' * * @return String */ public static BigInteger unifiedNumericToBigInteger(String number) { boolean match = Pattern.matches("0[xX][0-9a-fA-F]+", number); if (!match) { return (new BigInteger(number)); } else { number = number.substring(2); number = number.length() % 2 != 0 ? "0".concat(number) : number; byte[] numberBytes = Hex.decode(number); return (new BigInteger(1, numberBytes)); } }
public BigInteger convertInput( byte[] in, int inOff, int inLen) { if (inLen > (getInputBlockSize() + 1)) { throw new DataLengthException("input too large for RSA cipher."); } else if (inLen == (getInputBlockSize() + 1) && !forEncryption) { throw new DataLengthException("input too large for RSA cipher."); } byte[] block; if (inOff != 0 || inLen != in.length) { block = new byte[inLen]; System.arraycopy(in, inOff, block, 0, inLen); } else { block = in; } BigInteger res = new BigInteger(1, block); if (res.compareTo(key.getModulus()) >= 0) { throw new DataLengthException("input too large for RSA cipher."); } return res; }
private ECCurve(final BigInteger Q, final BigInteger A, final BigInteger B, final BigInteger N, final byte[] G) { this.Q = Q; this.A = new ECFieldElement(A, this); this.B = new ECFieldElement(B, this); this.N = N; Infinity = new ECPoint(new byte[1], null, null, this); this.G = ECPoint.DecodePoint(G, this); }
static int getRSAKeyLength(PublicKey key) { BigInteger modulus; if (key instanceof RSAPublicKey) { modulus = ((RSAPublicKey)key).getModulus(); } else { RSAPublicKeySpec spec = getRSAPublicKeySpec(key); modulus = spec.getModulus(); } return modulus.bitLength(); }
public static void checkCanonicalSubnetAddressRange(IpAddress lowerBound, IpAddress upperBound) { BigInteger size = getRangeSize(lowerBound, upperBound); boolean isPowersOfTwo = size.bitCount() == 1; if (! isPowersOfTwo) { throw new ValueException("サイズが2の冪になっていません."); } if (! lowerBound.toBigInteger().mod(size).equals(BigInteger.ZERO)) { throw new ValueException("始点アドレス(ネットワーク アドレス)がサイズの倍数になっていません."); } }
public TransactionInfo(byte[] rlp) { RLPList params = RLP.decode2(rlp); RLPList txInfo = (RLPList) params.get(0); RLPList receiptRLP = (RLPList) txInfo.get(0); RLPItem blockHashRLP = (RLPItem) txInfo.get(1); RLPItem indexRLP = (RLPItem) txInfo.get(2); receipt = new TransactionReceipt(receiptRLP.getRLPData()); blockHash = blockHashRLP.getRLPData(); if (indexRLP.getRLPData() == null) index = 0; else index = new BigInteger(1, indexRLP.getRLPData()).intValue(); }
public void addmod(cm.aptoide.pt.ethereum.ethereumj.vm.DataWord word1, cm.aptoide.pt.ethereum.ethereumj.vm.DataWord word2) { if (word2.isZero()) { this.data = new byte[32]; return; } BigInteger result = value().add(word1.value()) .mod(word2.value()); this.data = ByteUtil.copyToArray(result.and(MAX_VALUE)); }
public static void testBigIntegerConstructor() { Aprational a = new Aprational(BigInteger.valueOf(5)); assertEquals("5 radix", 10, a.radix()); assertEquals("5 String", "5", a.toString()); a = new Aprational(BigInteger.valueOf(11), 12); assertEquals("11 radix", 12, a.radix()); assertEquals("11 String", "b", a.toString()); }
public static String EncryptedByMD5(String arg) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(arg.getBytes()); return new BigInteger(1,md5.digest()).toString(16); }catch (Exception e){ e.printStackTrace(); throw new IllegalArgumentException("MD5加密失败!"); } }
@Override public BigInteger valInt() { MySQLTime ltime = new MySQLTime(); if (getArg0Date(ltime, MyTime.TIME_NO_ZERO_DATE)) return BigInteger.ZERO; return BigInteger.valueOf(MyTime.calcWeekday(MyTime.calcDaynr(ltime.getYear(), ltime.getMonth(), ltime.getDay()), false)); }
public SecretVoterData(BigInteger x, BigInteger y, byte[] f, byte[][] rc) { this.x = x; this.y = y; this.f = Arrays.copyOf(f, f.length); this.rc = new byte[rc.length][]; for (int i = 0; i < rc.length; i++) { this.rc[i] = Arrays.copyOf(rc[i], rc[i].length); } }
protected String getHistoryId(final ITestNGMethod method, final List<Parameter> parameters) { final MessageDigest digest = getMessageDigest(); final String testClassName = method.getTestClass().getName(); final String methodName = method.getMethodName(); digest.update(testClassName.getBytes(UTF_8)); digest.update(methodName.getBytes(UTF_8)); parameters.stream() .sorted(comparing(Parameter::getName).thenComparing(Parameter::getValue)) .forEachOrdered(parameter -> { digest.update(parameter.getName().getBytes(UTF_8)); digest.update(parameter.getValue().getBytes(UTF_8)); }); final byte[] bytes = digest.digest(); return new BigInteger(1, bytes).toString(16); }
@Test public void mgpOnRage() { MinimumGasPriceCalculator mgpCalculator = new MinimumGasPriceCalculator(); BigInteger prev = BigInteger.valueOf(1000L); BigInteger target = BigInteger.valueOf(995L); BigInteger mgp = mgpCalculator.calculate(prev, target); Assert.assertTrue(target.compareTo(mgp) == 0); }
public DSAPublicKeyParameters( BigInteger y, DSAParameters params) { super(false, params); this.y = y; }
@Test public void testEqualsHashCode() throws Exception { final LiquidityPoint liquidityPoint1 = LiquidityPoint.builder() .inputAmount(BigInteger.ZERO) .outputAmount(BigInteger.ONE) .build(); final LiquidityPoint liquidityPoint2 = LiquidityPoint.builder() .inputAmount(BigInteger.ZERO) .outputAmount(BigInteger.ONE) .build(); assertTrue(liquidityPoint1.equals(liquidityPoint2)); assertTrue(liquidityPoint2.equals(liquidityPoint1)); assertTrue(liquidityPoint1.hashCode() == liquidityPoint2.hashCode()); { final LiquidityPoint liquidityPoint3 = LiquidityPoint.builder() .inputAmount(BigInteger.TEN) .outputAmount(BigInteger.TEN) .build(); assertFalse(liquidityPoint1.equals(liquidityPoint3)); assertFalse(liquidityPoint3.equals(liquidityPoint1)); assertFalse(liquidityPoint1.hashCode() == liquidityPoint3.hashCode()); } }
public void testItem_0113() { rc_BigDecimal = new BigDecimal(new java.math.BigInteger("32"), new MathContext("precision=2147483647 roundingMode=HALF_UP")); Assert.assertEquals("32", rc_BigDecimal.toString()); }
public static void main(String[] args) throws Exception { check(new String(""+Long.MIN_VALUE), Long.MIN_VALUE); check(new String(""+Long.MAX_VALUE), Long.MAX_VALUE); check("10", 10L); check("0x10", 16L); check("0X10", 16L); check("010", 8L); check("#10", 16L); check("+10", 10L); check("+0x10", 16L); check("+0X10", 16L); check("+010", 8L); check("+#10", 16L); check("-10", -10L); check("-0x10", -16L); check("-0X10", -16L); check("-010", -8L); check("-#10", -16L); check(Long.toString(Long.MIN_VALUE), Long.MIN_VALUE); check(Long.toString(Long.MAX_VALUE), Long.MAX_VALUE); checkFailure("0x-10", "Long.decode allows negative sign in wrong position."); checkFailure("0x+10", "Long.decode allows positive sign in wrong position."); checkFailure("+", "Raw plus sign allowed."); checkFailure("-", "Raw minus sign allowed."); checkFailure(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE).toString(), "Out of range"); checkFailure(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE).toString(), "Out of range"); checkFailure("", "Empty String"); try { Long.decode(null); throw new RuntimeException("Long.decode(null) expected to throw NPE"); } catch (NullPointerException npe) {/* Okay */} }
public void testItem_0225() { rc_BigDecimal = new BigDecimal(new java.math.BigInteger("32")); Assert.assertEquals("32", rc_BigDecimal.toString()); }
@Override public BigInteger valInt() { return isNull() ? BigInteger.ZERO : valReal().toBigInteger(); }
public BigInteger getValue() { return value; }
@Test public void testArrayMapTypeField() throws Exception { addFieldTest("abstractMapArray", result -> assertEquals(buildTestString( "$T.newInstance($T.getInstance(), $T.newInstance($T.getInstance(), ($T<$T>) $T[]::new))", AbstractMapJsonDeserializer.class, StringKeyDeserializer.class, ArrayJsonDeserializer.class, StringJsonDeserializer.class, ArrayCreator.class, String.class, String.class), result)); addFieldTest("enumMapArray", result -> assertEquals(buildTestString( "$T.newInstance($T.newInstance($T.class), $T.newInstance($T.getInstance(), ($T<$T>) $T[]::new))", EnumMapJsonDeserializer.class, EnumKeyDeserializer.class, AnEnum.class, ArrayJsonDeserializer.class, IntegerJsonDeserializer.class, ArrayCreator.class, Integer.class, Integer.class), result)); addFieldTest("hashMapArray", result -> assertEquals(buildTestString( "$T.newInstance($T.getInstance(), $T.newInstance($T.getInstance(), ($T<$T>) $T[]::new))", HashMapJsonDeserializer.class, BaseNumberKeyDeserializer.IntegerKeyDeserializer.class, ArrayJsonDeserializer.class, DoubleJsonDeserializer.class, ArrayCreator.class, Double.class, Double.class), result)); addFieldTest("identityHashMapArray", result -> assertEquals(buildTestString( "$T.newInstance($T.getInstance(), $T.newInstance($T.getInstance(), ($T<$T>) $T[]::new))", IdentityHashMapJsonDeserializer.class, BaseNumberKeyDeserializer.LongKeyDeserializer.class, ArrayJsonDeserializer.class, DateJsonDeserializer.class, ArrayCreator.class, Date.class, Date.class), result)); addFieldTest("linkedHashMapArray", result -> assertEquals(buildTestString( "$T.newInstance($T.getInstance(), $T.newInstance($T.newInstance($T.class), ($T<$T>) $T[]::new))", LinkedHashMapJsonDeserializer.class, BaseNumberKeyDeserializer.DoubleKeyDeserializer.class, ArrayJsonDeserializer.class, EnumJsonDeserializer.class, AnEnum.class, ArrayCreator.class, AnEnum.class, AnEnum.class), result)); addFieldTest("mapArray", result -> assertEquals(buildTestString( "$T.newInstance($T.getInstance(), $T.newInstance($T.getInstance(), ($T<$T>) $T[]::new))", MapJsonDeserializer.class, BaseNumberKeyDeserializer.ShortKeyDeserializer.class, ArrayJsonDeserializer.class, SqlTimeJsonDeserializer.class, ArrayCreator.class, Time.class, Time.class), result)); addFieldTest("sortedMapArray", result -> assertEquals(buildTestString( "$T.newInstance($T.getInstance(), $T.newInstance($T.getInstance(), ($T<$T>) $T[]::new))", SortedMapJsonDeserializer.class, StringKeyDeserializer.class, ArrayJsonDeserializer.class, ShortJsonDeserializer.class, ArrayCreator.class, Short.class, Short.class), result)); addFieldTest("treeMapArray", result -> assertEquals(buildTestString( "$T.newInstance($T.getInstance(), $T.newInstance($T.getInstance(), ($T<$T>) $T[]::new))", TreeMapJsonDeserializer.class, StringKeyDeserializer.class, ArrayJsonDeserializer.class, BigIntegerJsonDeserializer.class, ArrayCreator.class, BigInteger.class, BigInteger.class), result)); runTests(); }
public void testItem_0622() { rc_BigDecimal = new BigDecimal(new java.math.BigInteger("32")); Assert.assertEquals("32", rc_BigDecimal.toString()); }
public BigInteger getGasPriceAsInteger() { return (this.getGasPrice() == null) ? null : BigIntegers.fromUnsignedByteArray(this.getGasPrice()); }
public BigInteger getGasLimit() { if (!parsed) rlpParse(); return gasLimit; }
public void testItem_0505() { rc_BigDecimal = new BigDecimal(new java.math.BigInteger("32")); Assert.assertEquals("32", rc_BigDecimal.toString()); }