Java Code Examples for org.spongycastle.util.Arrays#copyOfRange()

The following examples show how to use org.spongycastle.util.Arrays#copyOfRange() . 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: ContractEventParser.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * support: uint<m> (m ∈ [8, 256], m % 8 == 0), int<m> (m ∈ [8, 256], m % 8 == 0) uint (solidity
 * abi will auto convert to uint256) int (solidity abi will auto convert to int256) bool
 * <p>
 * otherwise, returns hexString
 * <p>
 * This is only for decode Topic. Since Topic and Data use different encode methods when deal
 * dynamic length types, such as bytes and string.
 */
protected static String parseTopic(byte[] bytes, String typeStr) {
    if (ArrayUtils.isEmpty(bytes) || StringUtils.isNullOrEmpty(typeStr)) {
        return "";
    }
    Type type = basicType(typeStr);
    if (type == Type.INT_NUMBER) {
        return DataWord.bigIntValue(bytes);
    } else if (type == Type.BOOL) {
        return String.valueOf(!DataWord.isZero(bytes));
    } else if (type == Type.ADDRESS) {
        byte[] last20Bytes = Arrays.copyOfRange(bytes, 12, bytes.length);
        return Wallet.encode58Check(MUtil.convertToGSCAddress(last20Bytes));
    }
    return Hex.toHexString(bytes);
}
 
Example 2
Source File: KeyChainGroupTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deterministicUpgradeRotating() throws Exception {
    group = new KeyChainGroup(PARAMS);
    group.setLookaheadSize(LOOKAHEAD_SIZE);   // Don't want slow tests.
    long now = Utils.currentTimeSeconds();
    ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key2 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key3 = new ECKey();
    group.importKeys(key2, key1, key3);
    group.upgradeToDeterministic(now + 10, null);
    DeterministicSeed seed = group.getActiveKeyChain().getSeed();
    assertNotNull(seed);
    // Check we used the right key: oldest non rotating.
    byte[] truncatedBytes = Arrays.copyOfRange(key2.getSecretBytes(), 0, 16);
    assertArrayEquals(seed.getEntropyBytes(), truncatedBytes);
}
 
Example 3
Source File: KeyChainGroupTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deterministicUpgradeEncrypted() throws Exception {
    group = new KeyChainGroup(PARAMS);
    final ECKey key = new ECKey();
    group.importKeys(key);
    final KeyCrypterScrypt crypter = new KeyCrypterScrypt();
    final KeyParameter aesKey = crypter.deriveKey("abc");
    assertTrue(group.isDeterministicUpgradeRequired());
    group.encrypt(crypter, aesKey);
    assertTrue(group.isDeterministicUpgradeRequired());
    try {
        group.upgradeToDeterministic(0, null);
        fail();
    } catch (DeterministicUpgradeRequiresPassword e) {
        // Expected.
    }
    group.upgradeToDeterministic(0, aesKey);
    assertFalse(group.isDeterministicUpgradeRequired());
    final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed();
    assertNotNull(deterministicSeed);
    assertTrue(deterministicSeed.isEncrypted());
    byte[] entropy = checkNotNull(group.getActiveKeyChain().toDecrypted(aesKey).getSeed()).getEntropyBytes();
    // Check we used the right key: oldest non rotating.
    byte[] truncatedBytes = Arrays.copyOfRange(key.getSecretBytes(), 0, 16);
    assertArrayEquals(entropy, truncatedBytes);
}
 
Example 4
Source File: KeyChainGroupTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deterministicUpgradeRotating() throws Exception {
    group = new KeyChainGroup(PARAMS);
    group.setLookaheadSize(LOOKAHEAD_SIZE);   // Don't want slow tests.
    long now = Utils.currentTimeSeconds();
    ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key2 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key3 = new ECKey();
    group.importKeys(key2, key1, key3);
    group.upgradeToDeterministic(now + 10, null);
    DeterministicSeed seed = group.getActiveKeyChain().getSeed();
    assertNotNull(seed);
    // Check we used the right key: oldest non rotating.
    byte[] truncatedBytes = Arrays.copyOfRange(key2.getSecretBytes(), 0, 16);
    assertArrayEquals(seed.getEntropyBytes(), truncatedBytes);
}
 
Example 5
Source File: KeyChainGroupTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deterministicUpgradeEncrypted() throws Exception {
    group = new KeyChainGroup(PARAMS);
    final ECKey key = new ECKey();
    group.importKeys(key);
    final KeyCrypterScrypt crypter = new KeyCrypterScrypt();
    final KeyParameter aesKey = crypter.deriveKey("abc");
    assertTrue(group.isDeterministicUpgradeRequired());
    group.encrypt(crypter, aesKey);
    assertTrue(group.isDeterministicUpgradeRequired());
    try {
        group.upgradeToDeterministic(0, null);
        fail();
    } catch (DeterministicUpgradeRequiresPassword e) {
        // Expected.
    }
    group.upgradeToDeterministic(0, aesKey);
    assertFalse(group.isDeterministicUpgradeRequired());
    final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed();
    assertNotNull(deterministicSeed);
    assertTrue(deterministicSeed.isEncrypted());
    byte[] entropy = checkNotNull(group.getActiveKeyChain().toDecrypted(aesKey).getSeed()).getEntropyBytes();
    // Check we used the right key: oldest non rotating.
    byte[] truncatedBytes = Arrays.copyOfRange(key.getSecretBytes(), 0, 16);
    assertArrayEquals(entropy, truncatedBytes);
}
 
