Example usage for org.bouncycastle.util Arrays copyOfRange

List of usage examples for org.bouncycastle.util Arrays copyOfRange

Introduction

In this page you can find the example usage for org.bouncycastle.util Arrays copyOfRange.

Prototype

public static BigInteger[] copyOfRange(BigInteger[] original, int from, int to) 

Source Link

Usage

From source file:org.ethereum.vm.DataWord.java

License:Open Source License

public byte[] getLast20Bytes() {
    return Arrays.copyOfRange(data, 12, data.length);
}

From source file:org.gity.internal.crypto.CPCipher.java

License:Open Source License

/**
 * Decrypts a given file with ChaCha20 w/ Poly1305 as MAC in
 * encrypt-then-MAC scheme.//from   w  ww .j a va  2  s  .c om
 * <p>
 * Reads data from the InputStream and writes the decrypted data to the
 * OutputStream
 *
 * @param key
 * @param nonce
 * @param input
 * @param output
 * @throws IOException
 */
public void decrypt(byte[] key, byte[] nonce, InputStream input, OutputStream output) throws IOException {
    this.cipher.init(false, new ParametersWithIV(new KeyParameter(key), nonce));
    byte[] computedMac = new byte[16], receivedMac = new byte[16], readBuf = new byte[BUFFER_SIZE],
            chachaBuf = new byte[BUFFER_SIZE];
    initMAC(cipher);

    int r = 0;
    while ((r = input.read(readBuf)) != -1) {
        // case when EOF has not been reached
        if (r == BUFFER_SIZE) {
            // use C in whole to update the MAC and decrypt
            updateMAC(readBuf, 0, r);
            cipher.processBytes(readBuf, 0, r, chachaBuf, 0);
            output.write(chachaBuf, 0, r);
        } else {
            // use all but the last 16 bytes from C to update the MAC and decrypt
            updateMAC(Arrays.copyOfRange(readBuf, 0, r - 16), 0, r - 16);
            cipher.processBytes(Arrays.copyOfRange(readBuf, 0, r - 16), 0, r - 16, chachaBuf, 0);
            output.write(chachaBuf, 0, r - 16);

            // copy the last 16 bytes as the original MAC
            receivedMac = Arrays.copyOfRange(readBuf, r - 16, r);
        }
    }

    // check if the two MACs match
    mac.doFinal(computedMac, 0);
    if (!Arrays.constantTimeAreEqual(computedMac, receivedMac)) {
        throw new TlsFatalAlert(AlertDescription.bad_record_mac);
    }
}

From source file:org.hyperledger.account.ShamirsSecretShares.java

License:Apache License

/**
 * Reconstruct a secret from a collection of shares. Provided they are suffcient.
 *
 * @param shares an array of secret shares
 * @return secret if successfully recreated. The algorithm can not check for success if the shares ver not created with verbose serialization.
 * @throws HyperLedgerException/*w w w  . ja  v a  2 s  . c om*/
 */
public static PrivateKey reconstruct(String[] shares) throws HyperLedgerException {
    SecretShare ss[] = new SecretShare[shares.length];

    boolean comp = true;
    for (int i = 0; i < shares.length; ++i) {
        byte[] raw = ByteUtils.fromBase58WithChecksum(shares[i]);
        byte[] prefix = Arrays.copyOfRange(raw, 0, 2);
        boolean verbose = Arrays.areEqual(prefix, compressed) || !Arrays.areEqual(prefix, legacy);
        if (!verbose && !Arrays.areEqual(prefix, compressedShort) && !Arrays.areEqual(prefix, legacyShort)) {
            throw new HyperLedgerException("Not a key share");
        }
        ss[i] = new SecretShare();
        ss[i].shareNumber = raw[2] & 0xff;
        ss[i].share = new BigInteger(1, Arrays.copyOfRange(raw, verbose ? 6 : 3, 40));
        comp = raw[1] == compressed[1];
    }
    return new PrivateKey(ss256.reconstruct(ss), comp);
}

From source file:org.hyperledger.common.MasterPrivateKey.java

License:Apache License

/**
 * Create a MasterPrivateKey from a plain text seed. The seed is stretched/resized to 64 bytes with HmacSHA512
 *
 * @param seed arbitrary data/*from   w ww.  j  av  a  2s .  c  o  m*/
 * @return (re-)created MasterPrivateKey
 * @throws HyperLedgerException for any error in called crypto libraries
 */
