org.web3j.crypto.Sign Java Examples

The following examples show how to use org.web3j.crypto.Sign. 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: SignedRawPrivateTransaction.java    From web3j with Apache License 2.0 6 votes vote down vote up
public SignedRawPrivateTransaction(
        final BigInteger nonce,
        final BigInteger gasPrice,
        final BigInteger gasLimit,
        final String to,
        final String data,
        final Sign.SignatureData signatureData,
        final Base64String privateFrom,
        final List<Base64String> privateFor,
        final Base64String privacyGroupId,
        final Restriction restriction) {
    super(
            nonce,
            gasPrice,
            gasLimit,
            to,
            data,
            privateFrom,
            privateFor,
            privacyGroupId,
            restriction);
    this.signatureData = signatureData;
}
 
Example #2
Source File: PrivateTransactionEncoder.java    From web3j with Apache License 2.0 6 votes vote down vote up
public static List<RlpType> asRlpValues(
        final RawPrivateTransaction privateTransaction,
        final Sign.SignatureData signatureData) {

    final List<RlpType> result =
            new ArrayList<>(
                    TransactionEncoder.asRlpValues(
                            privateTransaction.asRawTransaction(), signatureData));

    result.add(privateTransaction.getPrivateFrom().asRlp());

    privateTransaction
            .getPrivateFor()
            .ifPresent(privateFor -> result.add(Base64String.unwrapListToRlp(privateFor)));

    privateTransaction.getPrivacyGroupId().map(Base64String::asRlp).ifPresent(result::add);

    result.add(RlpString.create(privateTransaction.getRestriction().getRestriction()));

    return result;
}
 
Example #3
Source File: TransactionDecoder.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
public Sign.SignatureData getSignatureData(TransactionInput data)
{
    Sign.SignatureData sigData = null;
    if (data.functionData.hasSig && data.sigData != null && data.sigData.size() == 3)
    {
        BigInteger vBi = new BigInteger(data.sigData.get(0), 16);
        BigInteger rBi = new BigInteger(data.sigData.get(1), 16);
        BigInteger sBi = new BigInteger(data.sigData.get(2), 16);
        byte v = (byte) vBi.intValue();
        byte[] r = Numeric.toBytesPadded(rBi, 32);
        byte[] s = Numeric.toBytesPadded(sBi, 32);

        sigData = new Sign.SignatureData(v, r, s);
    }

    return sigData;
}
 
Example #4
Source File: CryptoFunctions.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
public static Sign.SignatureData sigFromByteArray(byte[] sig)
{
    if (sig.length < 64 || sig.length > 65) return null;

    byte   subv = sig[64];
    if (subv < 27) subv += 27;

    byte[] subrRev = Arrays.copyOfRange(sig, 0, 32);
    byte[] subsRev = Arrays.copyOfRange(sig, 32, 64);

    BigInteger r = new BigInteger(1, subrRev);
    BigInteger s = new BigInteger(1, subsRev);

    return new Sign.SignatureData(subv, subrRev, subsRev);
}
 
Example #5
Source File: SpawnableLinkGenerator.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
static byte[] bytesFromSignature(Sign.SignatureData signature)
{
    byte[] sigBytes = new byte[65];
    Arrays.fill(sigBytes, (byte) 0);
    try
    {
        System.arraycopy(signature.getR(), 0, sigBytes, 0, 32);
        System.arraycopy(signature.getS(), 0, sigBytes, 32, 32);
        System.arraycopy(signature.getV(), 0, sigBytes, 64, 1);
    }
    catch (IndexOutOfBoundsException e)
    {
        e.printStackTrace();
    }

    return sigBytes;
}
 
