Java Code Examples for org.fisco.bcos.web3j.utils.Numeric#hexStringToByteArray()

The following examples show how to use org.fisco.bcos.web3j.utils.Numeric#hexStringToByteArray() . 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: SignTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testGmSignVerify() throws IOException {
    byte[] sourceData =
            Hex.decode("434477813974bf58f94bcf760833c2b40f77a5fc360485b0b9ed1bd9682edb45");
    String publicKey =
            "e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
    String sign =
            "09628650676000c8d18bf43db68e7f66dfaed230d87e6391c29eb594b7b9cc3c8d370dbd29ce62bbcf3506adb57f041d8646ae4f70a26ea5179418e738fd4372e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
    byte[] signatureBytes = Numeric.hexStringToByteArray("0x" + sign);

    ASN1Integer d_r =
            new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 0, 32)));
    ASN1Integer d_s =
            new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 32, 64)));
    ASN1EncodableVector v2 = new ASN1EncodableVector();
    v2.add(d_r);
    v2.add(d_s);
    DERSequence der = new DERSequence(v2);
    boolean b =
            SM2Algorithm.verify(
                    sourceData,
                    der.getEncoded(),
                    publicKey.substring(0, 64),
                    publicKey.substring(64, 128));
    assertTrue("Test sm2 verify", b);
}
 
Example 2
Source File: TypeDecoder.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
static <T extends Bytes> T decodeBytes(String input, int offset, Class<T> type) {
    try {
        String simpleName = type.getSimpleName();
        String[] splitName = simpleName.split(Bytes.class.getSimpleName());
        int length = Integer.parseInt(splitName[1]);
        int hexStringLength = length << 1;

        byte[] bytes =
                Numeric.hexStringToByteArray(input.substring(offset, offset + hexStringLength));
        return type.getConstructor(byte[].class).newInstance(bytes);
    } catch (NoSuchMethodException
            | SecurityException
            | InstantiationException
            | IllegalAccessException
            | IllegalArgumentException
            | InvocationTargetException e) {
        throw new UnsupportedOperationException(
                "Unable to create instance of " + type.getName(), e);
    }
}
 
Example 3
Source File: TransactionDecoder.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static RawTransaction decode(String hexTransaction) {
    byte[] transaction = Numeric.hexStringToByteArray(hexTransaction);
    RlpList rlpList = RlpDecoder.decode(transaction);
    RlpList values = (RlpList) rlpList.getValues().get(0);
    BigInteger randomid = ((RlpString) values.getValues().get(0)).asPositiveBigInteger();
    BigInteger gasPrice = ((RlpString) values.getValues().get(1)).asPositiveBigInteger();
    BigInteger gasLimit = ((RlpString) values.getValues().get(2)).asPositiveBigInteger();
    BigInteger blockLimit = ((RlpString) values.getValues().get(3)).asPositiveBigInteger();
    String to = ((RlpString) values.getValues().get(4)).asString();
    BigInteger value = ((RlpString) values.getValues().get(5)).asPositiveBigInteger();
    String data = ((RlpString) values.getValues().get(6)).asString();
    if (values.getValues().size() > 7) {
        byte v = ((RlpString) values.getValues().get(7)).getBytes()[0];
        byte[] r =
                Numeric.toBytesPadded(
                        Numeric.toBigInt(((RlpString) values.getValues().get(8)).getBytes()),
                        32);
        byte[] s =
                Numeric.toBytesPadded(
                        Numeric.toBigInt(((RlpString) values.getValues().get(9)).getBytes()),
                        32);
        Sign.SignatureData signatureData = new Sign.SignatureData(v, r, s);
        return new SignedRawTransaction(
                randomid, gasPrice, gasLimit, blockLimit, to, value, data, signatureData);
    } else {
        return RawTransaction.createTransaction(
                randomid, gasPrice, gasLimit, blockLimit, to, value, data);
    }
}
 
Example 4
Source File: Tools.java    From evidenceSample with Apache License 2.0 5 votes vote down vote up
static public Sign.SignatureData stringToSignatureData(String signatureData)
{
    byte[] byte_3 = Numeric.hexStringToByteArray(signatureData);
    byte[] signR = new byte[32];
    System.arraycopy(byte_3, 1, signR, 0, signR.length);
    byte[] signS = new byte[32];
    System.arraycopy(byte_3, 1+signR.length, signS, 0, signS.length);
    return  new Sign.SignatureData(byte_3[0],signR,signS);
}
 
Example 5
Source File: FunctionReturnDecoderTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeIndexedBytes16Value() {
    String rawInput = "0x1234567890123456789012345678901200000000000000000000000000000000";
    byte[] rawInputBytes = Numeric.hexStringToByteArray(rawInput.substring(0, 34));

    assertThat(
            FunctionReturnDecoder.decodeIndexedValue(rawInput, new TypeReference<Bytes16>() {}),
            equalTo(new Bytes16(rawInputBytes)));
}
 
