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(BigInteger value) 

Source Link

Document

Return the passed in value as an unsigned byte array.

Usage

From source file:co.rsk.core.bc.BlockExecutorTest.java

License:Open Source License

private static Transaction createStrangeTransaction(Account sender, Account receiver, BigInteger value,
        BigInteger nonce, int strangeTransactionType) {
    byte[] privateKeyBytes = sender.getEcKey().getPrivKeyBytes();
    byte[] to = receiver.getAddress().getBytes();
    byte[] gasLimitData = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(21000));
    byte[] valueData = BigIntegers.asUnsignedByteArray(value);

    if (strangeTransactionType == 0) {
        to = new byte[1]; // one zero
        to[0] = 127;//from www. j a  v  a 2 s.  c o  m
    } else if (strangeTransactionType == 1) {
        to = new byte[1024];
        java.util.Arrays.fill(to, (byte) -1); // fill with 0xff
    } else {
        // Bad encoding for value
        byte[] newValueData = new byte[1024];
        System.arraycopy(valueData, 0, newValueData, 1024 - valueData.length, valueData.length);
        valueData = newValueData;
    }

    Transaction tx = new Transaction(BigIntegers.asUnsignedByteArray(nonce),
            BigIntegers.asUnsignedByteArray(BigInteger.ONE), //gasPrice
            gasLimitData, // gasLimit
            to, valueData, null); // no data
    tx.sign(privateKeyBytes);
    return tx;
}

From source file:co.rsk.core.TransactionTest.java

License:Open Source License