Example #6
Source File: DappBrowserFragment.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
public void testRecoverAddressFromSignature(String message, String sig)
{
    String prefix = PERSONAL_MESSAGE_PREFIX + message.length();
    byte[] msgHash = (prefix + message).getBytes();

    byte[] signatureBytes = Numeric.hexStringToByteArray(sig);
    Sign.SignatureData sd = sigFromByteArray(signatureBytes);
    String addressRecovered;

    try
    {
        BigInteger recoveredKey = Sign.signedMessageToKey(msgHash, sd);
        addressRecovered = "0x" + Keys.getAddress(recoveredKey);
        System.out.println("Recovered: " + addressRecovered);
    }
    catch (SignatureException e)
    {
        e.printStackTrace();
    }
}
 
Example #7
Source File: UniversalLinkTypeTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private String ecRecoverAddress(byte[] data, Sign.SignatureData signature) //get the hex string address from the sig and data
{
    String address = "";
    try
    {
        BigInteger recoveredKey = Sign.signedMessageToKey(data, signature); //get embedded address
        address = Keys.getAddress(recoveredKey);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return address;
}
 
Example #8
Source File: NodeIdTool.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
public static BigInteger testBlock(PlatonBlock.Block block){
    String extraData = block.getExtraData();
    String signature = extraData.substring(66, extraData.length());
    byte[] msgHash = getMsgHash(block);
    byte[] signatureBytes = Numeric.hexStringToByteArray(signature);
    byte v = signatureBytes[64];
    byte[] r = Arrays.copyOfRange(signatureBytes, 0, 32);
    byte[] s = Arrays.copyOfRange(signatureBytes, 32, 64);
    return Sign.recoverFromSignature( v, new ECDSASignature(new BigInteger(1, r), new BigInteger(1, s)), msgHash);
}
 
Example #9
Source File: UniversalLinkTypeTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private String ecRecoverAddress() throws Exception
{
    String testSigMsg = "obtain public key";
    Sign.SignatureData testSig = Sign.signMessage(testSigMsg.getBytes(), testKey);
    BigInteger recoveredKey = Sign.signedMessageToKey(testSigMsg.getBytes(), testSig);

    return Keys.getAddress(recoveredKey);
}
 
Example #10
Source File: QRSelectionTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private String ecRecoverAddress(byte[] data, Sign.SignatureData signature) //get the hex string address from the sig and data
{
    String address = "";
    try
    {
        BigInteger recoveredKey = Sign.signedMessageToKey(data, signature); //get embedded address
        address = Keys.getAddress(recoveredKey);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return address;
}
 
Example #11
Source File: QRSelectionTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public static Sign.SignatureData sigFromBase64Fix(byte[] sig) {
    byte subv = (byte) (sig[64] + 27);
    if (subv > 30)
        subv -= 27;

    byte[] subrRev = Arrays.copyOfRange(sig, 0, 32);
    byte[] subsRev = Arrays.copyOfRange(sig, 32, 64);

    return new Sign.SignatureData(subv, subrRev, subsRev);
}
 
Example #12
Source File: CryptoFunctions.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
@Override
public BigInteger signedMessageToKey(byte[] data, byte[] signature) throws SignatureException
{
    Sign.SignatureData sigData = sigFromByteArray(signature);
    if (sigData == null) return BigInteger.ZERO;
    else return Sign.signedMessageToKey(data, sigData);
}
 
Example #13
Source File: CryptoFunctions.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public static Sign.SignatureData sigFromByteArray(byte[] sig)
{
    if (sig.length < 64 || sig.length > 65) return null;

    byte   subv = sig[64];
    if (subv < 27) subv += 27;

    byte[] subrRev = Arrays.copyOfRange(sig, 0, 32);
    byte[] subsRev = Arrays.copyOfRange(sig, 32, 64);

    BigInteger r = new BigInteger(1, subrRev);
    BigInteger s = new BigInteger(1, subsRev);

    return new Sign.SignatureData(subv, subrRev, subsRev);
}
 
Example #14
Source File: CryptoFunctions.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
@Override
public BigInteger signedMessageToKey(byte[] data, byte[] signature) throws SignatureException
{
    Sign.SignatureData sigData = sigFromByteArray(signature);
    if (sigData == null) return BigInteger.ZERO;
    else return Sign.signedMessageToKey(data, sigData);
}
 
Example #15
Source File: CryptoFunctions.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public static Sign.SignatureData sigFromByteArray(byte[] sig)
{
    if (sig.length < 64 || sig.length > 65) return null;

    byte   subv = sig[64];
    if (subv < 27) subv += 27;

    byte[] subrRev = Arrays.copyOfRange(sig, 0, 32);
    byte[] subsRev = Arrays.copyOfRange(sig, 32, 64);

    BigInteger r = new BigInteger(1, subrRev);
    BigInteger s = new BigInteger(1, subsRev);

    return new Sign.SignatureData(subv, subrRev, subsRev);
}
 
Example #16
Source File: PrivateTransactionEncoder.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static byte[] signMessage(
        final RawPrivateTransaction rawTransaction, final Credentials credentials) {
    final byte[] encodedTransaction = encode(rawTransaction);
    final Sign.SignatureData signatureData =
            Sign.signMessage(encodedTransaction, credentials.getEcKeyPair());

    return encode(rawTransaction, signatureData);
}
 
Example #17
Source File: PrivateTransactionEncoder.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static byte[] signMessage(
        final RawPrivateTransaction rawTransaction,
        final long chainId,
        final Credentials credentials) {
    final byte[] encodedTransaction = encode(rawTransaction, chainId);
    final Sign.SignatureData signatureData =
            Sign.signMessage(encodedTransaction, credentials.getEcKeyPair());

    final Sign.SignatureData eip155SignatureData =
            TransactionEncoder.createEip155SignatureData(signatureData, chainId);
    return encode(rawTransaction, eip155SignatureData);
}
 
Example #18
Source File: UniversalLinkTypeTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private byte[] getSignature(byte[] message) throws SalesOrderMalformed {
    Sign.SignatureData sigData = Sign.signMessage(message, testKey);

    byte[] sig = new byte[65];

    try {
        System.arraycopy(sigData.getR(), 0, sig, 0, 32);
        System.arraycopy(sigData.getS(), 0, sig, 32, 32);
        System.arraycopy(sigData.getV(), 0, sig, 64, 1);
    } catch (IndexOutOfBoundsException e) {
        throw new SalesOrderMalformed("Signature shorter than expected 256");
    }

    return sig;
}
 
Example #19
Source File: UniversalLinkTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private String ecRecoverAddress() throws Exception
{
    String testSigMsg = "obtain public key";
    Sign.SignatureData testSig = Sign.signMessage(testSigMsg.getBytes(), testKey);
    BigInteger recoveredKey = Sign.signedMessageToKey(testSigMsg.getBytes(), testSig);

    return Keys.getAddress(recoveredKey);
}
 
Example #20
Source File: UniversalLinkTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private boolean verifySignature(byte[] message, byte[] signature) {
    boolean pass = false;
    try {
        Sign.SignatureData sig = sigFromByteArray(signature);
        String address = ecRecoverAddress(message, sig);

        if (Numeric.cleanHexPrefix(address).equalsIgnoreCase(Numeric.cleanHexPrefix(OWNER_ADDR)))
        {
            pass = true;
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return pass;
}
 
Example #21
Source File: UniversalLinkTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private String ecRecoverAddress(byte[] data, Sign.SignatureData signature) //get the hex string address from the sig and data
{
    String address = "";
    try
    {
        BigInteger recoveredKey = Sign.signedMessageToKey(data, signature); //get embedded address
        address = Keys.getAddress(recoveredKey);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return address;
}
 
Example #22
Source File: UniversalLinkTest.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private byte[] getSignature(byte[] message) throws SalesOrderMalformed {
    Sign.SignatureData sigData = Sign.signMessage(message, testKey);

    byte[] sig = new byte[65];

    try {
        System.arraycopy(sigData.getR(), 0, sig, 0, 32);
        System.arraycopy(sigData.getS(), 0, sig, 32, 32);
        System.arraycopy(sigData.getV(), 0, sig, 64, 1);
    } catch (IndexOutOfBoundsException e) {
        throw new SalesOrderMalformed("Signature shorter than expected 256");
    }

    return sig;
}
 
Example #23
Source File: AlphaWalletService.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private void addSignature(Map<String, String> args, byte[] sig)
{
    Sign.SignatureData sigData = sigFromByteArray(sig);
    if (sigData != null)
    {
        args.put("r", Numeric.toHexString(sigData.getR()));
        args.put("s", Numeric.toHexString(sigData.getS()));
        args.put("v", Numeric.toHexString(sigData.getV()));
    }
}
 
Example #24
Source File: MarketQueueService.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private BigInteger ecRecoverPublicKey(Wallet wallet, String password, int chainId) throws Exception
{
    String testSigMsg = "obtain public key";
    byte[] testSigBytes = transactionRepository.getSignatureFast(wallet, password, testSigMsg.getBytes(), chainId).blockingGet();
    Sign.SignatureData testSig = sigFromByteArray(testSigBytes);
    BigInteger recoveredKey = Sign.signedMessageToKey(testSigMsg.getBytes(), testSig);
    String publicKeyString = Keys.getAddress(recoveredKey); //TODO: Remove - this is here for debug/testing

    return recoveredKey;
}
 
Example #25
Source File: CreateTransactionInteract.java    From Upchain-wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
public Single<byte[]> getSignature(ETHWallet wallet, byte[] message, String password) {
    return  Single.fromCallable(() -> {
        Credentials credentials = WalletUtils.loadCredentials(password, wallet.getKeystorePath());
        Sign.SignatureData signatureData = Sign.signMessage(
                message, credentials.getEcKeyPair());

        List<RlpType> result = new ArrayList<>();
        result.add(RlpString.create(message));

        if (signatureData != null) {
            result.add(RlpString.create(signatureData.getV()));
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR())));
            result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS())));
        }

        RlpList rlpList = new RlpList(result);
        return RlpEncoder.encode(rlpList);
    });
}
 