Example 6
Source File: FunctionReturnDecoderTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeIndexedBytes32Value() {
    String rawInput = "0x1234567890123456789012345678901234567890123456789012345678901234";
    byte[] rawInputBytes = Numeric.hexStringToByteArray(rawInput);

    assertThat(
            FunctionReturnDecoder.decodeIndexedValue(rawInput, new TypeReference<Bytes32>() {}),
            equalTo(new Bytes32(rawInputBytes)));
}
 
Example 7
Source File: SM3Digest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public String hash(String hexInput) {
    byte[] md = new byte[32];
    //		 hexInput = cleanHexPrefix(hexInput);
    //		byte[] msg = Hex.decode(hexInput);
    byte[] msg = Numeric.hexStringToByteArray(hexInput);
    logger.debug("sm3 hash origData:{}", hexInput);
    SM3Digest sm3 = new SM3Digest();
    sm3.update(msg, 0, msg.length);
    sm3.doFinal(md, 0);
    logger.debug("sm3 hash data:{}", Hex.toHexString(md));
    return Numeric.toHexString(md);
}
 
Example 8
Source File: ContractTypeUtil.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
static <T extends Bytes> T encodeBytes(String input, Class<T> type) throws FrontException {
    try {
        byte[] bytes = Numeric.hexStringToByteArray(input);
        return type.getConstructor(byte[].class).newInstance(bytes);
    } catch (NoSuchMethodException | SecurityException | InstantiationException
            | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        log.error("encodeBytes failed.", e);
        throw new FrontException(ConstantCode.CONTRACT_TYPE_PARAM_ERROR.getCode(),
                String.format("unable to create instance of type:%s", type.getName()));
    }
}
 
Example 9
Source File: TransactionEncoder.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
static List<RlpType> asRlpValues(
        RawTransaction rawTransaction, Sign.SignatureData signatureData) {
    List<RlpType> result = new ArrayList<>();
    result.add(RlpString.create(rawTransaction.getRandomid()));
    result.add(RlpString.create(rawTransaction.getGasPrice()));
    result.add(RlpString.create(rawTransaction.getGasLimit()));
    result.add(RlpString.create(rawTransaction.getBlockLimit()));
    // an empty to address (contract creation) should not be encoded as a numeric 0 value
    String to = rawTransaction.getTo();
    if (to != null && to.length() > 0) {
        // addresses that start with zeros should be encoded with the zeros included, not
        // as numeric values
        result.add(RlpString.create(Numeric.hexStringToByteArray(to)));
    } else {
        result.add(RlpString.create(""));
    }

    result.add(RlpString.create(rawTransaction.getValue()));

    // value field will already be hex encoded, so we need to convert into binary first
    byte[] data = Numeric.hexStringToByteArray(rawTransaction.getData());
    result.add(RlpString.create(data));

    if (signatureData != null) {
        if (EncryptType.encryptType == 1) {
            result.add(RlpString.create(signatureData.getPub()));
            // logger.debug("RLP-Pub:{},RLP-PubLen:{}",Hex.toHexString(signatureData.getPub()),signatureData.getPub().length);
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR())));
            // logger.debug("RLP-R:{},RLP-RLen:{}",Hex.toHexString(signatureData.getR()),signatureData.getR().length);
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS())));
            // logger.debug("RLP-S:{},RLP-SLen:{}",Hex.toHexString(signatureData.getS()),signatureData.getS().length);
        } else {
            result.add(RlpString.create(signatureData.getV()));
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR())));
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS())));
        }
    }
    return result;
}
 
Example 10
Source File: TypeDecoder.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
static DynamicBytes decodeDynamicBytes(String input, int offset) {
    int encodedLength = decodeUintAsInt(input, offset);
    int hexStringEncodedLength = encodedLength << 1;

    int valueOffset = offset + MAX_BYTE_LENGTH_FOR_HEX_STRING;

    String data = input.substring(valueOffset, valueOffset + hexStringEncodedLength);
    byte[] bytes = Numeric.hexStringToByteArray(data);

    return new DynamicBytes(bytes);
}
 