public static MasterPrivateKey create(byte[] seed) throws HyperLedgerException {
    try {
        Mac mac = Mac.getInstance("HmacSHA512", "BC");
        SecretKey seedkey = new SecretKeySpec(BITCOIN_SEED, "HmacSHA512");
        mac.init(seedkey);
        byte[] lr = mac.doFinal(seed);
        byte[] l = Arrays.copyOfRange(lr, 0, 32);
        byte[] r = Arrays.copyOfRange(lr, 32, 64);
        BigInteger m = new BigInteger(1, l);
        if (m.compareTo(curve.getN()) >= 0 || m.compareTo(BigInteger.ZERO) == 0) {
            throw new HyperLedgerException("This is rather unlikely, but it did just happen");
        }
        PrivateKey keyPair = new PrivateKey(m, true);
        return new MasterPrivateKey(keyPair, r, 0, 0, 0);
    } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException e) {
        throw new HyperLedgerException(e);
    }
}

From source file:org.hyperledger.common.MasterPrivateKey.java

License:Apache License

/**
 * Re-create a MasterPrivateKey from encrypted serialization
 *
 * @param passphrase passphrase/*  ww  w . j  av  a 2  s.  c o m*/
 * @param encrypted  cipher text from encrypt
 * @return
 * @throws HyperLedgerException error in used libraries or wrong format
 */
public static MasterPrivateKey decrypt(String passphrase, byte[] encrypted) throws HyperLedgerException {
    try {
        byte[] key = SCrypt.generate(passphrase.getBytes("UTF-8"), BITCOIN_SEED, 16384, 8, 8, 32);
        SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
        byte[] data = Arrays.copyOfRange(encrypted, 16, encrypted.length);
        cipher.init(Cipher.DECRYPT_MODE, keyspec, new IvParameterSpec(iv));
        return MasterPrivateKey.parse(new String(cipher.doFinal(data)));
    } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException | NoSuchPaddingException
            | NoSuchProviderException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException
            | IllegalBlockSizeException e) {
        throw new HyperLedgerException(e);
    }
}

From source file:org.hyperledger.common.MasterPrivateKey.java

License:Apache License

private MasterPrivateKey generateKey(int sequence) throws HyperLedgerException {
    try {/*from w  w  w.java 2 s .c om*/
        Mac mac = Mac.getInstance("HmacSHA512", "BC");
        SecretKey key = new SecretKeySpec(chainCode, "HmacSHA512");
        mac.init(key);

        byte[] extended;
        byte[] pub = master.getPublic().toByteArray();
        if ((sequence & 0x80000000) == 0) {
            extended = new byte[pub.length + 4];
            System.arraycopy(pub, 0, extended, 0, pub.length);
            extended[pub.length] = (byte) ((sequence >>> 24) & 0xff);
            extended[pub.length + 1] = (byte) ((sequence >>> 16) & 0xff);
            extended[pub.length + 2] = (byte) ((sequence >>> 8) & 0xff);
            extended[pub.length + 3] = (byte) (sequence & 0xff);
        } else {
            byte[] priv = master.toByteArray();
            extended = new byte[priv.length + 5];
            System.arraycopy(priv, 0, extended, 1, priv.length);
            extended[priv.length + 1] = (byte) ((sequence >>> 24) & 0xff);
            extended[priv.length + 2] = (byte) ((sequence >>> 16) & 0xff);
            extended[priv.length + 3] = (byte) ((sequence >>> 8) & 0xff);
            extended[priv.length + 4] = (byte) (sequence & 0xff);
        }
        byte[] lr = mac.doFinal(extended);
        byte[] l = Arrays.copyOfRange(lr, 0, 32);
        byte[] r = Arrays.copyOfRange(lr, 32, 64);

        BigInteger m = new BigInteger(1, l);
        if (m.compareTo(curve.getN()) >= 0 || m.compareTo(BigInteger.ZERO) == 0) {
            throw new HyperLedgerException("This is rather unlikely, but it did just happen");
        }
        BigInteger k = m.add(new BigInteger(1, master.toByteArray())).mod(curve.getN());
        if (k.compareTo(BigInteger.ZERO) == 0) {
            throw new HyperLedgerException("This is rather unlikely, but it did just happen");
        }
        return new MasterPrivateKey(new PrivateKey(k, true), r, depth, parent, sequence);
    } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException e) {
        throw new HyperLedgerException(e);
    }
}

From source file:org.hyperledger.common.MasterPrivateKey.java

License:Apache License

/**
 * Recreate a key from BIP32 serialization
 *
 * @param serialized/*  www  .  j a v a  2 s . c o m*/
 * @return MasterPrivateKey
 * @throws HyperLedgerException
 */
