Search in sources :

Example 11 with SHA256Digest

use of org.spongycastle.crypto.digests.SHA256Digest in project rskj by rsksmart.

the class ProofOfWorkRule method isValid.

@Override
public boolean isValid(BlockHeader header) {
    if (isFallbackMiningPossibleAndBlockSigned(header)) {
        return validFallbackBlockSignature(constants, header, header.getBitcoinMergedMiningHeader());
    }
    co.rsk.bitcoinj.core.NetworkParameters bitcoinNetworkParameters = bridgeConstants.getBtcParams();
    byte[] bitcoinMergedMiningCoinbaseTransactionCompressed = header.getBitcoinMergedMiningCoinbaseTransaction();
    if (bitcoinMergedMiningCoinbaseTransactionCompressed == null) {
        return false;
    }
    if (header.getBitcoinMergedMiningHeader() == null) {
        return false;
    }
    if (header.getBitcoinMergedMiningMerkleProof() == null) {
        return false;
    }
    BtcBlock bitcoinMergedMiningBlock = bitcoinNetworkParameters.getDefaultSerializer().makeBlock(header.getBitcoinMergedMiningHeader());
    PartialMerkleTree bitcoinMergedMiningMerkleBranch = new PartialMerkleTree(bitcoinNetworkParameters, header.getBitcoinMergedMiningMerkleProof(), 0);
    BigInteger target = DifficultyUtils.difficultyToTarget(header.getDifficulty());
    BigInteger bitcoinMergedMiningBlockHashBI = bitcoinMergedMiningBlock.getHash().toBigInteger();
    if (bitcoinMergedMiningBlockHashBI.compareTo(target) > 0) {
        logger.warn("Hash {} is higher than target {}", bitcoinMergedMiningBlockHashBI.toString(16), target.toString(16));
        return false;
    }
    byte[] bitcoinMergedMiningCoinbaseTransactionMidstate = new byte[RskMiningConstants.MIDSTATE_SIZE];
    System.arraycopy(bitcoinMergedMiningCoinbaseTransactionCompressed, 0, bitcoinMergedMiningCoinbaseTransactionMidstate, 8, RskMiningConstants.MIDSTATE_SIZE_TRIMMED);
    byte[] bitcoinMergedMiningCoinbaseTransactionTail = new byte[bitcoinMergedMiningCoinbaseTransactionCompressed.length - RskMiningConstants.MIDSTATE_SIZE_TRIMMED];
    System.arraycopy(bitcoinMergedMiningCoinbaseTransactionCompressed, RskMiningConstants.MIDSTATE_SIZE_TRIMMED, bitcoinMergedMiningCoinbaseTransactionTail, 0, bitcoinMergedMiningCoinbaseTransactionTail.length);
    byte[] expectedCoinbaseMessageBytes = org.spongycastle.util.Arrays.concatenate(RskMiningConstants.RSK_TAG, header.getHashForMergedMining());
    List<Byte> bitcoinMergedMiningCoinbaseTransactionTailAsList = Arrays.asList(ArrayUtils.toObject(bitcoinMergedMiningCoinbaseTransactionTail));
    List<Byte> expectedCoinbaseMessageBytesAsList = Arrays.asList(ArrayUtils.toObject(expectedCoinbaseMessageBytes));
    int rskTagPosition = Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList, expectedCoinbaseMessageBytesAsList);
    if (rskTagPosition == -1) {
        logger.warn("bitcoin coinbase transaction tail message does not contain expected RSKBLOCK:RskBlockHeaderHash. Expected: {} . Actual: {} .", Arrays.toString(expectedCoinbaseMessageBytes), Arrays.toString(bitcoinMergedMiningCoinbaseTransactionTail));
        return false;
    }
    /*
        * We check that the there is no other block before the rsk tag, to avoid a possible malleability attack:
        * If we have a mid state with 10 blocks, and the rsk tag, we can also have
        * another mid state with 9 blocks, 64bytes + the rsk tag, giving us two blocks with different hashes but the same spv proof.
        * */
    if (rskTagPosition >= 64) {
        logger.warn("bitcoin coinbase transaction tag position is bigger than expected 64. Actual: {}.", Integer.toString(rskTagPosition));
        return false;
    }
    List<Byte> rskTagAsList = Arrays.asList(ArrayUtils.toObject(RskMiningConstants.RSK_TAG));
    int lastTag = Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList, rskTagAsList);
    if (rskTagPosition != lastTag) {
        logger.warn("The valid RSK tag is not the last RSK tag. Tail: {}.", Arrays.toString(bitcoinMergedMiningCoinbaseTransactionTail));
        return false;
    }
    int remainingByteCount = bitcoinMergedMiningCoinbaseTransactionTail.length - rskTagPosition - RskMiningConstants.RSK_TAG.length - RskMiningConstants.BLOCK_HEADER_HASH_SIZE;
    if (remainingByteCount > RskMiningConstants.MAX_BYTES_AFTER_MERGED_MINING_HASH) {
        logger.warn("More than 128 bytes after RSK tag");
        return false;
    }
    SHA256Digest digest = new SHA256Digest(bitcoinMergedMiningCoinbaseTransactionMidstate);
    digest.update(bitcoinMergedMiningCoinbaseTransactionTail, 0, bitcoinMergedMiningCoinbaseTransactionTail.length);
    byte[] bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash = new byte[32];
    digest.doFinal(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash, 0);
    Sha256Hash bitcoinMergedMiningCoinbaseTransactionHash = Sha256Hash.wrapReversed(Sha256Hash.hash(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash));
    List<Sha256Hash> txHashesInTheMerkleBranch = new ArrayList<>();
    Sha256Hash merkleRoot = bitcoinMergedMiningMerkleBranch.getTxnHashAndMerkleRoot(txHashesInTheMerkleBranch);
    if (!merkleRoot.equals(bitcoinMergedMiningBlock.getMerkleRoot())) {
        logger.warn("bitcoin merkle root of bitcoin block does not match the merkle root of merkle branch");
        return false;
    }
    if (!txHashesInTheMerkleBranch.contains(bitcoinMergedMiningCoinbaseTransactionHash)) {
        logger.warn("bitcoin coinbase transaction {} not included in merkle branch", bitcoinMergedMiningCoinbaseTransactionHash);
        return false;
    }
    return true;
}
Also used : Sha256Hash(co.rsk.bitcoinj.core.Sha256Hash) ArrayList(java.util.ArrayList) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) PartialMerkleTree(co.rsk.bitcoinj.core.PartialMerkleTree) BtcBlock(co.rsk.bitcoinj.core.BtcBlock) BigInteger(java.math.BigInteger)

