org.fisco.bcos.web3j.crypto.Hash Java Examples

The following examples show how to use org.fisco.bcos.web3j.crypto.Hash. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NodeMgrTools.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * get hash value
 * type: sha256 or sm3
 */
public static byte[] getHashValue(byte[] byteArray) {
    byte[] hashResult;
    if(EncryptType.encryptType == 1) {
       hashResult = Hash.sha3(byteArray);
       return hashResult;
    } else {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA-256");
            hashResult = sha.digest(byteArray);
            return hashResult;
        } catch (Exception e) {
            log.error("shaEncode getHashValue fail:", e);
            return null;
        }
    }
}
 
Example #2
Source File: NameHash.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
private static byte[] nameHash(String[] labels) {
    if (labels.length == 0 || labels[0].equals("")) {
        return EMPTY;
    } else {
        String[] tail;
        if (labels.length == 1) {
            tail = new String[] {};
        } else {
            tail = Arrays.copyOfRange(labels, 1, labels.length);
        }

        byte[] remainderHash = nameHash(tail);
        byte[] result = Arrays.copyOf(remainderHash, 64);

        byte[] labelHash = Hash.sha3(labels[0].getBytes(StandardCharsets.UTF_8));
        System.arraycopy(labelHash, 0, result, 32, labelHash.length);

        return Hash.sha3(result);
    }
}
 
Example #3
Source File: RawTransactionManager.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public SendTransaction signAndSend(RawTransaction rawTransaction) throws IOException {

        byte[] signedMessage;

        if (chainId > ChainId.NONE) {
            signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials);
        } else {
            signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        }

        String hexValue = Numeric.toHexString(signedMessage);
        SendTransaction sendTransaction = web3j.sendRawTransaction(hexValue).send();
        if (sendTransaction != null && !sendTransaction.hasError()) {
            String txHashLocal = Hash.sha3(hexValue);
            String txHashRemote = sendTransaction.getTransactionHash();
            if (!txHashVerifier.verify(txHashLocal, txHashRemote)) {
                throw new TxHashMismatchException(txHashLocal, txHashRemote);
            }
        }
        return sendTransaction;
    }
 
Example #4
Source File: FunctionReturnDecoderTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeIndexedDynamicArrayValue() {
    DynamicArray<Uint256> array = new DynamicArray<>(new Uint256(BigInteger.TEN));
    String encoded = TypeEncoder.encodeDynamicArray(array);
    String hash = Hash.sha3(encoded);

    assertThat(
            FunctionReturnDecoder.decodeIndexedValue(
                    hash, new TypeReference<DynamicArray>() {}),
            equalTo(new Bytes32(Numeric.hexStringToByteArray(hash))));
}
 
Example #5
Source File: FunctionReturnDecoderTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeIndexedDynamicBytesValue() {
    DynamicBytes bytes = new DynamicBytes(new byte[] {1, 2, 3, 4, 5});
    String encoded = TypeEncoder.encodeDynamicBytes(bytes);
    String hash = Hash.sha3(encoded);

    assertThat(
            FunctionReturnDecoder.decodeIndexedValue(
                    hash, new TypeReference<DynamicBytes>() {}),
            equalTo(new Bytes32(Numeric.hexStringToByteArray(hash))));
}
 
Example #6
Source File: FunctionReturnDecoderTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeIndexedStringValue() {
    Utf8String string = new Utf8String("some text");
    String encoded = TypeEncoder.encodeString(string);
    String hash = Hash.sha3(encoded);

    assertThat(
            FunctionReturnDecoder.decodeIndexedValue(hash, new TypeReference<Utf8String>() {}),
            equalTo(new Bytes32(Numeric.hexStringToByteArray(hash))));
}
 
Example #7
Source File: MerkleProofUtility.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Verify transaction receipt merkle proof
 *
 * @param receiptRoot
 * @param transactionReceipt
 * @param receiptProof
 * @return
 */
public static boolean verifyTransactionReceipt(
        String receiptRoot,
        TransactionReceipt transactionReceipt,
        List<MerkleProofUnit> receiptProof) {

    if (!transactionReceipt.getGasUsedRaw().startsWith("0x")) {
        transactionReceipt.setGasUsed("0x" + transactionReceipt.getGasUsed().toString(16));
    }

    // transaction index
    byte[] byteIndex =
            RlpEncoder.encode(RlpString.create(transactionReceipt.getTransactionIndex()));

    String receiptRlp = ReceiptEncoder.encode(transactionReceipt);
    String rlpHash = Hash.sha3(receiptRlp);
    String input = Numeric.toHexString(byteIndex) + rlpHash.substring(2);

    String proof = Merkle.calculateMerkleRoot(receiptProof, input);

    logger.debug(
            " transaction hash: {}, transactionReceipt: {}, receiptProof: {}, receiptRoot: {}, proof: {}",
            transactionReceipt.getTransactionHash(),
            transactionReceipt,
            receiptProof,
            receiptRoot,
            proof);

    return proof.equals(receiptRoot);
}
 
Example #8
Source File: MerkleProofUtility.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Verify transaction receipt merkle proof
 *
 * @param receiptRoot
 * @param receiptAndProof
 * @return
 */