Example 6
Source File: KeyChainGroupTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void deterministicUpgradeUnencrypted() throws Exception {
    // Check that a group that contains only random keys has its HD chain created using the private key bytes of
    // the oldest random key, so upgrading the same wallet twice gives the same outcome.
    group = new KeyChainGroup(PARAMS);
    group.setLookaheadSize(LOOKAHEAD_SIZE);   // Don't want slow tests.
    ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key2 = new ECKey();
    group.importKeys(key2, key1);

    List<Protos.Key> protobufs = group.serializeToProtobuf();
    group.upgradeToDeterministic(0, null);
    assertFalse(group.isDeterministicUpgradeRequired());
    DeterministicKey dkey1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicSeed seed1 = group.getActiveKeyChain().getSeed();
    assertNotNull(seed1);

    group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protobufs);
    group.upgradeToDeterministic(0, null);  // Should give same result as last time.
    DeterministicKey dkey2 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicSeed seed2 = group.getActiveKeyChain().getSeed();
    assertEquals(seed1, seed2);
    assertEquals(dkey1, dkey2);

    // Check we used the right (oldest) key despite backwards import order.
    byte[] truncatedBytes = Arrays.copyOfRange(key1.getSecretBytes(), 0, 16);
    assertArrayEquals(seed1.getEntropyBytes(), truncatedBytes);
}
 
Example 7
Source File: KeyChainGroupTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void deterministicUpgradeUnencrypted() throws Exception {
    // Check that a group that contains only random keys has its HD chain created using the private key bytes of
    // the oldest random key, so upgrading the same wallet twice gives the same outcome.
    group = new KeyChainGroup(PARAMS);
    group.setLookaheadSize(LOOKAHEAD_SIZE);   // Don't want slow tests.
    ECKey key1 = new ECKey();
    Utils.rollMockClock(86400);
    ECKey key2 = new ECKey();
    group.importKeys(key2, key1);

    List<Protos.Key> protobufs = group.serializeToProtobuf();
    group.upgradeToDeterministic(0, null);
    assertFalse(group.isDeterministicUpgradeRequired());
    DeterministicKey dkey1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicSeed seed1 = group.getActiveKeyChain().getSeed();
    assertNotNull(seed1);

    group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protobufs);
    group.upgradeToDeterministic(0, null);  // Should give same result as last time.
    DeterministicKey dkey2 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicSeed seed2 = group.getActiveKeyChain().getSeed();
    assertEquals(seed1, seed2);
    assertEquals(dkey1, dkey2);

    // Check we used the right (oldest) key despite backwards import order.
    byte[] truncatedBytes = Arrays.copyOfRange(key1.getSecretBytes(), 0, 16);
    assertArrayEquals(seed1.getEntropyBytes(), truncatedBytes);
}
 
Example 8
Source File: DataWord.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public byte[] getLast20Bytes() {
    return Arrays.copyOfRange(data, 12, data.length);
}
 
Example 9
Source File: DataWord.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public byte[] getLast20Bytes() {
  return Arrays.copyOfRange(data, 12, data.length);
}
 
Example 10
Source File: DataWord.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 4 votes vote down vote up
public byte[] getLast20Bytes() {
    return Arrays.copyOfRange(data, 12, data.length);
}
 
Example 11
Source File: ExtendedKey.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 4 votes vote down vote up
public static ExtendedKey parse(String serialized) throws ValidationException {
    byte[] data = Base58Check.base58ToBytes(serialized);
    if (data.length != 78) {
        throw new ValidationException("invalid extended key");
    }
    byte[] type = Arrays.copyOf(data, 4);
    boolean hasPrivate;
    if (Arrays.areEqual(type, xprv) || Arrays.areEqual(type, tprv)) {
        hasPrivate = true;
    } else if (Arrays.areEqual(type, xpub) || Arrays.areEqual(type, tpub)) {
        hasPrivate = false;
    } else {
        throw new ValidationException("invalid magic number for an extended key");
    }

    int depth = data[4] & 0xff;

    int parent = data[5] & 0xff;
    parent <<= 8;
    parent |= data[6] & 0xff;
    parent <<= 8;
    parent |= data[7] & 0xff;
    parent <<= 8;
    parent |= data[8] & 0xff;

    int sequence = data[9] & 0xff;
    sequence <<= 8;
    sequence |= data[10] & 0xff;
    sequence <<= 8;
    sequence |= data[11] & 0xff;
    sequence <<= 8;
    sequence |= data[12] & 0xff;

    byte[] chainCode = Arrays.copyOfRange(data, 13, 13 + 32);
    byte[] pubOrPriv = Arrays.copyOfRange(data, 13 + 32, data.length);
    Key key;
    if (hasPrivate) {
        key = new ECKeyPair(new BigInteger(1, pubOrPriv), true);
    } else {
        key = new ECPublicKey(pubOrPriv, true);
    }
    return new ExtendedKey(key, chainCode, depth, parent, sequence);
}
 