public static MasterPrivateKey parse(String serialized) throws HyperLedgerException {
    byte[] data = ByteUtils.fromBase58WithChecksum(serialized);
    if (data.length != 78) {
        throw new HyperLedgerException("invalid master key");
    }
    byte[] type = Arrays.copyOf(data, 4);
    if (!Arrays.areEqual(type, xprv) && !Arrays.areEqual(type, tprv)) {
        throw new HyperLedgerException("invalid magic number for a master private 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);
    return new MasterPrivateKey(new PrivateKey(new BigInteger(1, pubOrPriv), true), chainCode, depth, parent,
            sequence);
}

From source file:org.hyperledger.common.MasterPublicKey.java

License:Apache License

/**
 * Re-create a MasterPublicKey from encrypted serialization.
 *
 * @param passphrase - passphrase//from w ww.j a va  2  s  . c o m
 * @param encrypted  - the cipher text returned by encrypt
 * @return
 * @throws HyperLedgerException error in used libraries or wrong format
 */
public static MasterPublicKey decrypt(String passphrase, byte[] encrypted) throws HyperLedgerException {
    try {
        byte[] key = SCrypt.generate(passphrase.getBytes("UTF-8"), BITCOIN_SEED, 16384, 8, 8, 32);
        SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
        byte[] data = Arrays.copyOfRange(encrypted, 16, encrypted.length);
        cipher.init(Cipher.DECRYPT_MODE, keyspec, new IvParameterSpec(iv));
        return MasterPublicKey.parse(new String(cipher.doFinal(data)));
    } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException | NoSuchPaddingException
            | NoSuchProviderException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException
            | IllegalBlockSizeException e) {
        throw new HyperLedgerException(e);
    }
}

From source file:org.hyperledger.common.MasterPublicKey.java

License:Apache License

private MasterPublicKey generateKey(int sequence) throws HyperLedgerException {
    try {/*from   w w  w  .ja va 2 s . com*/
        if ((sequence & 0x80000000) != 0) {
            throw new HyperLedgerException("need private key for hardened generation");
        }
        Mac mac = Mac.getInstance("HmacSHA512", "BC");
        SecretKey key = new SecretKeySpec(chainCode, "HmacSHA512");
        mac.init(key);

        byte[] extended;
        byte[] pub = master.toByteArray();
        extended = new byte[pub.length + 4];
        System.arraycopy(pub, 0, extended, 0, pub.length);
        extended[pub.length] = (byte) ((sequence >>> 24) & 0xff);
        extended[pub.length + 1] = (byte) ((sequence >>> 16) & 0xff);
        extended[pub.length + 2] = (byte) ((sequence >>> 8) & 0xff);
        extended[pub.length + 3] = (byte) (sequence & 0xff);
        byte[] lr = mac.doFinal(extended);
        byte[] l = Arrays.copyOfRange(lr, 0, 32);
        byte[] r = Arrays.copyOfRange(lr, 32, 64);

        BigInteger m = new BigInteger(1, l);
        if (m.compareTo(curve.getN()) >= 0 || m.compareTo(BigInteger.ZERO) == 0) {
            throw new HyperLedgerException("This is rather unlikely, but it did just happen");
        }
        ECPoint q = curve.getG().multiply(m).add(curve.getCurve().decodePoint(pub));
        if (q.isInfinity()) {
            throw new HyperLedgerException("This is rather unlikely, but it did just happen");
        }
        pub = q.getEncoded(true);
        return new MasterPublicKey(new PublicKey(pub, true), r, depth, parent, sequence);
    } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException e) {
        throw new HyperLedgerException(e);
    }
}

From source file:org.hyperledger.common.MasterPublicKey.java

License:Apache License

/**
 * Parse a MasterPublickey from its BIP32 compliant serialization.
 *
 * @param serialized a Base58 string//from  w  w  w  .ja  v  a  2s.  c om
 * @return a master key
 * @throws HyperLedgerException for invalid format
 */
public static MasterPublicKey parse(String serialized) throws HyperLedgerException {
    byte[] data = ByteUtils.fromBase58WithChecksum(serialized);
    if (data.length != 78) {
        throw new HyperLedgerException("invalid extended key");
    }
    byte[] type = Arrays.copyOf(data, 4);
    if (!Arrays.areEqual(type, xpub) && !Arrays.areEqual(type, tpub)) {
        throw new HyperLedgerException("invalid magic number for an master public 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);
    return new MasterPublicKey(new PublicKey(pubOrPriv, true), chainCode, depth, parent, sequence);
}