List of usage examples for java.math BigInteger toByteArray
public byte[] toByteArray()
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
/** * @param originalMessage/*from ww w .j av a 2 s . c om*/ * original message to be changed * @param si * factor * @return Prepared message as byte array */ private byte[] prepareMsg(final BigInteger originalMessage, final BigInteger si) { byte[] msg; BigInteger tmp; // encrypt: si^e mod n tmp = si.modPow(this.pubKey.getPublicExponent(), this.pubKey.getModulus()); // blind: c0*(si^e) mod n // or: m*si mod n (in case of plaintext m_Oracle) tmp = originalMessage.multiply(tmp); tmp = tmp.mod(this.pubKey.getModulus()); // get bytes msg = correctSize(tmp.toByteArray(), this.blockSize, true); return msg; }
From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java
/** * Get the id of other nodes that should have this node in its finger table. For example, for a 16 node ring with base id 8, router * position 0 expects 7, router position 1 expects 6, router position 2 expects 4, and router position 3 expects 0. For more * information, see Chord research paper. * @param idx router position to get expected id for * @return expected id for a specific router position * @throws IllegalArgumentException if {@code idx < 0 || idx > table.size()} (size of table = bit size of base pointer's limit) *//*from w w w. j av a2s . co m*/ public Id getRouterId(int idx) { Validate.inclusiveBetween(0, table.size() - 1, idx); BigInteger data = BigInteger.ONE.shiftLeft(idx); byte[] offsetIdRaw = data.toByteArray(); Id offsetId = new Id(offsetIdRaw, basePtr.getId().getLimitAsByteArray()); Id routerId = Id.subtract(getBaseId(), offsetId); return routerId; }
From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java
/** * Constructs a {@link FingerTable}. All fingers are initialized to * {@code base}./*w w w . j a v a 2s .c o m*/ * * @param basePtr base pointer * @throws NullPointerException if any arguments are {@code null} */ public FingerTable(InternalPointer basePtr) { Validate.notNull(basePtr); Id baseId = basePtr.getId(); Validate.isTrue(IdUtils.isUseableId(baseId)); // make sure satisfies 2^n-1 this.basePtr = basePtr; this.bitCount = IdUtils.getBitLength(baseId); byte[] limit = baseId.getLimitAsByteArray(); table = new ArrayList<>(bitCount); for (int i = 0; i < bitCount; i++) { BigInteger data = BigInteger.ONE.shiftLeft(i); byte[] offsetIdRaw = data.toByteArray(); Id offsetId = new Id(offsetIdRaw, limit); Id expectedId = Id.add(baseId, offsetId); InternalEntry te = new InternalEntry(); te.expectedId = expectedId; te.pointer = basePtr; table.add(te); } }
From source file:com.maverick.ssl.SSLHandshakeProtocol.java
private void onServerHelloDoneMsg() throws SSLException { // Generate the premaster secret calculatePreMasterSecret();/*w w w .j a v a 2s. c o m*/ byte[] secret = null; try { // Encrypt the premaster secret BigInteger input = new BigInteger(1, premasterSecret); PublicKey key = x509.getPublicKey(); if (key instanceof RsaPublicKey) { BigInteger padded = Rsa.padPKCS1(input, 0x02, 128); BigInteger s = Rsa.doPublic(padded, ((RsaPublicKey) key).getModulus(), ((RsaPublicKey) key).getPublicExponent()); secret = s.toByteArray(); } else { throw new SSLException(SSLException.UNSUPPORTED_CERTIFICATE); } } catch (CertificateException ex) { throw new SSLException(SSLException.UNSUPPORTED_CERTIFICATE, ex.getMessage()); } if (secret[0] == 0) { byte[] tmp = new byte[secret.length - 1]; System.arraycopy(secret, 1, tmp, 0, secret.length - 1); secret = tmp; } sendMessage(CLIENT_KEY_EXCHANGE_MSG, secret); // Calculate the master secret calculateMasterSecret(); // #ifdef DEBUG log.debug(Messages.getString("SSLHandshakeProtocol.generatingKeyData")); //$NON-NLS-1$ // #endif // Generate the keys etc and put the cipher into use byte[] keydata; int length = 0; length += pendingCipherSuite.getKeyLength() * 2; length += pendingCipherSuite.getMACLength() * 2; length += pendingCipherSuite.getIVLength() * 2; ByteArrayOutputStream out = new ByteArrayOutputStream(); MD5Digest md5 = new MD5Digest(); SHA1Digest sha1 = new SHA1Digest(); int turn = 0; while (out.size() < length) { md5.reset(); sha1.reset(); for (int i = 0; i <= turn; i++) { sha1.update((byte) ('A' + turn)); } sha1.update(masterSecret, 0, masterSecret.length); sha1.update(serverRandom, 0, serverRandom.length); sha1.update(clientRandom, 0, clientRandom.length); md5.update(masterSecret, 0, masterSecret.length); byte[] tmp = new byte[sha1.getDigestSize()]; sha1.doFinal(tmp, 0); md5.update(tmp, 0, tmp.length); tmp = new byte[md5.getDigestSize()]; md5.doFinal(tmp, 0); // Write out a block of key data out.write(tmp, 0, tmp.length); turn++; } keydata = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(keydata); byte[] encryptKey = new byte[pendingCipherSuite.getKeyLength()]; byte[] encryptIV = new byte[pendingCipherSuite.getIVLength()]; byte[] encryptMAC = new byte[pendingCipherSuite.getMACLength()]; byte[] decryptKey = new byte[pendingCipherSuite.getKeyLength()]; byte[] decryptIV = new byte[pendingCipherSuite.getIVLength()]; byte[] decryptMAC = new byte[pendingCipherSuite.getMACLength()]; try { in.read(encryptMAC); in.read(decryptMAC); in.read(encryptKey); in.read(decryptKey); in.read(encryptIV); in.read(decryptIV); } catch (IOException ex) { throw new SSLException(SSLException.INTERNAL_ERROR, ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage()); } pendingCipherSuite.init(encryptKey, encryptIV, encryptMAC, decryptKey, decryptIV, decryptMAC); currentHandshakeStep = SERVER_HELLO_DONE_MSG; // Send the change cipher spec socket.sendCipherChangeSpec(pendingCipherSuite); // Send the finished msg sendHandshakeFinished(); }
From source file:org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.java
private void prepareEncryptionDictRev2345(String ownerPassword, String userPassword, PDEncryption encryptionDictionary, int permissionInt, PDDocument document, int revision, int length) throws IOException { COSArray idArray = document.getDocument().getDocumentID(); //check if the document has an id yet. If it does not then generate one if (idArray == null || idArray.size() < 2) { MessageDigest md = MessageDigests.getMD5(); BigInteger time = BigInteger.valueOf(System.currentTimeMillis()); md.update(time.toByteArray()); md.update(ownerPassword.getBytes(Charsets.ISO_8859_1)); md.update(userPassword.getBytes(Charsets.ISO_8859_1)); md.update(document.getDocument().toString().getBytes(Charsets.ISO_8859_1)); byte[] id = md.digest(this.toString().getBytes(Charsets.ISO_8859_1)); COSString idString = new COSString(id); idArray = new COSArray(); idArray.add(idString);/*from ww w . ja v a 2 s.co m*/ idArray.add(idString); document.getDocument().setDocumentID(idArray); } COSString id = (COSString) idArray.getObject(0); byte[] ownerBytes = computeOwnerPassword(ownerPassword.getBytes(Charsets.ISO_8859_1), userPassword.getBytes(Charsets.ISO_8859_1), revision, length); byte[] userBytes = computeUserPassword(userPassword.getBytes(Charsets.ISO_8859_1), ownerBytes, permissionInt, id.getBytes(), revision, length, true); encryptionKey = computeEncryptedKey(userPassword.getBytes(Charsets.ISO_8859_1), ownerBytes, null, null, null, permissionInt, id.getBytes(), revision, length, true, false); encryptionDictionary.setOwnerKey(ownerBytes); encryptionDictionary.setUserKey(userBytes); }
From source file:acp.sdk.SecureUtil.java
/** * /*from w w w . java2 s .c o m*/ * @param tPIN * @param iPan * @param publicKey * @return */ public String assymEncrypt(String tPIN, String iPan, RSAPublicKey publicKey) { System.out.println("SampleHashMap::assymEncrypt([" + tPIN + "])"); System.out.println("SampleHashMap::assymEncrypt(PIN =[" + tPIN + "])"); try { int tKeyLength = 1024; int tBlockSize = tKeyLength / 8; byte[] tTemp = null; tTemp = SecureUtil.pin2PinBlockWithCardNO(tPIN, iPan); tTemp = addPKCS1Padding(tTemp, tBlockSize); BigInteger tPlainText = new BigInteger(tTemp); BigInteger tCipherText = tPlainText.modPow(publicKey.getPublicExponent(), publicKey.getModulus()); byte[] tCipherBytes = tCipherText.toByteArray(); int tCipherLength = tCipherBytes.length; if (tCipherLength > tBlockSize) { byte[] tTempBytes = new byte[tBlockSize]; System.arraycopy(tCipherBytes, tCipherLength - tBlockSize, tTempBytes, 0, tBlockSize); tCipherBytes = tTempBytes; } else if (tCipherLength < tBlockSize) { byte[] tTempBytes = new byte[tBlockSize]; for (int i = 0; i < tBlockSize - tCipherLength; i++) { tTempBytes[i] = 0x00; } System.arraycopy(tCipherBytes, 0, tTempBytes, tBlockSize - tCipherLength, tCipherLength); tCipherBytes = tTempBytes; } String tEncryptPIN = new String(SecureUtil.base64Encode(tCipherBytes)); System.out.println("SampleHashMap::assymEncrypt(EncryptCardNo =[" + tEncryptPIN + "])"); return tEncryptPIN; } catch (Exception e) { e.printStackTrace(System.out); return tPIN; } catch (Error e) { e.printStackTrace(System.out); return tPIN; } }
From source file:org.apache.spark.sql.execution.vectorized.ColumnVector.java
public final void putDecimal(int rowId, Decimal value, int precision) { if (precision <= Decimal.MAX_INT_DIGITS()) { putInt(rowId, (int) value.toUnscaledLong()); } else if (precision <= Decimal.MAX_LONG_DIGITS()) { putLong(rowId, value.toUnscaledLong()); } else {/*from ww w . j ava 2 s. c o m*/ BigInteger bigInteger = value.toJavaBigDecimal().unscaledValue(); putByteArray(rowId, bigInteger.toByteArray()); } }
From source file:com.ery.ertc.estorm.util.Bytes.java
/** * Iterate over keys within the passed range. *///from ww w . j av a 2 s . c om public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, 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)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } 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:org.jmangos.realm.network.packet.auth.client.CMD_AUTH_LOGON_CHALLENGE.java
@Override protected void readImpl() throws BufferUnderflowException, RuntimeException { readC();/*from w ww . j a va2 s .c o m*/ if (readC() == WoWAuthResponse.WOW_SUCCESS.getMessageId()) { final SecureRandom random = new SecureRandom(); MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return; } final BigInteger k = new BigInteger("3"); final byte[] Bb = readB(32); final BigInteger g = new BigInteger(readB(readC())); final byte[] Nb = readB(readC()); final byte[] saltb = readB(32); /* byte[] unk3 = */readB(16); readC(); ArrayUtils.reverse(Bb); final BigInteger B = new BigInteger(1, Bb); ArrayUtils.reverse(Bb); ArrayUtils.reverse(Nb); final BigInteger N = new BigInteger(1, Nb); ArrayUtils.reverse(Nb); final BigInteger a = new BigInteger(1, random.generateSeed(19)); final byte[] passhash = sha.digest(this.config.AUTH_LOGIN.toUpperCase().concat(":") .concat(this.config.AUTH_PASSWORD.toUpperCase()).getBytes(Charset.forName("UTF-8"))); sha.update(saltb); sha.update(passhash); final byte[] xhash = sha.digest(); ArrayUtils.reverse(xhash); final BigInteger x = new BigInteger(1, xhash); logger.debug("x:" + x.toString(16).toUpperCase()); final BigInteger v = g.modPow(x, N); logger.debug("v:" + v.toString(16).toUpperCase()); final BigInteger A = g.modPow(a, N); logger.debug("A:" + A.toString(16).toUpperCase()); logger.debug("B:" + B.toString(16).toUpperCase()); this.ahash = A.toByteArray(); ArrayUtils.reverse(this.ahash); sha.update(this.ahash); sha.update(Bb); final byte[] hashu = sha.digest(); ArrayUtils.reverse(hashu); final BigInteger u = new BigInteger(1, hashu); logger.debug("u:" + u.toString(16).toUpperCase()); final BigInteger S = (B.subtract(k.multiply(g.modPow(x, N)))).modPow(a.add(u.multiply(x)), N); final byte[] full_S = S.toByteArray(); ArrayUtils.reverse(full_S); logger.debug("t:" + StringUtils.toHexString(full_S)); final byte[] s1_hash = new byte[16]; final byte[] s2_hash = new byte[16]; for (int i = 0; i < 16; i++) { s1_hash[i] = full_S[i * 2]; s2_hash[i] = full_S[(i * 2) + 1]; } final byte[] t1 = sha.digest(s1_hash); final byte[] t2 = sha.digest(s2_hash); final byte[] vK = new byte[40]; for (int i = 0; i < 20; i++) { vK[i * 2] = t1[i]; vK[(i * 2) + 1] = t2[i]; } byte[] hash = new byte[20]; logger.debug("N:" + N.toString(16).toUpperCase()); hash = sha.digest(Nb); logger.debug("hash:" + new BigInteger(1, hash).toString(16).toUpperCase()); byte[] gH = new byte[20]; sha.update(g.toByteArray()); gH = sha.digest(); for (int i = 0; i < 20; ++i) { hash[i] ^= gH[i]; } byte[] t4 = new byte[20]; t4 = sha.digest(this.config.AUTH_LOGIN.toUpperCase().getBytes(Charset.forName("UTF-8"))); sha.update(hash); logger.debug("hash:" + StringUtils.toHexString(hash)); sha.update(t4); logger.debug("t4:" + StringUtils.toHexString(t4)); sha.update(saltb); logger.debug("saltb:" + StringUtils.toHexString(saltb)); sha.update(this.ahash); logger.debug("ahash:" + StringUtils.toHexString(this.ahash)); sha.update(Bb); logger.debug("Bb:" + StringUtils.toHexString(Bb)); sha.update(vK); logger.debug("vK:" + StringUtils.toHexString(vK)); this.m1 = sha.digest(); sha.update(this.ahash); sha.update(this.m1); sha.update(vK); logger.debug("m1 value" + StringUtils.toHexString(this.m1)); @SuppressWarnings("unused") final byte[] m2 = sha.digest(); final ChannelPipeline pipeline = getClient().getChannel().getPipeline(); ((RealmToAuthChannelHandler) pipeline.getLast()).setSeed(vK); } else { getChannel().getPipeline().remove("handler"); getChannel().getPipeline().remove("eventlog"); getChannel().getPipeline().remove("executor"); getChannel().close(); getChannel().getFactory().releaseExternalResources(); } }
From source file:org.apache.kylin.common.util.Bytes.java
/** * Iterate over keys within the passed range. */// www. j a v a 2s . co m public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, 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)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1L); 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; } }; }