Example usage for org.bouncycastle.util BigIntegers asUnsignedByteArray

List of usage examples for org.bouncycastle.util BigIntegers asUnsignedByteArray

Introduction

In this page you can find the example usage for org.bouncycastle.util BigIntegers asUnsignedByteArray.

Prototype

public static byte[] asUnsignedByteArray(int length, BigInteger value) 

Source Link

Document

Return the passed in value as an unsigned byte array.

Usage

From source file:co.rsk.net.discovery.message.PeerDiscoveryMessage.java

License:Open Source License

public PeerDiscoveryMessage encode(byte[] type, byte[] data, ECKey privKey) {
    /* [1] Calc sha3 - prepare for sig */
    byte[] payload = new byte[type.length + data.length];
    payload[0] = type[0];/*from   w ww  .ja v a2s  . c o  m*/
    System.arraycopy(data, 0, payload, 1, data.length);
    byte[] forSig = HashUtil.keccak256(payload);

    /* [2] Crate signature*/
    ECKey.ECDSASignature ecdsaSignature = privKey.sign(forSig);

    ecdsaSignature.v -= 27;

    byte[] sigBytes = merge(BigIntegers.asUnsignedByteArray(32, ecdsaSignature.r),
            BigIntegers.asUnsignedByteArray(32, ecdsaSignature.s), new byte[] { ecdsaSignature.v });

    // [3] calculate MDC
    byte[] forSha = merge(sigBytes, type, data);

    // wrap all the data in to the packet
    this.mdc = HashUtil.keccak256(forSha);
    this.signature = sigBytes;
    this.type = type;
    this.data = data;

    this.wire = merge(this.mdc, this.signature, this.type, this.data);

    return this;
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.ECAssistant.java

License:Open Source License

public static byte[] encodedField(int length, BigInteger i) {
    return BigIntegers.asUnsignedByteArray(length, i);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.key.ECPrivateKey.java

License:Open Source License

public byte[] dEncoded() {
    return BigIntegers.asUnsignedByteArray(publicKey.point().fieldLength(), d);
}

From source file:COSE.Recipient.java

private byte[] ECDH_GenerateSecret(OneKey key) throws CoseException {
    OneKey epk;/*from ww  w.  j  av  a  2  s.c  o  m*/

    if (senderKey != null) {
        epk = key;
        key = senderKey;
    } else {
        CBORObject cn;
        cn = findAttribute(HeaderKeys.ECDH_SPK);
        if (cn == null) {
            cn = findAttribute(HeaderKeys.ECDH_EPK);
        }
        if (cn == null)
            throw new CoseException("No second party EC key");
        epk = new OneKey(cn);
    }

    if (key.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2)
        throw new CoseException("Not an EC2 Key");
    if (epk.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2)
        throw new CoseException("Not an EC2 Key");
    if (epk.get(KeyKeys.EC2_Curve.AsCBOR()) != key.get(KeyKeys.EC2_Curve.AsCBOR()))
        throw new CoseException("Curves are not the same");

    X9ECParameters p = epk.GetCurve();
    ECDomainParameters parameters = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH());

    ECPoint pubPoint;

    CBORObject y = epk.get(KeyKeys.EC2_Y.AsCBOR());
    byte[] x = epk.get(KeyKeys.EC2_X.AsCBOR()).GetByteString();
    if (y.getType() == CBORType.Boolean) {
        byte[] X = epk.get(KeyKeys.EC2_X.AsCBOR()).GetByteString();
        byte[] rgb = new byte[X.length + 1];
        System.arraycopy(X, 0, rgb, 1, X.length);
        rgb[0] = (byte) (2 + (y.AsBoolean() ? 1 : 0));
        pubPoint = p.getCurve().decodePoint(rgb);
    } else {
        pubPoint = p.getCurve().createPoint(new BigInteger(1, x), new BigInteger(1, y.GetByteString()));
    }

    ECPublicKeyParameters pub = new ECPublicKeyParameters(pubPoint, parameters);
    ECPrivateKeyParameters priv = new ECPrivateKeyParameters(
            new BigInteger(1, key.get(KeyKeys.EC2_D.AsCBOR()).GetByteString()), parameters);
    BasicAgreement e1 = new ECDHBasicAgreement();
    e1.init(priv);

    BigInteger k1 = e1.calculateAgreement(pub);
    return BigIntegers.asUnsignedByteArray((p.getCurve().getFieldSize() + 7) / 8, k1);
}

From source file:de.rub.nds.tlsattacker.attacks.ec.oracles.RealDirectMessageECOracle.java

License:Apache License

@Override
public boolean checkSecretCorrectnes(Point ecPoint, BigInteger secret) {
    ConfigHandler configHandler = new ClientConfigHandler();
    TransportHandler transportHandler = configHandler.initializeTransportHandler(config);
    TlsContext tlsContext = configHandler.initializeTlsContext(config);
    WorkflowExecutor workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext);

    WorkflowTrace trace = tlsContext.getWorkflowTrace();
    ECDHClientKeyExchangeMessage message = (ECDHClientKeyExchangeMessage) trace
            .getFirstHandshakeMessage(HandshakeMessageType.CLIENT_KEY_EXCHANGE);

    // modify public point base X coordinate
    ModifiableBigInteger x = ModifiableVariableFactory.createBigIntegerModifiableVariable();
    x.setModification(BigIntegerModificationFactory.explicitValue(ecPoint.getX()));
    message.setPublicKeyBaseX(x);/*from  w  ww .  j  ava  2s  . c o  m*/

    // modify public point base Y coordinate
    ModifiableBigInteger y = ModifiableVariableFactory.createBigIntegerModifiableVariable();
    y.setModification(BigIntegerModificationFactory.explicitValue(ecPoint.getY()));
    message.setPublicKeyBaseY(y);

    // set explicit premaster secret value (X value of the resulting point
    // coordinate)
    ModifiableByteArray pms = ModifiableVariableFactory.createByteArrayModifiableVariable();
    byte[] explicitePMS = BigIntegers.asUnsignedByteArray(curve.getKeyBits() / 8, secret);
    pms.setModification(ByteArrayModificationFactory.explicitValue(explicitePMS));
    message.setPremasterSecret(pms);

    if (numberOfQueries % 100 == 0) {
        LOGGER.info("Number of queries so far: {}", numberOfQueries);
    }

    boolean valid = true;
    try {
        workflowExecutor.executeWorkflow();
    } catch (Exception e) {
        valid = false;
        e.printStackTrace();
    } finally {
        numberOfQueries++;
        transportHandler.closeConnection();
    }

    if (!TlsContextAnalyzer.containsFullWorkflow(tlsContext)) {
        valid = false;
    }

    return valid;
}

