Java Code Examples for org.spongycastle.util.BigIntegers#asUnsignedByteArray()

The following examples show how to use org.spongycastle.util.BigIntegers#asUnsignedByteArray() . 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: EthTransaction.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
private void validate() {
        if (getNonce().length > HASH_LENGTH) throw new RuntimeException("Nonce is not valid");
        if (receiveAddress != null && receiveAddress.length != 0 && receiveAddress.length !=
                ADDRESS_LENGTH)
            throw new RuntimeException("Receive address is not valid");
        if (gasLimit.length > HASH_LENGTH)
            throw new RuntimeException("Gas Limit is not valid");
        if (gasPrice != null && gasPrice.length > HASH_LENGTH)
            throw new RuntimeException("Gas Price is not valid");
        if (value != null && value.length > HASH_LENGTH)
            throw new RuntimeException("Value is not valid");
        if (getSignature() != null) {
            if (BigIntegers.asUnsignedByteArray(signature.r).length > HASH_LENGTH)
                throw new RuntimeException("Signature R is not valid");
            if (BigIntegers.asUnsignedByteArray(signature.s).length > HASH_LENGTH)
                throw new RuntimeException("Signature S is not valid");
//            if (getSender() != null && getSender().length != ADDRESS_LENGTH)
//                throw new RuntimeException("Sender is not valid");
        }
    }
 
Example 2
Source File: Transaction.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
private void validate() {
  if (getNonce().length > HASH_LENGTH) throw new RuntimeException("Nonce is not valid");
  if (receiveAddress != null
      && receiveAddress.length != 0
      && receiveAddress.length != ADDRESS_LENGTH) {
    throw new RuntimeException("Receive address is not valid");
  }
  if (gasLimit.length > HASH_LENGTH) throw new RuntimeException("Gas Limit is not valid");
  if (gasPrice != null && gasPrice.length > HASH_LENGTH) {
    throw new RuntimeException("Gas Price is not valid");
  }
  if (value != null && value.length > HASH_LENGTH) {
    throw new RuntimeException("Value is not valid");
  }
  if (getSignature() != null) {
    if (BigIntegers.asUnsignedByteArray(signature.r).length > HASH_LENGTH) {
      throw new RuntimeException("Signature R is not valid");
    }
    if (BigIntegers.asUnsignedByteArray(signature.s).length > HASH_LENGTH) {
      throw new RuntimeException("Signature S is not valid");
    }
    if (getSender() != null && getSender().length != ADDRESS_LENGTH) {
      throw new RuntimeException("Sender is not valid");
    }
  }
}
 
Example 3
Source File: ECKeySecp256k1.java    From aion with MIT License 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private key as an AES key");
    }

    AESFastEngine engine = new AESFastEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key =
            new KeyParameter(
                    BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize()) {
            break;
        }
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example 4
Source File: TransactionTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test
    public void testTransactionCreateContract() {

//        String rlp = "f89f808609184e72a0008203e8808203e8b84b4560005444602054600f60056002600a02010b0d630000001d596002602054630000003b5860066000530860056006600202010a0d6300000036596004604054630000003b5860056060541ca0ddc901d83110ea50bc40803f42083afea1bbd420548f6392a679af8e24b21345a06620b3b512bea5f0a272703e8d6933177c23afc79516fd0ca4a204aa6e34c7e9";

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

        byte[] nonce			= BigIntegers.asUnsignedByteArray(BigInteger.ZERO);
        byte[] gasPrice			= Hex.decode("09184e72a000");		// 10000000000000
        byte[] gas				= Hex.decode("03e8");			// 1000
        byte[] recieveAddress	= null;
        byte[] endowment     	= Hex.decode("03e8"); //10000000000000000"
        byte[] init 			= Hex.decode("4560005444602054600f60056002600a02010b0d630000001d596002602054630000003b5860066000530860056006600202010a0d6300000036596004604054630000003b586005606054");


        Transaction tx1 = new Transaction(nonce, gasPrice, gas,
                recieveAddress, endowment, init);
        tx1.sign(senderPrivKey);

        byte[] payload = tx1.getEncoded();


        System.out.println(Hex.toHexString(payload));
        Transaction tx2 = new Transaction(payload);
//        tx2.getSender();

        String plainTx1 = Hex.toHexString(tx1.getEncodedRaw());
        String plainTx2 = Hex.toHexString(tx2.getEncodedRaw());

//        Transaction tx = new Transaction(Hex.decode(rlp));

        System.out.println("tx1.hash: " + Hex.toHexString(tx1.getHash()));
        System.out.println("tx2.hash: " + Hex.toHexString(tx2.getHash()));
        System.out.println();
        System.out.println("plainTx1: " + plainTx1 );
        System.out.println("plainTx2: " + plainTx2 );

        System.out.println( Hex.toHexString(tx2.getSender()));
    }
 