Example 12 with SHA256Digest

use of org.spongycastle.crypto.digests.SHA256Digest in project rskj by rsksmart.

the class ECIESCoder method makeIESEngine.

private static EthereumIESEngine makeIESEngine(boolean isEncrypt, ECPoint pub, BigInteger prv, byte[] iv) {
    AESFastEngine aesFastEngine = new AESFastEngine();
    EthereumIESEngine iesEngine = new EthereumIESEngine(new ECDHBasicAgreement(), new ConcatKDFBytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new SHA256Digest(), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
    byte[] d = new byte[] {};
    byte[] e = new byte[] {};
    IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, iv);
    iesEngine.init(isEncrypt, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(pub, CURVE), parametersWithIV);
    return iesEngine;
}
Also used : HMac(org.spongycastle.crypto.macs.HMac) SICBlockCipher(org.spongycastle.crypto.modes.SICBlockCipher) AESFastEngine(org.spongycastle.crypto.engines.AESFastEngine) ECDHBasicAgreement(org.spongycastle.crypto.agreement.ECDHBasicAgreement) ConcatKDFBytesGenerator(org.ethereum.ConcatKDFBytesGenerator) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) BufferedBlockCipher(org.spongycastle.crypto.BufferedBlockCipher)

Example 13 with SHA256Digest

use of org.spongycastle.crypto.digests.SHA256Digest in project rskj by rsksmart.

the class CryptoTest method test15.