Example #26
Source File: TransactionRepository.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private Single<byte[]> encodeTransaction(byte[] signatureBytes, RawTransaction rtx)
{
	return Single.fromCallable(() -> {
		Sign.SignatureData sigData = sigFromByteArray(signatureBytes);
		if (sigData == null) return FAILED_SIGNATURE.getBytes();
		return encode(rtx, sigData);
	});
}
 
Example #27
Source File: Transaction.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private TransactionOperation[] processTrade(TransactionInput f, String contractAddress)
{
	TransactionOperation[] o;
	try
	{
		Sign.SignatureData sig = decoder.getSignatureData(f);
		//ecrecover the recipient of the ether
		int[] ticketIndexArray = decoder.getIndices(f);
		String expiryStr = f.miscData.get(0);
		long expiry = Long.valueOf(expiryStr, 16);
		BigInteger priceWei = new BigInteger(value);
		contractAddress = to;
		o = generateERC875Op();
		TransactionOperation op = o[0];
		TransactionContract ct = op.contract;
		if (error.equals("0")) //don't bother checking signature unless the transaction succeeded
		{
			if (parser == null) parser = new ParseMagicLink(new CryptoFunctions(), EthereumNetworkRepository.extraChains()); //parser on demand
			byte[] tradeBytes = parser.getTradeBytes(ticketIndexArray, contractAddress, priceWei, expiry);
			//attempt ecrecover
			BigInteger key = Sign.signedMessageToKey(tradeBytes, sig);
			ct.setOtherParty("0x" + Keys.getAddress(key));
		}
		ct.address = contractAddress;
		ct.setIndicies(f.paramValues);
		ct.name = contractAddress;
	}
	catch (Exception e)
	{
		o = generateERC875Op();
		e.printStackTrace();
	}

	return o;
}
 