Example 5
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private " +
                "key as an AES key");
    }

    AESEngine engine = new AESEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray((
            (BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize()) {
            break;
        }
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example 6
Source File: Peer.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public byte[] calcDistance(Peer toPeer) {

        BigInteger aaPeer = new BigInteger(getId());
        BigInteger bbPeer = new BigInteger(toPeer.getId());

        BigInteger distance = aaPeer.xor(bbPeer);
        return BigIntegers.asUnsignedByteArray(distance);
    }
 
Example 7
Source File: CallTransaction.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 5 votes vote down vote up
public static EthTransaction createRawTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String toAddress,
                                                  BigInteger value, byte[] data) {
    EthTransaction tx = new EthTransaction(BigIntegers.asUnsignedByteArray(nonce),
            BigIntegers.asUnsignedByteArray(gasPrice),
            BigIntegers.asUnsignedByteArray(gasLimit),
            toAddress == null ? null : Hex.decode(toAddress),
            BigIntegers.asUnsignedByteArray(value),
            data,
            null);
    return tx;
}
 
Example 8
Source File: EthTransaction.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @deprecated use
 * {@link EthTransaction#create(String, BigInteger, BigInteger, BigInteger, BigInteger, Integer)} instead
 */
public static EthTransaction create(String to, BigInteger amount, BigInteger nonce,
                                    BigInteger gasPrice, BigInteger gasLimit) {
    return new EthTransaction(BigIntegers.asUnsignedByteArray(nonce),
            BigIntegers.asUnsignedByteArray(gasPrice),
            BigIntegers.asUnsignedByteArray(gasLimit),
            Hex.decode(to),
            BigIntegers.asUnsignedByteArray(amount),
            null);
}
 
Example 9
Source File: TransactionTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test
public void testTransactionFromNew2() throws MissingPrivateKeyException {
       byte[] privKeyBytes = Hex.decode("c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4");
       
       String RLP_TX_UNSIGNED = "eb8085e8d4a510008227109413978aee95f38490e9769c39b2773ed763d9cd5f872386f26fc1000080808080";
       String RLP_TX_SIGNED = "f86b8085e8d4a510008227109413978aee95f38490e9769c39b2773ed763d9cd5f872386f26fc10000801ba0eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4a014a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1";
       String HASH_TX_UNSIGNED = "328ea6d24659dec48adea1aced9a136e5ebdf40258db30d1b1d97ed2b74be34e";
       
	byte[] nonce			= BigIntegers.asUnsignedByteArray(BigInteger.ZERO);
	byte[] gasPrice			= Hex.decode("e8d4a51000");		// 1000000000000
	byte[] gas				= Hex.decode("2710");			// 10000
	byte[] recieveAddress	= Hex.decode("13978aee95f38490e9769c39b2773ed763d9cd5f");
	byte[] value			= Hex.decode("2386f26fc10000"); //10000000000000000"
	byte[] data 			= new byte[0];
	
   	Transaction tx = new Transaction(nonce, gasPrice, gas, recieveAddress, value, data);
   	    	
   	// Testing unsigned
   	String encodedUnsigned = Hex.toHexString(tx.getEncoded());
       assertEquals(RLP_TX_UNSIGNED, encodedUnsigned);
       assertEquals(HASH_TX_UNSIGNED, Hex.toHexString(tx.getHash()));

       // Testing signed
       tx.sign(privKeyBytes);
       String encodedSigned = Hex.toHexString(tx.getEncoded());       
       assertEquals(RLP_TX_SIGNED, encodedSigned);
       assertEquals(HASH_TX_UNSIGNED, Hex.toHexString(tx.getHash()));
}
 
Example 10
Source File: ECKey.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher
 *            -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private key as an AES key");
    }

    AESFastEngine engine = new AESFastEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize())
            break;
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example 11
Source File: BlockHeader.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Verify that block is valid for its difficulty
 * 
 * @return boolean
 */