public static boolean verifyTransactionReceipt(
        String receiptRoot, TransactionReceiptWithProof.ReceiptAndProof receiptAndProof) {

    TransactionReceipt transactionReceipt = receiptAndProof.getTransactionReceipt();

    // transaction index
    byte[] byteIndex =
            RlpEncoder.encode(RlpString.create(transactionReceipt.getTransactionIndex()));

    if (!transactionReceipt.getGasUsedRaw().startsWith("0x")) {
        transactionReceipt.setGasUsed("0x" + transactionReceipt.getGasUsed().toString(16));
    }

    String receiptRlp = ReceiptEncoder.encode(transactionReceipt);
    String rlpHash = Hash.sha3(receiptRlp);
    String input = Numeric.toHexString(byteIndex) + rlpHash.substring(2);

    String proof = Merkle.calculateMerkleRoot(receiptAndProof.getReceiptProof(), input);

    logger.debug(
            " transaction hash: {}, receipt index: {}, root: {}, proof: {}, receipt: {}",
            transactionReceipt.getTransactionHash(),
            transactionReceipt.getTransactionIndex(),
            receiptRoot,
            proof,
            receiptAndProof.getTransactionReceipt());

    return proof.equals(receiptRoot);
}
 
Example #9
Source File: Merkle.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static String calculateMerkleRoot(List<MerkleProofUnit> merkleProofUnits, String hash) {
    if (merkleProofUnits == null) {
        return hash;
    }
    String result = hash;
    for (MerkleProofUnit merkleProofUnit : merkleProofUnits) {
        String left = splicing(merkleProofUnit.getLeft());
        String right = splicing(merkleProofUnit.getRight());
        String input = splicing("0x", left, result.substring(2), right);
        result = Hash.sha3(input);
    }
    return result;
}
 
Example #10
Source File: SignDataTest.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
     * test guomi webase-sign
     * needed: config keyServer in yml
     */
    @Test
    public void testSignData() throws SignatureException {
        EncodeInfo encodeInfo = new EncodeInfo();
        // uuid to set uuid of webase-sign's keystoreInfo
        encodeInfo.setSignUserId("uuid");
        encodeInfo.setEncodedDataStr(Hash.sha3String(rawData));
        String signedData = keyStoreService.getSignData(encodeInfo);// from webase-sign
        System.out.println(signedData); // 00fd8bbc86faa0cf9216886e15118862ef5469c5283ab43b727ebaee93d866ced346c6eea89aac11be598de5ad8b3711791594651a3a3e44df2f7d9a522da351e0
//        Assert.assertTrue(StringUtils.isNotBlank(signedData));

    }
 
Example #11
Source File: SM3PwdEncoderTest.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
@Test
public void testPwdMatches() {
    String raw = passwordEncoder.encode("123");
    boolean res = passwordEncoder.matches(raw, pwdSM3Of123);
    System.out.println(res);
    System.out.println(Hash.sha3("123"));

}
 
Example #12
Source File: Web3Tools.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
/**
 * get methodId after hash
 */
public static String buildMethodId(AbiDefinition abiDefinition) {
    byte[] inputs = getMethodIdBytes(abiDefinition);
    // 2019/11/27 support guomi
    byte[] hash = Hash.sha3(inputs);
    return Numeric.toHexString(hash).substring(0, 10);
}
 
Example #13
Source File: TopicTools.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static String bytesToTopic(byte[] b) {
    byte[] hash = Hash.sha3(b);
    return Numeric.toHexString(hash);
}
 
Example #14
Source File: TopicTools.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static String stringToTopic(String s) {
    byte[] hash = Hash.sha3(s.getBytes());
    return Numeric.toHexString(hash);
}
 
Example #15
Source File: TransactionResource.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public TransactionReceiptWithProof getTransactionReceiptWithProof(
        String transactionHash, String rootHash) throws IOException {
    TransactionReceiptWithProof transactionReceiptWithProof =
            web3j.getTransactionReceiptByHashWithProof(transactionHash).send();

    if (transactionReceiptWithProof.getTransactionReceiptWithProof() == null) {
        return null;
    }
    TransactionReceipt transactionReceipt =
            transactionReceiptWithProof
                    .getTransactionReceiptWithProof()
                    .getTransactionReceipt();
    logger.debug("Receipt {}", transactionReceipt.toString());

    // transaction index
    String index = transactionReceipt.getTransactionIndexRaw();
    BigInteger indexValue = Numeric.toBigInt(index);
    byte[] byteIndex = RlpEncoder.encode(RlpString.create(indexValue));

    String receiptRlp = ReceiptEncoder.encode(transactionReceipt);
    logger.debug("ReceiptRlp:{}", receiptRlp);

    String rlpHash = Hash.sha3(receiptRlp);
    logger.debug("ReceiptRlpHash:{}", rlpHash);

    String input = Numeric.toHexString(byteIndex) + rlpHash.substring(2);
    logger.info("ReceiptWithIndex:{}", input);

    String proof =
            Merkle.calculateMerkleRoot(
                    transactionReceiptWithProof
                            .getTransactionReceiptWithProof()
                            .getReceiptProof(),
                    input);

    //        System.out.println("MerkleRoot: " + proof);
    if (!proof.equals(rootHash)) {
        logger.debug("MerkleRoot:{}", proof);
        logger.debug("TransRoot :{}", rootHash);
        return null;
    }
    return transactionReceiptWithProof;
}
 
Example #16
Source File: EventEncoder.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static String buildEventSignature(String methodSignature) {
    byte[] input = methodSignature.getBytes();
    byte[] hash = Hash.sha3(input);
    return Numeric.toHexString(hash);
}
 
Example #17
Source File: FunctionEncoder.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static String buildMethodId(String methodSignature) {
    byte[] input = methodSignature.getBytes();
    byte[] hash = Hash.sha3(input);
    return Numeric.toHexString(hash).substring(0, 10);
}