List of usage examples for java.math BigInteger toByteArray
public byte[] toByteArray()
From source file:org.openhie.openempi.recordlinkage.protocols.ThreeThirdPartyPRLProtocolBase.java
public void testBFReencoding(int leftPersonMatchRequestId, int rightPersonMatchRequestId, boolean measurement) throws ApplicationException { PersonMatchRequest leftPersonMatchRequest = personMatchRequestDao .getPersonMatchRequest(leftPersonMatchRequestId); PersonMatchRequest rightPersonMatchRequest = personMatchRequestDao .getPersonMatchRequest(rightPersonMatchRequestId); int leftDhSecret = leftPersonMatchRequest.getDhSecret(); DiffieHellmanKeyExchange dhkeLeft = new DiffieHellmanKeyExchange(leftDhSecret); BigInteger dhPublicKeyLeft = dhkeLeft.computePublicKey(); byte[] dhPublicKeyEncLeft = dhPublicKeyLeft.toByteArray(); if (!measurement) Assert.assertArrayEquals(dhPublicKeyEncLeft, leftPersonMatchRequest.getDhPublicKey()); int rightDhSecret = rightPersonMatchRequest.getDhSecret(); DiffieHellmanKeyExchange dhkeRight = new DiffieHellmanKeyExchange(rightDhSecret); BigInteger dhPublicKeyRight = dhkeRight.computePublicKey(); byte[] dhPublicKeyEncRight = dhPublicKeyRight.toByteArray(); if (!measurement) Assert.assertArrayEquals(dhPublicKeyEncRight, rightPersonMatchRequest.getDhPublicKey()); int sharedSecretLeft = dhkeLeft.computeSharedSecret(dhPublicKeyEncRight); int sharedSecretRight = dhkeRight.computeSharedSecret(dhPublicKeyEncLeft); if (!measurement) Assert.assertEquals(sharedSecretLeft, sharedSecretRight); BloomFilterParameterAdvice leftBfpa = getBloomFilterParameterAdviceForRightSide(leftPersonMatchRequest, rightPersonMatchRequest);//from www . ja v a2s . com handleBloomFilterParameterAdvice(leftPersonMatchRequest.getBlockingServiceName(), leftPersonMatchRequest.getMatchingServiceName(), Constants.DEFAULT_ADMIN_USERNAME, Constants.DEFAULT_ADMIN_PASSWORD, Constants.DEFAULT_ADMIN_USERNAME, Constants.DEFAULT_ADMIN_PASSWORD, leftPersonMatchRequest.getDataset(), leftPersonMatchRequest.getDataset(), rightPersonMatchRequest.getDataset(), leftBfpa.getColumnMatchInformation(), leftBfpa.getMatchPairStatHalves(), null, sharedSecretLeft, true, Constants.LOCALHOST_IP_ADDRESS); BloomFilterParameterAdvice rightBfpa = getBloomFilterParameterAdviceForRightSide(rightPersonMatchRequest, leftPersonMatchRequest); handleBloomFilterParameterAdvice(rightPersonMatchRequest.getBlockingServiceName(), rightPersonMatchRequest.getMatchingServiceName(), Constants.DEFAULT_ADMIN_USERNAME, Constants.DEFAULT_ADMIN_PASSWORD, Constants.DEFAULT_ADMIN_USERNAME, Constants.DEFAULT_ADMIN_PASSWORD, rightPersonMatchRequest.getDataset(), rightPersonMatchRequest.getDataset(), leftPersonMatchRequest.getDataset(), rightBfpa.getColumnMatchInformation(), rightBfpa.getMatchPairStatHalves(), null, measurement ? sharedSecretLeft : sharedSecretRight, false, Constants.LOCALHOST_IP_ADDRESS); }
From source file:org.apache.accumulo.pig.Bytes.java
/** * Iterate over keys within the passed inclusive range. *///from w ww. ja v a2 s . c om 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; } }; }
From source file:NaraePreference.java
public void put(String key, BigInteger value) { editor.putString(key, Arrays.toString(value.toByteArray())); editor.commit();//from w w w . jav a2s.co m keylist.add(key); }
From source file:org.openhie.openempi.recordlinkage.protocols.ThreeThirdPartyPRLProtocolBase.java
public void testPMLinkRecords(int leftDatasetId, int rightDatasetId, String blockingServiceName, String matchingServiceName) throws ApplicationException { long startTime = System.currentTimeMillis(); log.warn("PAM EM calculation Start: " + startTime); SecureRandom rnd = new SecureRandom(); PersonManagerService personManagerService = Context.getPersonManagerService(); Dataset leftDataset = personManagerService.getDatasetById(leftDatasetId); int leftNonce = rnd.nextInt(); DiffieHellmanKeyExchange dhkeLeft = new DiffieHellmanKeyExchange(leftNonce); BigInteger dhPublicKeyLeft = dhkeLeft.computePublicKey(); PersonMatchRequest leftPersonMatchRequest = createPersonMatchRequest(leftDataset, dhPublicKeyLeft.toByteArray(), Constants.LOCALHOST_IP_ADDRESS, blockingServiceName, matchingServiceName);/* w ww .j a v a2 s .c om*/ leftPersonMatchRequest = personMatchRequestDao.addPersonMatchRequest(leftPersonMatchRequest); Dataset rightDataset = personManagerService.getDatasetById(rightDatasetId); int rightNonce = rnd.nextInt(); DiffieHellmanKeyExchange dhkeRight = new DiffieHellmanKeyExchange(rightNonce); BigInteger dhPublicKeyRight = dhkeRight.computePublicKey(); PersonMatchRequest rightPersonMatchRequest = createPersonMatchRequest(rightDataset, dhPublicKeyRight.toByteArray(), Constants.LOCALHOST_IP_ADDRESS, blockingServiceName, matchingServiceName); rightPersonMatchRequest = personMatchRequestDao.addPersonMatchRequest(rightPersonMatchRequest); linkRecords(leftPersonMatchRequest, rightPersonMatchRequest, ComponentType.PARAMETER_MANAGER_MODE, null); long endTime = System.currentTimeMillis(); log.warn("PAM EM calculation End: " + endTime + ", elapsed: " + (endTime - startTime)); }
From source file:com.chinamobile.bcbsp.util.Bytes.java
/** * Split passed range. Expensive operation relatively. Uses BigInteger math. * Useful splitting ranges for MapReduce jobs. * * @param a/*w w w . j a v a2s. c o m*/ * Beginning of range * @param b * End of range * @param num * Number of times to split range. Pass 1 if you want to split the * range in two; i.e. one split. * @return Array of dividing values */ public static byte[][] split(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 }; BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } byte[][] result = new byte[num + 2][]; result[0] = a; for (int i = 1; i <= num; i++) { 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); } result[i] = padded; } result[num + 1] = b; return result; }
From source file:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java
/** * This method generates an OCSP Request to be sent to an OCSP endpoint. * * @param issuerCert is the Certificate of the Issuer of the peer certificate we are interested in. * @param serialNumber of the peer certificate. * @return generated OCSP request./* ww w. j a va 2 s .c o m*/ * @throws CertificateVerificationException * */ private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws CertificateVerificationException { //TODO: Have to check if this is OK with synapse implementation. //Add provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); try { byte[] issuerCertEnc = issuerCert.getEncoded(); X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc); DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(); // CertID structure is used to uniquely identify certificates that are the subject of // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560 CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder, serialNumber); // basic request generation with nonce OCSPReqBuilder builder = new OCSPReqBuilder(); builder.addRequest(id); // create details for nonce extension. The nonce extension is used to bind // a request to a response to prevent replay attacks. As the name implies, // the nonce value is something that the client should only use once within a reasonably small period. BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); //to create the request Extension builder.setRequestExtensions(new Extensions(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce.toByteArray())))); return builder.build(); } catch (Exception e) { throw new CertificateVerificationException("Cannot generate OSCP Request with the given certificate", e); } }
From source file:co.rsk.mine.BlockToMineBuilder.java
private BlockHeader createHeader(Block newBlockParent, List<BlockHeader> uncles, List<Transaction> txs, Coin minimumGasPrice) {// www . ja va 2s . c om final byte[] unclesListHash = HashUtil.keccak256(BlockHeader.getUnclesEncodedEx(uncles)); final long timestampSeconds = clock.calculateTimestampForChild(newBlockParent); // Set gas limit before executing block BigInteger minGasLimit = BigInteger.valueOf(miningConfig.getGasLimit().getMininimum()); BigInteger targetGasLimit = BigInteger.valueOf(miningConfig.getGasLimit().getTarget()); BigInteger parentGasLimit = new BigInteger(1, newBlockParent.getGasLimit()); BigInteger gasUsed = BigInteger.valueOf(newBlockParent.getGasUsed()); boolean forceLimit = miningConfig.getGasLimit().isTargetForced(); BigInteger gasLimit = gasLimitCalculator.calculateBlockGasLimit(parentGasLimit, gasUsed, minGasLimit, targetGasLimit, forceLimit); final BlockHeader newHeader = new BlockHeader(newBlockParent.getHash().getBytes(), unclesListHash, miningConfig.getCoinbaseAddress().getBytes(), new Bloom().getData(), new byte[] { 1 }, newBlockParent.getNumber() + 1, gasLimit.toByteArray(), 0, timestampSeconds, new byte[] {}, new byte[] {}, new byte[] {}, new byte[] {}, minimumGasPrice.getBytes(), CollectionUtils.size(uncles)); newHeader.setDifficulty(difficultyCalculator.calcDifficulty(newHeader, newBlockParent.getHeader())); newHeader.setTransactionsRoot(Block.getTxTrie(txs).getHash().getBytes()); return newHeader; }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testManualEncryption() throws Exception { while (true) { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); SecureRandom random = new SecureRandom(); int keySize = 128; keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; LOG.debug("private key modulus: " + rsaPrivateKey.getModulus()); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; LOG.debug("public key modulus: " + rsaPublicKey.getModulus()); LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent()); LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); int dataSize = keySize / 8 - 11; byte[] data1 = new byte[dataSize]; for (int i = 0; i < data1.length; i++) { data1[i] = 0x00;/* w w w. j av a 2s. c o m*/ } byte[] data2 = new byte[dataSize]; for (int i = 0; i < data2.length; i++) { data2[i] = 0x00; } data2[data2.length - 1] = 0x07; byte[] signatureValue1 = cipher.doFinal(data1); LOG.debug("signature size: " + signatureValue1.length); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] signatureValue2 = cipher.doFinal(data2); BigInteger sigBigInt1 = new BigInteger(signatureValue1); BigInteger sigBigInt2 = new BigInteger(signatureValue2); BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); LOG.debug("msg big int: " + msgBigInt1); byte[] msgBytes1 = msgBigInt1.toByteArray(); LOG.debug("original message size: " + msgBytes1.length); LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1))); LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray()))); LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100)); LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100)); // BigInteger.pow offers a very naive implementation LOG.debug("calculating s1^e..."); BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s1^e: " + s1_e); LOG.debug("calculating s2^e..."); BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s2^e: " + s2_e); LOG.debug("calculating GCD..."); LOG.debug("msg1: " + msgBigInt1); LOG.debug("msg2: " + msgBigInt2); BigInteger a = s1_e.subtract(msgBigInt1); BigInteger b = s2_e.subtract(msgBigInt2); LOG.debug("a: " + a); LOG.debug("b: " + b); BigInteger candidateModulus = a.gcd(b); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length); BigInteger s_e = s1_e.multiply(s2_e); BigInteger m = msgBigInt1.multiply(msgBigInt2); while (false == rsaPublicKey.getModulus().equals(candidateModulus)) { LOG.error("incorrect candidate modulus"); LOG.debug("modulus | candidate modulus: " + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO)); s_e = s_e.multiply(s1_e); m = m.multiply(msgBigInt1); BigInteger n1 = s_e.subtract(m).gcd(a); BigInteger n2 = s_e.subtract(m).gcd(b); candidateModulus = n1.gcd(n2); // try / 2 LOG.debug("new modulus: " + n1); LOG.debug("new modulus: " + n2); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("actual mod: " + rsaPublicKey.getModulus()); } } }
From source file:org.apache.hadoop.hive.serde2.teradata.TeradataBinaryDataOutputStream.java
/** * Write DECIMAL(P, S).//from w w w . j a va2 s .c om * The representation of decimal in Teradata binary format is: * the byte number to read is decided solely by the precision(P), * HiveDecimal is constructed through the byte array and scale. * the rest of byte will use 0x00 to pad (positive) and use 0xFF to pad (negative). * the null DECIMAL will use 0x00 to pad. * * @param writable the writable * @param byteNum the byte num * @throws IOException the io exception */ public void writeDecimal(HiveDecimalWritable writable, int byteNum, int scale) throws IOException { if (writable == null) { byte[] pad = new byte[byteNum]; write(pad); return; } // since the HiveDecimal will auto adjust the scale to save resource // we need to adjust it back otherwise the output bytes will be wrong int hiveScale = writable.getHiveDecimal().scale(); BigInteger bigInteger = writable.getHiveDecimal().unscaledValue(); if (hiveScale < scale) { BigInteger multiplicand = new BigInteger("1" + join("", Collections.nCopies(scale - hiveScale, "0"))); bigInteger = bigInteger.multiply(multiplicand); } byte[] content = bigInteger.toByteArray(); int signBit = content[0] >> 7 & 1; ArrayUtils.reverse(content); write(content); if (byteNum > content.length) { byte[] pad; if (signBit == 0) { pad = new byte[byteNum - content.length]; } else { pad = new byte[byteNum - content.length]; Arrays.fill(pad, (byte) 255); } write(pad); } }
From source file:egovframework.rte.fdl.idgnr.impl.EgovUUIdGnrService.java
/** * @original This method transforms Java BigInteger * type into a fix size byte array * containing the two's-complement * representation of the integer. The * byte array will be in big-endian * byte-order: the most significant byte * is in the zeroth element. If the * destination array is shorter then the * BigInteger.toByteArray(), the the less * significant bytes will be copy only. * If the destination array is longer * then the BigInteger.toByteArray(), * destination will be left padded with * zeros./* w w w. j a v a 2s.co m*/ * @param bigInt * Java BigInteger type * @param destination * destination array */ private void toFixSizeByteArray(BigInteger bigInt, byte[] destination) { // Prepare the destination for (int i = 0; i < destination.length; i++) { destination[i] = 0x00; } // Convert the BigInt to a byte array byte[] source = bigInt.toByteArray(); // Copy only the fix size length if (source.length <= destination.length) { for (int i = 0; i < source.length; i++) { destination[destination.length - source.length + i] = source[i]; } } else { for (int i = 0; i < destination.length; i++) { destination[i] = source[source.length - destination.length + i]; } } }