public boolean validateNonce() {
	BigInteger max = BigInteger.valueOf(2).pow(256);
	byte[] target = BigIntegers.asUnsignedByteArray(32,
			max.divide(new BigInteger(1, this.getDifficulty())));
	byte[] hash = HashUtil.sha3(this.getEncodedWithoutNonce());
	byte[] concat = Arrays.concatenate(hash, this.getNonce());
	byte[] result = HashUtil.sha3(concat);
	return FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0;
}
 
Example 12
Source File: SerpentCompiler.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 *
 * @param code
 * @param init
 * @return encoded bytes
 */
public static byte[] encodeMachineCodeForVMRun(byte[] code, byte[] init) {

    if (code == null || code.length == 0) throw new RuntimeException("code can't be empty code: " + code);

    int numBytes = ByteUtil.numBytes(code.length + "");
    byte[] lenBytes = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(code.length));

    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < lenBytes.length; ++i) {
        sb.append(lenBytes[i]).append(" ");
    }

    // calc real code start position (after the init header)
    int pos = 10  + numBytes * 2;
    if (init != null) pos+=init.length;

    // @push_len @len PUSH1 @src_start  PUSH1 0 CODECOPY @push_len @len 0 PUSH1 0 RETURN
    String header =  String.format("[asm %s %s PUSH1 %d  PUSH1 0 CODECOPY %s %s PUSH1 0 RETURN asm]",
            "PUSH" + numBytes, sb.toString(), pos , "PUSH" + numBytes, sb.toString());

    byte[] headerMachine = compileAssemblyToMachine(header);

    byte[] result = init != null ? Arrays.concatenate(init, headerMachine, code) :
            Arrays.concatenate(headerMachine, code);

    return result;
}
 