Example 11
Source File: TypeDecoder.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
static <T extends NumericType> T decodeNumeric(String input, Class<T> type) {
    try {
        byte[] inputByteArray = Numeric.hexStringToByteArray(input);
        int typeLengthAsBytes = getTypeLengthInBytes(type);

        byte[] resultByteArray = new byte[typeLengthAsBytes + 1];

        if (Int.class.isAssignableFrom(type) || Fixed.class.isAssignableFrom(type)) {
            resultByteArray[0] = inputByteArray[0]; // take MSB as sign bit
        }

        int valueOffset = Type.MAX_BYTE_LENGTH - typeLengthAsBytes;
        System.arraycopy(inputByteArray, valueOffset, resultByteArray, 1, typeLengthAsBytes);

        BigInteger numericValue = new BigInteger(resultByteArray);
        return type.getConstructor(BigInteger.class).newInstance(numericValue);

    } catch (NoSuchMethodException
            | SecurityException
            | InstantiationException
            | IllegalAccessException
            | IllegalArgumentException
            | InvocationTargetException e) {
        throw new UnsupportedOperationException(
                "Unable to create instance of " + type.getName(), e);
    }
}
 
Example 12
Source File: CommonUtils.java    From WeBASE-Transaction with Apache License 2.0 5 votes vote down vote up
/**
 * stringToSignatureData.
 * 19/12/24 support guomi: add byte[] pub in signatureData
 * @param signatureData signatureData
 * @return
 */
public static SignatureData stringToSignatureData(String signatureData) {
    byte[] byteArr = Numeric.hexStringToByteArray(signatureData);
    byte[] signR = new byte[32];
    System.arraycopy(byteArr, 1, signR, 0, signR.length);
    byte[] signS = new byte[32];
    System.arraycopy(byteArr, 1 + signR.length, signS, 0, signS.length);
    if (EncryptType.encryptType == 1) {
        byte[] pub = new byte[64];
        System.arraycopy(byteArr, 1 + signR.length + signS.length, pub, 0, pub.length);
        return new SignatureData(byteArr[0], signR, signS, pub);
    } else {
        return new SignatureData(byteArr[0], signR, signS);
    }
}
 
Example 13
Source File: CommonUtils.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * stringToSignatureData. 19/12/24 support guomi: add byte[] pub in signatureData
 * 
 * @param signatureData signatureData
 * @return
 */
public static SignatureData stringToSignatureData(String signatureData) {
    byte[] byteArr = Numeric.hexStringToByteArray(signatureData);
    byte[] signR = new byte[32];
    System.arraycopy(byteArr, 1, signR, 0, signR.length);
    byte[] signS = new byte[32];
    System.arraycopy(byteArr, 1 + signR.length, signS, 0, signS.length);
    if (EncryptType.encryptType == 1) {
        byte[] pub = new byte[64];
        System.arraycopy(byteArr, 1 + signR.length + signS.length, pub, 0, pub.length);
        return new SignatureData(byteArr[0], signR, signS, pub);
    } else {
        return new SignatureData(byteArr[0], signR, signS);
    }
}
 
Example 14
Source File: SHA3Digest.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public String hash(String hexInput) {
    byte[] bytes = Numeric.hexStringToByteArray(hexInput);
    byte[] result = hash(bytes);
    return Numeric.toHexString(result);
}
 
Example 15
Source File: ExtendedTransactionDecoder.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static ExtendedRawTransaction decode(String hexTransaction) {
    byte[] transaction = Numeric.hexStringToByteArray(hexTransaction);
    RlpList rlpList = RlpDecoder.decode(transaction);
    RlpList values = (RlpList) rlpList.getValues().get(0);
    BigInteger randomid = ((RlpString) values.getValues().get(0)).asPositiveBigInteger();
    BigInteger gasPrice = ((RlpString) values.getValues().get(1)).asPositiveBigInteger();
    BigInteger gasLimit = ((RlpString) values.getValues().get(2)).asPositiveBigInteger();
    BigInteger blockLimit = ((RlpString) values.getValues().get(3)).asPositiveBigInteger();
    String to = ((RlpString) values.getValues().get(4)).asString();
    BigInteger value = ((RlpString) values.getValues().get(5)).asPositiveBigInteger();
    String data = ((RlpString) values.getValues().get(6)).asString();

    // add extra data
    BigInteger chainId = ((RlpString) values.getValues().get(7)).asPositiveBigInteger();
    BigInteger groupId = ((RlpString) values.getValues().get(8)).asPositiveBigInteger();
    String extraData = ((RlpString) values.getValues().get(9)).asString();
    if (values.getValues().size() > 9) {
        byte v = ((RlpString) values.getValues().get(10)).getBytes()[0];
        byte[] r =
                Numeric.toBytesPadded(
                        Numeric.toBigInt(((RlpString) values.getValues().get(11)).getBytes()),
                        32);
        byte[] s =
                Numeric.toBytesPadded(
                        Numeric.toBigInt(((RlpString) values.getValues().get(12)).getBytes()),
                        32);
        Sign.SignatureData signatureData = new Sign.SignatureData(v, r, s);
        return new SignedExtendedRawTransaction(
                randomid,
                gasPrice,
                gasLimit,
                blockLimit,
                to,
                value,
                data,
                chainId,
                groupId,
                extraData,
                signatureData);
    } else {
        return ExtendedRawTransaction.createTransaction(
                randomid,
                gasPrice,
                gasLimit,
                blockLimit,
                to,
                value,
                data,
                chainId,
                groupId,
                extraData);
    }
}
 