Example #28
Source File: CryptoFunctions.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
@Override
public BigInteger signedMessageToKey(byte[] data, byte[] signature) throws SignatureException
{
    Sign.SignatureData sigData = sigFromByteArray(signature);
    if (sigData == null) return BigInteger.ZERO;
    return Sign.signedMessageToKey(data, sigData);
}
 
Example #29
Source File: MagicLinkParcel.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public static byte[] generateReverseTradeData(MagicLinkData order, Token token, String recipient)
{
    byte[] data = null;
    try
    {
        List<BigInteger> tokenElements = new ArrayList<>();
        BigInteger expiry = BigInteger.valueOf(order.expiry);
        //convert to signature representation
        Sign.SignatureData sellerSig = CryptoFunctions.sigFromByteArray(order.signature);
        int v = (new BigInteger(sellerSig.getV())).intValue();

        switch (order.contractType)
        {
            case spawnable:
                data = TokenRepository.createSpawnPassTo(token, expiry, order.tokenIds, v, sellerSig.getR(), sellerSig.getS(), recipient);
                break;
            case currencyLink:
                // for testing only, we would be using an intermediate server
                data = TokenRepository.createDropCurrency(order, v, sellerSig.getR(), sellerSig.getS(), recipient);
                break;
            default:
                for (int ticketIndex : order.indices) {
                    tokenElements.add(BigInteger.valueOf(ticketIndex));
                }
                data = TokenRepository.createTrade(token, expiry, tokenElements, v, sellerSig.getR(), sellerSig.getS());
                break;
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return data;
}
 
Example #30
Source File: PrivateTransactionDecoderTest.java    From web3j with Apache License 2.0 4 votes vote down vote up
@Test
public void testDecodingSignedPrivacyGroup() throws Exception {
    final BigInteger nonce = BigInteger.ZERO;
    final BigInteger gasPrice = BigInteger.ONE;
    final BigInteger gasLimit = BigInteger.TEN;
    final String to = "0x0add5355";
    final RawPrivateTransaction rawTransaction =
            RawPrivateTransaction.createTransaction(
                    nonce,
                    gasPrice,
                    gasLimit,
                    to,
                    "",
                    MOCK_ENCLAVE_KEY,
                    MOCK_ENCLAVE_KEY,
                    RESTRICTED);
    final String privateKey =
            "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63";
    final Credentials credentials = Credentials.create(privateKey);
    final byte[] encodedMessage =
            PrivateTransactionEncoder.signMessage(rawTransaction, credentials);
    final String hexMessage = Numeric.toHexString(encodedMessage);

    final RawPrivateTransaction result = PrivateTransactionDecoder.decode(hexMessage);
    assertNotNull(result);
    assertEquals(nonce, result.getNonce());
    assertEquals(gasPrice, result.getGasPrice());
    assertEquals(gasLimit, result.getGasLimit());
    assertEquals(to, result.getTo());
    assertEquals("", result.getData());
    assertEquals(MOCK_ENCLAVE_KEY, result.getPrivateFrom());
    assertEquals(MOCK_ENCLAVE_KEY, result.getPrivacyGroupId().get());
    assertEquals(RESTRICTED, result.getRestriction());
    assertTrue(result instanceof SignedRawPrivateTransaction);
    final SignedRawPrivateTransaction signedResult = (SignedRawPrivateTransaction) result;
    assertNotNull(signedResult.getSignatureData());
    Sign.SignatureData signatureData = signedResult.getSignatureData();
    final byte[] encodedTransaction = PrivateTransactionEncoder.encode(rawTransaction);
    final BigInteger key = Sign.signedMessageToKey(encodedTransaction, signatureData);
    assertEquals(key, credentials.getEcKeyPair().getPublicKey());
    assertEquals(credentials.getAddress(), signedResult.getFrom());
    signedResult.verify(credentials.getAddress());
    assertNull(signedResult.getChainId());
}