Example 13
Source File: Transaction.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @deprecated use {@link Transaction#create(String, BigInteger, BigInteger, BigInteger, * BigInteger, Integer)} instead
 */
public static Transaction create(String to, BigInteger amount, BigInteger nonce,
    BigInteger gasPrice, BigInteger gasLimit) {
  return new Transaction(BigIntegers.asUnsignedByteArray(nonce),
      BigIntegers.asUnsignedByteArray(gasPrice), BigIntegers.asUnsignedByteArray(gasLimit),
      Hex.decode(to), BigIntegers.asUnsignedByteArray(amount), null);
}
 
Example 14
Source File: ContractSubmitDialog.java    From ethereumj with MIT License 4 votes vote down vote up
private Transaction createTransaction() {

        Account account = ((AccountWrapper)creatorAddressCombo.getSelectedItem()).getAccount();

        byte[] senderPrivKey = account.getEcKey().getPrivKeyBytes();
        byte[] nonce = account.getNonce() == BigInteger.ZERO ? null : account.getNonce().toByteArray();
        byte[] gasPrice = new BigInteger("10000000000000").toByteArray();

        BigInteger gasBI = new BigInteger(gasInput.getText());
        byte[] gasValue  = BigIntegers.asUnsignedByteArray(gasBI);
        byte[] endowment = BigIntegers.asUnsignedByteArray(new BigInteger("1000"));

        byte[] zeroAddress = null;

//        UIEthereumManager.ethereum.createTransaction();

        Transaction tx = new Transaction(nonce, gasPrice, gasValue,
                zeroAddress, endowment, initByteCode);

        tx.sign(senderPrivKey);

        return tx;
    }
 
Example 15
Source File: MiningBlockHeader.java    From aion with MIT License 4 votes vote down vote up
public byte[] getPowBoundary() {
    return BigIntegers.asUnsignedByteArray(
            32, BigInteger.ONE.shiftLeft(256).divide(getDifficultyBI()));
}
 
Example 16
Source File: Miner.java    From ethereumj with MIT License 4 votes vote down vote up
/**
	 * Adds a nonce to given block which complies with the given difficulty
	 * 
	 * For the PoC series, we use a simplified proof-of-work. 
	 * This is not ASIC resistant and is meant merely as a placeholder. 
	 * It utilizes the bare SHA3 hash function to secure the block chain by requiring 
	 * the SHA3 hash of the concatenation of the nonce and the header’s SHA3 hash to be 
	 * sufficiently low. It is formally defined as PoW:
	 * 
	 * 		PoW(H, n) ≡ BE(SHA3(SHA3(RLP(H!n)) ◦ n))
	 *
	 * 	where:
	 * 		RLP(H!n) is the RLP encoding of the block header H, not including the
	 *			final nonce component;
	 *		SHA3 is the SHA3 hash function accepting an arbitrary length series of
	 *			bytes and evaluating to a series of 32 bytes (i.e. 256-bit);
	 *		n is the nonce, a series of 32 bytes;
	 *		o is the series concatenation operator;
	 *		BE(X) evaluates to the value equal to X when interpreted as a
	 *			big-endian-encoded integer.
	 * 
	 * @param newBlock without a valid nonce
	 * @param difficulty - the mining difficulty
	 * @return true if valid nonce has been added to the block
	 */
	public boolean mine(Block newBlock, byte[] difficulty) {

		BigInteger max = BigInteger.valueOf(2).pow(256);
		byte[] target = BigIntegers.asUnsignedByteArray(32,
				max.divide(new BigInteger(1, difficulty)));

		byte[] hash = HashUtil.sha3(newBlock.getEncodedWithoutNonce());
		byte[] testNonce = new byte[32];
		byte[] concat;
		
		while(ByteUtil.increment(testNonce)) {
			concat = Arrays.concatenate(hash, testNonce);
			byte[] result = HashUtil.sha3(concat);
			if(FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0) {
				newBlock.setNonce(testNonce);
//				System.out.println(Hex.toHexString(newBlock.getEncoded()));
				return true;
			}
		}
		return false; // couldn't find a valid nonce
	}
 
Example 17
Source File: Transaction.java    From asf-sdk with GNU General Public License v3.0 4 votes vote down vote up
public static Transaction create(String to, BigInteger amount, BigInteger nonce,
    BigInteger gasPrice, BigInteger gasLimit, Integer chainId) {
  return new Transaction(BigIntegers.asUnsignedByteArray(nonce),
      BigIntegers.asUnsignedByteArray(gasPrice), BigIntegers.asUnsignedByteArray(gasLimit),
      Hex.decode(to), BigIntegers.asUnsignedByteArray(amount), null, chainId);
}
 
Example 18
Source File: ContractCallDialog.java    From ethereumj with MIT License 4 votes vote down vote up
private Transaction createTransaction() {

		byte[] data;
		if (!msgDataTA.getText().trim().equals("")) {
			Object[] lexaList = msgDataTA.getText().split(",");
			data = ByteUtil.encodeDataList(lexaList);
		} else {
			data = new byte[] {};
		}

        byte[] contractAddress = Hex.decode( contractAddrInput.getText());

        Account account = ((AccountWrapper)creatorAddressCombo.getSelectedItem()).getAccount();

        byte[] senderPrivKey = account.getEcKey().getPrivKeyBytes();
        byte[] nonce = account.getNonce() == BigInteger.ZERO ? null : account.getNonce().toByteArray();
        BigInteger gasPrice = new BigInteger("10000000000000");

        BigInteger gasBI = new BigInteger(gasInput.getText());
        byte[] gasValue  = BigIntegers.asUnsignedByteArray(gasBI);
        BigInteger endowment = new BigInteger("1000");

        if (logger.isInfoEnabled()) {
            logger.info("Contract call:");
            logger.info("tx.nonce: {}", nonce == null ? "null" : Hex.toHexString(nonce));
            logger.info("tx.gasPrice: {}", Hex.toHexString(BigIntegers.asUnsignedByteArray( gasPrice )));
            logger.info("tx.gasValue: {}", Hex.toHexString(gasValue));
            logger.info("tx.address: {}", Hex.toHexString(contractAddress));
            logger.info("tx.endowment: {}", Hex.toHexString(BigIntegers.asUnsignedByteArray( endowment)));
            logger.info("tx.data: {}", Hex.toHexString(data));
        }

        Transaction tx = UIEthereumManager.ethereum.createTransaction(account.getNonce(),
                gasPrice, gasBI,
                contractAddress, endowment, data);

        try {
            tx.sign(senderPrivKey);
        } catch (Exception e1) {
            dialog.alertStatusMsg("Failed to sign the transaction");
            return null;
        }
        return tx;
    }
 
Example 19
Source File: EthereumIESEngine.java    From wkcwallet-java with Apache License 2.0 4 votes vote down vote up
public byte[] processBlock(
        byte[] in,
        int inOff,
        int inLen,
        byte[] macData)
        throws InvalidCipherTextException
    {
        if (forEncryption)
        {
            if (keyPairGenerator != null)
            {
                EphemeralKeyPair ephKeyPair = keyPairGenerator.generate();

                this.privParam = ephKeyPair.getKeyPair().getPrivate();
                this.V = ephKeyPair.getEncodedPublicKey();
            }
        }
        else
        {
            if (keyParser != null)
            {
                ByteArrayInputStream bIn = new ByteArrayInputStream(in, inOff, inLen);

                try
                {
                    this.pubParam = keyParser.readKey(bIn);
                }
                catch (IOException e)
                {
                    throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.getMessage(), e);
                }

                int encLength = (inLen - bIn.available());
                this.V = Arrays.copyOfRange(in, inOff, inOff + encLength);
            }
        }

        // Compute the common value and convert to byte array.
        agree.init(privParam);
        BigInteger z = agree.calculateAgreement(pubParam);
        byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

        // Create input to KDF.
        byte[] VZ;
//        if (V.length != 0)
//        {
//            VZ = new byte[V.length + Z.length];
//            System.arraycopy(V, 0, VZ, 0, V.length);
//            System.arraycopy(Z, 0, VZ, V.length, Z.length);
//        }
//        else
        {
            VZ = Z;
        }

        // Initialise the KDF.
        DerivationParameters kdfParam;
        if (kdf instanceof MGF1BytesGeneratorExt) {
            kdfParam = new MGFParameters(VZ);
        } else {
            kdfParam = new KDFParameters(VZ, param.getDerivationV());
        }
        kdf.init(kdfParam);

        return forEncryption
            ? encryptBlock(in, inOff, inLen, macData)
            : decryptBlock(in, inOff, inLen, macData);
    }
 