From source file:de.rub.nds.tlsattacker.attacks.ec.oracles.RealDirectMessageECOracle.java

License:Apache License

@Override
public boolean isFinalSolutionCorrect(BigInteger guessedSecret) {
    // BigInteger correct = new
    // BigInteger("25091756309879652045519159642875354611257005804552159157");
    // if (correct.compareTo(guessedSecret) == 0) {
    // return true;
    // } else {/*from  www  .  j  a va  2s .  com*/
    // return false;
    // }

    computer.setSecret(guessedSecret);
    try {
        Point p = computer.mul(checkPoint);
        byte[] pms = BigIntegers.asUnsignedByteArray(curve.getKeyBits() / 8, p.getX());
        return Arrays.equals(checkPMS, pms);
    } catch (DivisionException ex) {
        LOGGER.debug(ex);
        return false;
    }
}

From source file:de.rub.nds.tlsattacker.attacks.impl.InvalidCurveAttack.java

License:Apache License

private WorkflowTrace executeProtocolFlow(ConfigHandler configHandler) {
    TransportHandler transportHandler = configHandler.initializeTransportHandler(config);
    TlsContext tlsContext = configHandler.initializeTlsContext(config);
    WorkflowExecutor workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext);

    WorkflowTrace trace = tlsContext.getWorkflowTrace();
    ECDHClientKeyExchangeMessage message = (ECDHClientKeyExchangeMessage) trace
            .getFirstHandshakeMessage(HandshakeMessageType.CLIENT_KEY_EXCHANGE);

    // modify public point base X coordinate
    ModifiableBigInteger x = ModifiableVariableFactory.createBigIntegerModifiableVariable();
    x.setModification(BigIntegerModificationFactory.explicitValue(config.getPublicPointBaseX()));
    message.setPublicKeyBaseX(x);/*  ww w. j  a  v  a  2  s .  c  o  m*/

    // modify public point base Y coordinate
    ModifiableBigInteger y = ModifiableVariableFactory.createBigIntegerModifiableVariable();
    y.setModification(BigIntegerModificationFactory.explicitValue(config.getPublicPointBaseY()));
    message.setPublicKeyBaseY(y);

    // set explicit premaster secret value (X value of the resulting point
    // coordinate)
    ModifiableByteArray pms = ModifiableVariableFactory.createByteArrayModifiableVariable();
    byte[] explicitePMS = BigIntegers.asUnsignedByteArray(CURVE_FIELD_SIZE, config.getPremasterSecret());
    pms.setModification(ByteArrayModificationFactory.explicitValue(explicitePMS));
    message.setPremasterSecret(pms);

    workflowExecutor.executeWorkflow();

    tlsContexts.add(tlsContext);

    transportHandler.closeConnection();

    return trace;
}