// ECIES_AES128_SHA256 + Ephemeral Key + IV(all zeroes)
@Test
public void test15() throws Throwable {
    byte[] privKey = Hex.decode("a4627abc2a3c25315bff732cb22bc128f203912dd2a840f31e66efb27a47d2b1");
    ECKey ecKey = ECKey.fromPrivate(privKey);
    ECPrivateKeyParameters ecPrivKey = new ECPrivateKeyParameters(ecKey.getPrivKey(), ECKey.CURVE);
    ECPublicKeyParameters ecPubKey = new ECPublicKeyParameters(ecKey.getPubKeyPoint(), ECKey.CURVE);
    AsymmetricCipherKeyPair myKey = new AsymmetricCipherKeyPair(ecPubKey, ecPrivKey);
    AESFastEngine aesFastEngine = new AESFastEngine();
    IESEngine iesEngine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
    byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
    IESParameters p = new IESWithCipherParameters(d, e, 64, 128);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[16]);
    ECKeyPairGenerator eGen = new ECKeyPairGenerator();
    KeyGenerationParameters gParam = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
    eGen.init(gParam);
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keygenParams);
    EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(generator, new KeyEncoder() {

        public byte[] getEncoded(AsymmetricKeyParameter keyParameter) {
            return ((ECPublicKeyParameters) keyParameter).getQ().getEncoded();
        }
    });
    ECKeyPairGenerator gen = new ECKeyPairGenerator();
    gen.init(new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom()));
    iesEngine.init(myKey.getPublic(), parametersWithIV, kGen);
    byte[] message = Hex.decode("010101");
    log.info("payload: {}", Hex.toHexString(message));
    byte[] cipher = iesEngine.processBlock(message, 0, message.length);
    log.info("cipher: {}", Hex.toHexString(cipher));
    IESEngine decryptorIES_Engine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
    decryptorIES_Engine.init(myKey.getPrivate(), parametersWithIV, new ECIESPublicKeyParser(ECKey.CURVE));
    byte[] orig = decryptorIES_Engine.processBlock(cipher, 0, cipher.length);
    log.info("orig: " + Hex.toHexString(orig));
}
Also used : ECKeyPairGenerator(org.spongycastle.crypto.generators.ECKeyPairGenerator) EphemeralKeyPairGenerator(org.spongycastle.crypto.generators.EphemeralKeyPairGenerator) KeyEncoder(org.spongycastle.crypto.KeyEncoder) HMac(org.spongycastle.crypto.macs.HMac) SecureRandom(java.security.SecureRandom) SICBlockCipher(org.spongycastle.crypto.modes.SICBlockCipher) AESFastEngine(org.spongycastle.crypto.engines.AESFastEngine) KeyGenerationParameters(org.spongycastle.crypto.KeyGenerationParameters) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) IESEngine(org.spongycastle.crypto.engines.IESEngine) ECDHBasicAgreement(org.spongycastle.crypto.agreement.ECDHBasicAgreement) KDF2BytesGenerator(org.spongycastle.crypto.generators.KDF2BytesGenerator) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) BufferedBlockCipher(org.spongycastle.crypto.BufferedBlockCipher) ECIESPublicKeyParser(org.spongycastle.crypto.parsers.ECIESPublicKeyParser) Test(org.junit.Test)

Example 14 with SHA256Digest

use of org.spongycastle.crypto.digests.SHA256Digest in project rskj by rsksmart.

the class ECIESTest method makeIESEngine.

private static EthereumIESEngine makeIESEngine(boolean isEncrypt, ECPoint pub, BigInteger prv, byte[] IV) {
    AESFastEngine aesFastEngine = new AESFastEngine();
    EthereumIESEngine iesEngine = new EthereumIESEngine(new ECDHBasicAgreement(), new ConcatKDFBytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new SHA256Digest(), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
    byte[] d = new byte[] {};
    byte[] e = new byte[] {};
    IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, IV);
    iesEngine.init(isEncrypt, new ECPrivateKeyParameters(prv, curve), new ECPublicKeyParameters(pub, curve), parametersWithIV);
    return iesEngine;
}
Also used : HMac(org.spongycastle.crypto.macs.HMac) SICBlockCipher(org.spongycastle.crypto.modes.SICBlockCipher) AESFastEngine(org.spongycastle.crypto.engines.AESFastEngine) ECDHBasicAgreement(org.spongycastle.crypto.agreement.ECDHBasicAgreement) ConcatKDFBytesGenerator(org.ethereum.ConcatKDFBytesGenerator) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest)