Example 20
Source File: MyHMacDSAKCalculator.java    From token-core-android with Apache License 2.0 2 votes vote down vote up
public void init(BigInteger n, BigInteger d, byte[] message) {
  this.n = n;
  this.needTry = false;

  Arrays.fill(V, (byte) 0x01);
  Arrays.fill(K, (byte) 0);

  byte[] x = new byte[(n.bitLength() + 7) / 8];
  byte[] dVal = BigIntegers.asUnsignedByteArray(d);

  System.arraycopy(dVal, 0, x, x.length - dVal.length, dVal.length);

  byte[] m = new byte[(n.bitLength() + 7) / 8];

  BigInteger mInt = bitsToInt(message);

  if (mInt.compareTo(n) > 0) {
    mInt = mInt.subtract(n);
  }

  byte[] mVal = BigIntegers.asUnsignedByteArray(mInt);

  System.arraycopy(mVal, 0, m, m.length - mVal.length, mVal.length);

  hMac.init(new KeyParameter(K));

  hMac.update(V, 0, V.length);
  hMac.update((byte) 0x00);
  hMac.update(x, 0, x.length);
  hMac.update(m, 0, m.length);

  hMac.doFinal(K, 0);

  hMac.init(new KeyParameter(K));

  hMac.update(V, 0, V.length);

  hMac.doFinal(V, 0);

  hMac.update(V, 0, V.length);
  hMac.update((byte) 0x01);
  hMac.update(x, 0, x.length);
  hMac.update(m, 0, m.length);

  hMac.doFinal(K, 0);

  hMac.init(new KeyParameter(K));

  hMac.update(V, 0, V.length);

  hMac.doFinal(V, 0);
}