From source file:org.ethereum.core.BlockHeader.java

License:Open Source License

public byte[] getPowBoundary() {
    return BigIntegers.asUnsignedByteArray(32,
            BigInteger.ONE.shiftLeft(256).divide(getDifficulty().asBigInteger()));
}

From source file:org.ethereum.crypto.EthereumIESEngine.java

License:Open Source License

public byte[] processBlock(byte[] in, int inOff, int inLen, byte[] macData) throws InvalidCipherTextException {
    if (forEncryption) {
        if (keyPairGenerator != null) {
            EphemeralKeyPair ephKeyPair = keyPairGenerator.generate();

            this.privParam = ephKeyPair.getKeyPair().getPrivate();
            this.v = ephKeyPair.getEncodedPublicKey();
        }/*from w  w w  .j av a 2 s .c  om*/
    } else {
        if (keyParser != null) {
            ByteArrayInputStream bIn = new ByteArrayInputStream(in, inOff, inLen);

            try {
                this.pubParam = keyParser.readKey(bIn);
            } catch (IOException e) {
                throw new InvalidCipherTextException(
                        "unable to recover ephemeral public key: " + e.getMessage(), e);
            }

            int encLength = (inLen - bIn.available());
            this.v = Arrays.copyOfRange(in, inOff, inOff + encLength);
        }
    }

    // Compute the common value and convert to byte array.
    agree.init(privParam);
    BigInteger z = agree.calculateAgreement(pubParam);
    byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

    // Create input to KDF.
    byte[] vz;
    //        if (v.length != 0)
    //        {
    //            VZ = new byte[v.length + Z.length];
    //            System.arraycopy(v, 0, VZ, 0, v.length);
    //            System.arraycopy(Z, 0, VZ, v.length, Z.length);
    //        }
    //        else
    {
        vz = Z;
    }

    // Initialise the KDF.
    DerivationParameters kdfParam;
    if (kdf instanceof MGF1BytesGeneratorExt) {
        kdfParam = new MGFParameters(vz);
    } else {
        kdfParam = new KDFParameters(vz, param.getDerivationV());
    }
    kdf.init(kdfParam);

    return forEncryption ? encryptBlock(in, inOff, inLen, macData) : decryptBlock(in, inOff, inLen, macData);
}

From source file:org.ethereum.util.ByteUtilTest.java

License:Open Source License

/**
 * This test shows the difference between iterating over,
 * and comparing byte[] vs BigInteger value.
 *
 * Results indicate that the former has ~15x better performance.
 * Therefore this is used in the Miner.mine() method.
 *///from w w w.  j a v a2s. co m
@Test
public void testIncrementPerformance() {
    boolean testEnabled = false;

    if (testEnabled) {
        byte[] counter1 = new byte[4];
        byte[] max = ByteBuffer.allocate(4).putInt(Integer.MAX_VALUE).array();
        long start1 = System.currentTimeMillis();
        while (ByteUtil.increment(counter1)) {
            if (FastByteComparisons.compareTo(counter1, 0, 4, max, 0, 4) == 0) {
                break;
            }
        }
        System.out.println(System.currentTimeMillis() - start1 + "ms to reach: " + Hex.toHexString(counter1));

        BigInteger counter2 = BigInteger.ZERO;
        long start2 = System.currentTimeMillis();
        while (true) {
            if (counter2.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 0) {
                break;
            }
            counter2 = counter2.add(BigInteger.ONE);
        }
        System.out.println(System.currentTimeMillis() - start2 + "ms to reach: "
                + Hex.toHexString(BigIntegers.asUnsignedByteArray(4, counter2)));
    }
}