@Test /* achieve public key of the sender */
public void test2() throws Exception {
    if (config.getBlockchainConfig().getCommonConstants().getChainId() != 0)
        return;//from   ww w  . jav  a 2 s  . c  o  m

    // cat --> 79b08ad8787060333663d19704909ee7b1903e58
    // cow --> cd2a3d9f938e13cd947ec05abc7fe734df8dd826

    BigInteger value = new BigInteger("1000000000000000000000");

    byte[] privKey = HashUtil.keccak256("cat".getBytes());
    ECKey ecKey = ECKey.fromPrivate(privKey);

    byte[] senderPrivKey = HashUtil.keccak256("cow".getBytes());

    byte[] gasPrice = Hex.decode("09184e72a000");
    byte[] gas = Hex.decode("4255");

    // Tn (nonce); Tp(pgas); Tg(gaslimi); Tt(value); Tv(value); Ti(sender);  Tw; Tr; Ts
    Transaction tx = new Transaction(null, gasPrice, gas, ecKey.getAddress(), value.toByteArray(), null);

    tx.sign(senderPrivKey);

    System.out.println("v\t\t\t: " + Hex.toHexString(new byte[] { tx.getSignature().v }));
    System.out.println("r\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().r)));
    System.out.println("s\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().s)));

    System.out.println("RLP encoded tx\t\t: " + Hex.toHexString(tx.getEncoded()));

    // retrieve the signer/sender of the transaction
    ECKey key = ECKey.signatureToKey(tx.getHash().getBytes(), tx.getSignature());

    System.out.println("Tx unsigned RLP\t\t: " + Hex.toHexString(tx.getEncodedRaw()));
    System.out.println("Tx signed   RLP\t\t: " + Hex.toHexString(tx.getEncoded()));

    System.out.println("Signature public key\t: " + Hex.toHexString(key.getPubKey()));
    System.out.println("Sender is\t\t: " + Hex.toHexString(key.getAddress()));

    assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(key.getAddress()));

    System.out.println(tx.toString());
}

From source file:co.rsk.core.TransactionTest.java

License:Open Source License

@Test /* achieve public key of the sender */
public void testSenderShouldChangeWhenReSigningTx() throws Exception {
    BigInteger value = new BigInteger("1000000000000000000000");

    byte[] privateKey = HashUtil.keccak256("cat".getBytes());
    ECKey ecKey = ECKey.fromPrivate(privateKey);

    byte[] senderPrivateKey = HashUtil.keccak256("cow".getBytes());

    byte[] gasPrice = Hex.decode("09184e72a000");
    byte[] gas = Hex.decode("4255");

    // Tn(nonce); Tp(pgas); Tg(gaslimit); Tt(value); Tv(value); Ti(sender);  Tw; Tr; Ts
    Transaction tx = new Transaction(null, gasPrice, gas, ecKey.getAddress(), value.toByteArray(), null);

    tx.sign(senderPrivateKey);//  w w  w  . ja v a  2s. co m

    System.out.println("v\t\t\t: " + Hex.toHexString(new byte[] { tx.getSignature().v }));
    System.out.println("r\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().r)));
    System.out.println("s\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().s)));

    System.out.println("RLP encoded tx\t\t: " + Hex.toHexString(tx.getEncoded()));

    // Retrieve sender from transaction
    RskAddress sender = tx.getSender();

    // Re-sign transaction with a different sender's key
    byte[] newSenderPrivateKey = HashUtil.keccak256("bat".getBytes());
    tx.sign(newSenderPrivateKey);

    // Retrieve new sender from transaction
    RskAddress newSender = tx.getSender();

    // Verify sender changed
    assertNotEquals(sender, newSender);

    System.out.println(tx.toString());
}

From source file:co.rsk.peg.BridgeSupportTest.java

License:Open Source License

@Test
public void releaseBtcFromContract() throws BlockStoreException, AddressFormatException, IOException {
    Repository repository = createRepositoryImpl(config);
    Repository track = repository.startTracking();

    org.ethereum.core.Transaction tx = new InternalTransaction(null, 0, 0,
            BigIntegers.asUnsignedByteArray(NONCE), new DataWord(BigIntegers.asUnsignedByteArray(GAS_PRICE)),
            new DataWord(BigIntegers.asUnsignedByteArray(GAS_LIMIT)),
            new RskAddress(org.ethereum.crypto.ECKey.fromPrivate(new BtcECKey().getPrivKey()).getAddress())
                    .getBytes(),//from  ww  w.j  av a 2 s  .c om
            Hex.decode(TO_ADDRESS), BigIntegers.asUnsignedByteArray(AMOUNT), Hex.decode(DATA), "");

    track.saveCode(tx.getSender(), new byte[] { 0x1 });
    BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR,
            config.getBlockchainConfig().getCommonConstants().getBridgeConstants(),
            bridgeStorageConfigurationAtHeightZero);
    BridgeSupport bridgeSupport = new BridgeSupport(config, track, mock(BridgeEventLogger.class), provider,
            null);

    try {
        bridgeSupport.releaseBtc(tx);
    } catch (Program.OutOfGasException e) {
        return;
    }
    Assert.fail();
}

From source file:co.rsk.test.builders.BlockBuilder.java

License:Open Source License

/**
 * This has to be called after .parent() in order to have any effect
 *//*from  ww w .  j  a  v  a  2  s.  c om*/
public BlockBuilder gasLimit(BigInteger gasLimit) {
    this.gasLimit = BigIntegers.asUnsignedByteArray(gasLimit);
    return this;
}

From source file:com.github.horrorho.inflatabledonkey.crypto.srp.SRPAssistant.java

License:Open Source License

public static byte[] padded(BigInteger n, int length) {
    // org.bouncycastle.crypto.agreement.srp.SRP6Util#getPadded() with overflow check
    byte[] byteArray = BigIntegers.asUnsignedByteArray(n);

    if (byteArray.length > length) {
        throw new IllegalArgumentException("BigInteger overflows specified length");
    }/*from  w w  w  .j  a va  2s .  c  o m*/

    if (byteArray.length < length) {
        byte[] tmp = new byte[length];
        System.arraycopy(byteArray, 0, tmp, length - byteArray.length, byteArray.length);
        byteArray = tmp;
    }
    return byteArray;
}

From source file:com.sun.midp.crypto.BouncyCastleRSAPrivateKey.java

License:Open Source License

public BouncyCastleRSAPrivateKey(RSAKeyParameters keyParam) {
    rsaPrivateKey = new RSAPrivateKey(BigIntegers.asUnsignedByteArray(keyParam.getModulus()),
            BigIntegers.asUnsignedByteArray(keyParam.getExponent()));
}

From source file:COSE.Recipient.java

private void ECDH_GenerateEphemeral() throws CoseException {
    X9ECParameters p = privateKey.GetCurve();
    ECDomainParameters parameters = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH());

    ECKeyPairGenerator pGen = new ECKeyPairGenerator();
    ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, null);
    pGen.init(genParam);/* www  .j av a2s . c  om*/

    AsymmetricCipherKeyPair p1 = pGen.generateKeyPair();

    CBORObject epk = CBORObject.NewMap();
    epk.Add(KeyKeys.KeyType.AsCBOR(), KeyKeys.KeyType_EC2);
    epk.Add(KeyKeys.EC2_Curve.AsCBOR(), privateKey.get(KeyKeys.EC2_Curve.AsCBOR()));
    ECPublicKeyParameters priv = (ECPublicKeyParameters) p1.getPublic();

    byte[] rgbEncoded = priv.getQ().normalize().getEncoded(true);
    byte[] X = new byte[rgbEncoded.length - 1];
    System.arraycopy(rgbEncoded, 1, X, 0, X.length);
    epk.Add(KeyKeys.EC2_X.AsCBOR(), CBORObject.FromObject(X));
    epk.Add(KeyKeys.EC2_Y.AsCBOR(), CBORObject.FromObject((rgbEncoded[0] & 1) == 1));
    addAttribute(HeaderKeys.ECDH_EPK, epk, Attribute.UNPROTECTED);

    OneKey secretKey = new OneKey();
    secretKey.add(KeyKeys.KeyType, KeyKeys.KeyType_EC2);
    secretKey.add(KeyKeys.EC2_Curve, privateKey.get(KeyKeys.EC2_Curve.AsCBOR()));
    secretKey.add(KeyKeys.EC2_X, CBORObject.FromObject(X));
    secretKey.add(KeyKeys.EC2_Y, CBORObject.FromObject((rgbEncoded[0] & 1) == 1));
    ECPrivateKeyParameters priv1 = (ECPrivateKeyParameters) p1.getPrivate();
    secretKey.add(KeyKeys.EC2_D, CBORObject.FromObject(BigIntegers.asUnsignedByteArray(priv1.getD())));

    senderKey = secretKey;
}