Example 15 with SHA256Digest

use of org.spongycastle.crypto.digests.SHA256Digest in project rskj by rsksmart.

the class MinerServerImpl method compressCoinbase.

public static byte[] compressCoinbase(byte[] bitcoinMergedMiningCoinbaseTransactionSerialized, boolean lastOccurrence) {
    List<Byte> coinBaseTransactionSerializedAsList = java.util.Arrays.asList(ArrayUtils.toObject(bitcoinMergedMiningCoinbaseTransactionSerialized));
    List<Byte> tagAsList = java.util.Arrays.asList(ArrayUtils.toObject(RskMiningConstants.RSK_TAG));
    int rskTagPosition;
    if (lastOccurrence) {
        rskTagPosition = Collections.lastIndexOfSubList(coinBaseTransactionSerializedAsList, tagAsList);
    } else {
        rskTagPosition = Collections.indexOfSubList(coinBaseTransactionSerializedAsList, tagAsList);
    }
    int remainingByteCount = bitcoinMergedMiningCoinbaseTransactionSerialized.length - rskTagPosition - RskMiningConstants.RSK_TAG.length - RskMiningConstants.BLOCK_HEADER_HASH_SIZE;
    if (remainingByteCount > RskMiningConstants.MAX_BYTES_AFTER_MERGED_MINING_HASH) {
        throw new IllegalArgumentException("More than 128 bytes after RSK tag");
    }
    int sha256Blocks = rskTagPosition / 64;
    int bytesToHash = sha256Blocks * 64;
    SHA256Digest digest = new SHA256Digest();
    digest.update(bitcoinMergedMiningCoinbaseTransactionSerialized, 0, bytesToHash);
    byte[] hashedContent = digest.getEncodedState();
    byte[] trimmedHashedContent = new byte[RskMiningConstants.MIDSTATE_SIZE_TRIMMED];
    System.arraycopy(hashedContent, 8, trimmedHashedContent, 0, RskMiningConstants.MIDSTATE_SIZE_TRIMMED);
    byte[] unHashedContent = new byte[bitcoinMergedMiningCoinbaseTransactionSerialized.length - bytesToHash];
    System.arraycopy(bitcoinMergedMiningCoinbaseTransactionSerialized, bytesToHash, unHashedContent, 0, unHashedContent.length);
    return Arrays.concatenate(trimmedHashedContent, unHashedContent);
}
Also used : SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest)

Aggregations

SHA256Digest (org.spongycastle.crypto.digests.SHA256Digest)15 BigInteger (java.math.BigInteger)8 ECDSASigner (org.spongycastle.crypto.signers.ECDSASigner)7 HMacDSAKCalculator (org.spongycastle.crypto.signers.HMacDSAKCalculator)7 ECDHBasicAgreement (org.spongycastle.crypto.agreement.ECDHBasicAgreement)5 AESFastEngine (org.spongycastle.crypto.engines.AESFastEngine)5 HMac (org.spongycastle.crypto.macs.HMac)5 SICBlockCipher (org.spongycastle.crypto.modes.SICBlockCipher)5 ECPrivateKeyParameters (org.spongycastle.crypto.params.ECPrivateKeyParameters)5 InvalidKeyException (java.security.InvalidKeyException)4 Signature (java.security.Signature)4 SignatureException (java.security.SignatureException)4 ConcatKDFBytesGenerator (org.ethereum.ConcatKDFBytesGenerator)4 BufferedBlockCipher (org.spongycastle.crypto.BufferedBlockCipher)4 BCECPrivateKey (org.spongycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey)4 Test (org.junit.Test)3 SecureRandom (java.security.SecureRandom)2 AsymmetricCipherKeyPair (org.spongycastle.crypto.AsymmetricCipherKeyPair)2 KeyGenerationParameters (org.spongycastle.crypto.KeyGenerationParameters)2 IESEngine (org.spongycastle.crypto.engines.IESEngine)2