Example 12
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 13
Source File: CommonWallet.java    From wkcwallet-java with Apache License 2.0 4 votes vote down vote up
@Override
public String toV3(String password, int n, int p, int r) {

    // derived key
    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[64];
    random.nextBytes(salt);
    int dkLen = 32;
    byte[] derivedkey = SCrypt.generate(password.getBytes(), salt, n, r, p, dkLen);
    byte[] dk = Arrays.copyOf(derivedkey, 16);
    byte[] vk = Arrays.copyOfRange(derivedkey, 16, 32);

    // Encrypt
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CTR/NoPadding");
        SecretKey aesKey = new SecretKeySpec(dk, "AES");
        byte[] iv = new byte[16];
        random.nextBytes(iv);
        IvParameterSpec iv_spec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, aesKey, iv_spec);
        byte[] ciphertext = cipher.doFinal(getPrivateKey());

        // Calc MAC
        byte[] mac = HashUtil.sha3(Arrays.concatenate(vk, ciphertext));

        // Output
        StringBuilder sb = new StringBuilder();
        sb.append("{\"address\":\"").append(getAddressString()).append('"');
        sb.append(",\"crypto\":{\"cipher\":\"aes-128-ctr\"");
        sb.append(",\"ciphertext\":\"").append(Hex.toHexString(ciphertext)).append('"');
        sb.append(",\"cipherparams\":{");
        sb.append("\"iv\":\"").append(Hex.toHexString(iv)).append('"');
        sb.append("}");
        sb.append(",\"kdf\":\"").append("scrypt").append('"');
        sb.append(",\"kdfparams\":{");
        sb.append("\"dklen\":").append(dkLen);
        sb.append(",\"n\":").append(n);
        sb.append(",\"r\":").append(r);
        sb.append(",\"p\":").append(p);
        sb.append(",\"salt\":\"").append(Hex.toHexString(salt)).append('"');
        sb.append('}');
        sb.append(",\"mac\":\"").append(Hex.toHexString(mac)).append('"');
        sb.append('}');
        sb.append(",\"id\":\"").append(UUID.randomUUID()).append('"');
        sb.append(",\"version\":3}");
        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeCryptoException();
    }

}
 
Example 14
Source File: DataWord.java    From asf-sdk with GNU General Public License v3.0 4 votes vote down vote up
public byte[] getLast20Bytes() {
  return Arrays.copyOfRange(data, 12, data.length);
}
 
Example 15
Source File: PublicKey.java    From steem-java-api-wrapper with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Create a new public key by providing an address as String.
 * 
 * @param address
 *            The address in its String representation.
 *            <p>
 *            Example: <br>
 *            STM5jYVokmZHdEpwo5oCG3ES2Ca4VYzy6tM8pWWkGdgVnwo2mFLFq
 *            </p>
 * @throws AddressFormatException
 *             If the input is not base 58 or the checksum does not
 *             validate.
 */
@JsonCreator
public PublicKey(String address) {
    // As this method is also used for parsing different operations where
    // the field could be empty we sadly have to handle "null" cases here.
    if (address != null && !"".equals(address)) {
        if (address.length() != 53) {
            LOGGER.warn("The provided address '{}' has an invalid length and will not be set.", address);
            this.setPublicKey(null);
        } else {
            // We expect the first three chars to be the prefix (STM). The
            // rest
            // of the String contains the base58 encoded public key and its
            // checksum.
            this.prefix = address.substring(0, 3);
            byte[] decodedAddress = Base58.decode(address.substring(3, address.length()));
            // As sha256 is used for Bitcoin and ripemd160 for Steem, we
            // can't
            // use Bitcoinjs Base58.decodeChecked here and have to do all
            // stuff
            // on our own.
            byte[] potentialPublicKey = Arrays.copyOfRange(decodedAddress, 0,
                    decodedAddress.length - CHECKSUM_BYTES);
            byte[] expectedChecksum = Arrays.copyOfRange(decodedAddress, decodedAddress.length - CHECKSUM_BYTES,
                    decodedAddress.length);

            byte[] actualChecksum = calculateChecksum(potentialPublicKey);

            // And compare them.
            for (int i = 0; i < expectedChecksum.length; i++) {
                if (expectedChecksum[i] != actualChecksum[i]) {
                    throw new AddressFormatException("Checksum does not match.");
                }
            }

            this.setPublicKey(ECKey.fromPublicOnly(potentialPublicKey));
        }
    } else {
        LOGGER.warn(
                "An empty address has been provided. This can cause some problems if you plan to broadcast this key.");
        this.setPublicKey(null);
    }
}
 
Example 16
Source File: DataWord.java    From ethereumj with MIT License 4 votes vote down vote up
public byte[] getLast20Bytes() {
	return Arrays.copyOfRange(data, 12, data.length);
}