From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.DHClientKeyExchangeHandler.java

License:Apache License

@Override
byte[] prepareKeyExchangeMessage() {
    if (tlsContext.getServerDHParameters() == null) {
        // we are probably handling a simple DH ciphersuite, we try to
        // establish server public key parameters from the server
        // certificate message
        Certificate x509Cert = tlsContext.getServerCertificate();

        SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
        DHPublicKeyParameters parameters;
        try {//  www.ja v  a  2  s.com
            parameters = (DHPublicKeyParameters) PublicKeyFactory.createKey(keyInfo);
            tlsContext.setServerDHParameters(new ServerDHParams(parameters));
        } catch (IOException e) {
            throw new WorkflowExecutionException("Problem in parsing public key parameters from certificate",
                    e);
        }
    }

    // generate client's original dh public and private key, based on the
    // server's public parameters
    AsymmetricCipherKeyPair kp = TlsDHUtils.generateDHKeyPair(new SecureRandom(),
            tlsContext.getServerDHParameters().getPublicKey().getParameters());
    DHPublicKeyParameters dhPublic = (DHPublicKeyParameters) kp.getPublic();
    DHPrivateKeyParameters dhPrivate = (DHPrivateKeyParameters) kp.getPrivate();

    protocolMessage.setG(dhPublic.getParameters().getG());
    protocolMessage.setP(dhPublic.getParameters().getP());
    protocolMessage.setY(dhPublic.getY());
    protocolMessage.setX(dhPrivate.getX());

    // set the modified values of client's private and public parameters
    DHParameters newParams = new DHParameters(protocolMessage.getP().getValue(),
            protocolMessage.getG().getValue());
    // DHPublicKeyParameters newDhPublic = new
    // DHPublicKeyParameters(dhMessage.getY().getValue(), newParams);
    DHPrivateKeyParameters newDhPrivate = new DHPrivateKeyParameters(protocolMessage.getX().getValue(),
            newParams);

    byte[] serializedPublicKey = BigIntegers.asUnsignedByteArray(protocolMessage.getY().getValue());
    protocolMessage.setSerializedPublicKey(serializedPublicKey);
    protocolMessage.setSerializedPublicKeyLength(serializedPublicKey.length);

    byte[] result = ArrayConverter
            .concatenate(
                    ArrayConverter.intToBytes(protocolMessage.getSerializedPublicKeyLength().getValue(),
                            HandshakeByteLength.DH_PARAM_LENGTH),
                    protocolMessage.getSerializedPublicKey().getValue());

    byte[] premasterSecret = TlsDHUtils
            .calculateDHBasicAgreement(tlsContext.getServerDHParameters().getPublicKey(), newDhPrivate);
    protocolMessage.setPremasterSecret(premasterSecret);
    LOGGER.debug("Computed PreMaster Secret: {}",
            ArrayConverter.bytesToHexString(protocolMessage.getPremasterSecret().getValue()));

    byte[] random = tlsContext.getClientServerRandom();

    PRFAlgorithm prfAlgorithm = AlgorithmResolver.getPRFAlgorithm(tlsContext.getProtocolVersion(),
            tlsContext.getSelectedCipherSuite());
    byte[] masterSecret = PseudoRandomFunction.compute(prfAlgorithm,
            protocolMessage.getPremasterSecret().getValue(), PseudoRandomFunction.MASTER_SECRET_LABEL, random,
            HandshakeByteLength.MASTER_SECRET);
    LOGGER.debug("Computed Master Secret: {}", ArrayConverter.bytesToHexString(masterSecret));

    protocolMessage.setMasterSecret(masterSecret);
    tlsContext.setMasterSecret(protocolMessage.getMasterSecret().getValue());

    return result;

}

From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.DHClientKeyExchangeHandlerTest.java

License:Apache License

/**
 * Test of prepareMessageAction method, of class
 * ECDHClientKeyExchangeHandler./*from  w  w w .ja va 2s. com*/
 */
@Test
public void testPrepareMessage() {
    handler.initializeProtocolMessage();

    DHClientKeyExchangeMessage message = (DHClientKeyExchangeMessage) handler.getProtocolMessage();
    ModifiableBigInteger y = new ModifiableBigInteger();
    y.setModification(BigIntegerModificationFactory.explicitValue(publicKey));
    message.setY(y);

    byte[] result = handler.prepareMessageAction();

    assertEquals("Message type must be ClientKeyExchange", HandshakeMessageType.CLIENT_KEY_EXCHANGE,
            message.getHandshakeMessageType());

    byte[] serializedPublicKey = BigIntegers.asUnsignedByteArray(publicKey);
    byte[] expected = ArrayConverter
            .concatenate(new byte[] { 0x10, 0x00, 0x00, (byte) 0x42, 0x00, (byte) 0x40 }, serializedPublicKey);

    Assert.assertArrayEquals(expected, result);
}