Example 16
Source File: ExtendedTransactionEncoder.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
static List<RlpType> asRlpValues(
        ExtendedRawTransaction rawTransaction, Sign.SignatureData signatureData) {
    List<RlpType> result = new ArrayList<>();
    result.add(RlpString.create(rawTransaction.getRandomid()));
    result.add(RlpString.create(rawTransaction.getGasPrice()));
    result.add(RlpString.create(rawTransaction.getGasLimit()));
    result.add(RlpString.create(rawTransaction.getBlockLimit()));
    // an empty to address (contract creation) should not be encoded as a numeric 0 value
    String to = rawTransaction.getTo();
    if (to != null && to.length() > 0) {
        // addresses that start with zeros should be encoded with the zeros included, not
        // as numeric values
        result.add(RlpString.create(Numeric.hexStringToByteArray(to)));
    } else {
        result.add(RlpString.create(""));
    }

    result.add(RlpString.create(rawTransaction.getValue()));

    // value field will already be hex encoded, so we need to convert into binary first
    byte[] data = Numeric.hexStringToByteArray(rawTransaction.getData());
    result.add(RlpString.create(data));

    // add extra data!!!

    result.add(RlpString.create(rawTransaction.getFiscoChainId()));
    result.add(RlpString.create(rawTransaction.getGroupId()));
    if (rawTransaction.getExtraData() == null) {
        result.add(RlpString.create(""));
    } else {
        result.add(
                RlpString.create(Numeric.hexStringToByteArray(rawTransaction.getExtraData())));
    }
    if (signatureData != null) {
        if (EncryptType.encryptType == 1) {
            // Note: shouldn't trimLeadingZeroes here for the Pub must be with the length of 64
            // Bytes
            result.add(RlpString.create(signatureData.getPub()));
            // logger.debug("RLP-Pub:{},RLP-PubLen:{}",Hex.toHexString(signatureData.getPub()),signatureData.getPub().length);
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR())));
            // logger.debug("RLP-R:{},RLP-RLen:{}",Hex.toHexString(signatureData.getR()),signatureData.getR().length);
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS())));
            // logger.debug("RLP-S:{},RLP-SLen:{}",Hex.toHexString(signatureData.getS()),signatureData.getS().length);
        } else {
            result.add(RlpString.create(signatureData.getV()));
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR())));
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS())));
        }
    }
    return result;
}
 
Example 17
Source File: NameHash.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static byte[] nameHashAsBytes(String ensName) {
    return Numeric.hexStringToByteArray(nameHash(ensName));
}
 
Example 18
Source File: ECRecoverTest.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void testRecoverAddressFromSignature() {
    // CHECKSTYLE:OFF
    String signature =
            "0x2c6401216c9031b9a6fb8cbfccab4fcec6c951cdf40e2320108d1856eb532250576865fbcd452bcdc4c57321b619ed7a9cfd38bd973c3e1e0243ac2777fe9d5b1b";
    // CHECKSTYLE:ON
    String address = "0x31b26e43651e9371c88af3d36c14cfd938baf4fd";
    String message = "v0G9u7huK4mJb2K1";

    String prefix = PERSONAL_MESSAGE_PREFIX + message.length();
    byte[] msgHash = Hash.sha3((prefix + message).getBytes());

    byte[] signatureBytes = Numeric.hexStringToByteArray(signature);
    byte v = signatureBytes[64];
    if (v < 27) {
        v += 27;
    }

    SignatureData sd =
            new SignatureData(
                    v,
                    (byte[]) Arrays.copyOfRange(signatureBytes, 0, 32),
                    (byte[]) Arrays.copyOfRange(signatureBytes, 32, 64));

    String addressRecovered = null;
    boolean match = false;

    // Iterate for each possible key to recover
    for (int i = 0; i < 4; i++) {
        BigInteger publicKey =
                Sign.recoverFromSignature(
                        (byte) i,
                        new ECDSASignature(
                                new BigInteger(1, sd.getR()), new BigInteger(1, sd.getS())),
                        msgHash);

        if (publicKey != null) {
            addressRecovered = "0x" + Keys.getAddress(publicKey);

            if (addressRecovered.equals(address)) {
                match = true;
                break;
            }
        }
    }

    assertThat(addressRecovered, is(address));
    assertTrue(match);
}