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:com.amazonawsencryptionsdk.CryptoInputStreamTest.java

License:Open Source License

@Test
public void decryptAPIComptability() throws IOException {
    final int ptSize = 1000000; // 1MB
    final byte[] plaintextBytes = TestIOUtils.generateRandomPlaintext(ptSize);

    final String inputFileName = sandboxPath_ + "plaintext_1MB.txt";
    final String encryptedFileName = new String(inputFileName + ".enc");

    OutputStream outStream = new FileOutputStream(inputFileName);
    outStream.write(plaintextBytes);//from w w w. j  av a 2 s.  co m
    outStream.close();

    Map<String, String> encryptionContext = new HashMap<String, String>(1);
    encryptionContext.put("ENC", "Test with %s" + inputFileName);

    encryptionClient_.setEncryptionFrameSize(AwsCrypto.getDefaultFrameSize());

    // encryption
    InputStream inStream = new FileInputStream(inputFileName);
    final InputStream encryptionInStream = encryptionClient_.createEncryptingStream(customerMasterKey, inStream,
            encryptionContext);
    outStream = new FileOutputStream(encryptedFileName);

    TestIOUtils.copyInStreamToOutStream(encryptionInStream, outStream);
    encryptionInStream.close();
    outStream.close();

    // decryption
    inStream = new FileInputStream(encryptedFileName);
    final int encryptedBytesLen = (int) encryptionClient_.estimateCiphertextSize(customerMasterKey, ptSize,
            encryptionContext);
    final byte[] encryptedBytes = new byte[encryptedBytesLen];

    int readLen = 0;
    int totalReadBytes = 0;
    while (readLen >= 0) {
        totalReadBytes += readLen;
        try {
            readLen = inStream.read(encryptedBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    inStream.close();

    final byte[] outBytes = Arrays.copyOfRange(encryptedBytes, 0, totalReadBytes);
    final CryptoResult<byte[], JceMasterKey> decryptedText = encryptionClient_.decryptData(customerMasterKey,
            outBytes);

    assertArrayEquals(plaintextBytes, decryptedText.getResult());
}

From source file:com.bitsofproof.supernode.api.ExtendedKey.java

License:Apache License

public static ExtendedKey create(byte[] seed) throws ValidationException {
    try {/*from  ww  w  .ja  va2  s. co  m*/
        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) {
            throw new ValidationException("This is rather unlikely, but it did just happen");
        }
        ECKeyPair keyPair = new ECKeyPair(l, true);
        return new ExtendedKey(keyPair, r, 0, 0, 0);
    } catch (NoSuchAlgorithmException e) {
        throw new ValidationException(e);
    } catch (NoSuchProviderException e) {
        throw new ValidationException(e);
    } catch (InvalidKeyException e) {
        throw new ValidationException(e);
    }
}

From source file:com.bitsofproof.supernode.api.ExtendedKey.java

License:Apache License

private ExtendedKey generateKey(int sequence) throws ValidationException {
    try {/* www . j  a  va 2 s .c  o m*/
        if ((sequence & 0x80000000) != 0 && master.getPrivate() == null) {
            throw new ValidationException("need private key for private generation");
        }
        Mac mac = Mac.getInstance("HmacSHA512", "BC");
        SecretKey key = new SecretKeySpec(chainCode, "HmacSHA512");
        mac.init(key);

        byte[] extended;
        byte[] pub = master.getPublic();
        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.getPrivate();
            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) {
            throw new ValidationException("This is rather unlikely, but it did just happen");
        }
        if (master.getPrivate() != null) {
            BigInteger k = m.add(new BigInteger(1, master.getPrivate())).mod(curve.getN());
            if (k.equals(BigInteger.ZERO)) {
                throw new ValidationException("This is rather unlikely, but it did just happen");
            }
            return new ExtendedKey(new ECKeyPair(k, true), r, depth, parent, sequence);
        } else {
            ECPoint q = curve.getG().multiply(m).add(curve.getCurve().decodePoint(pub));
            if (q.isInfinity()) {
                throw new ValidationException("This is rather unlikely, but it did just happen");
            }
            pub = new ECPoint.Fp(curve.getCurve(), q.getX(), q.getY(), true).getEncoded();
            return new ExtendedKey(new ECPublicKey(pub, true), r, depth, parent, sequence);
        }
    } catch (NoSuchAlgorithmException e) {
        throw new ValidationException(e);
    } catch (NoSuchProviderException e) {
        throw new ValidationException(e);
    } catch (InvalidKeyException e) {
        throw new ValidationException(e);
    }
}

From source file:com.bitsofproof.supernode.api.ExtendedKey.java

License:Apache License

public static ExtendedKey parse(String serialized) throws ValidationException {
    byte[] data = ByteUtils.fromBase58WithChecksum(serialized);
    if (data.length != 78) {
        throw new ValidationException("invalid extended key");
    }//from   www .j  a v  a  2s . co  m
    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);
}

From source file:com.bitsofproof.supernode.common.ExtendedKey.java

License:Apache License

public static ExtendedKey createFromPassphrase(String passphrase, byte[] encrypted) throws ValidationException {
    try {//from   ww  w  .  j  a  v a  2  s  .c  o m
        byte[] key = SCrypt.generate(passphrase.getBytes("UTF-8"), BITCOIN_SEED, 16384, 8, 8, 32);
        SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
        if (encrypted.length == 32) {
            // asssume encrypted is seed
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, keyspec);
            return create(cipher.doFinal(encrypted));
        } else {
            // assume encrypted serialization of a key
            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 ExtendedKey.parse(new String(cipher.doFinal(data)));
        }
    } catch (UnsupportedEncodingException e) {
        throw new ValidationException(e);
    } catch (IllegalBlockSizeException e) {
        throw new ValidationException(e);
    } catch (BadPaddingException e) {
        throw new ValidationException(e);
    } catch (InvalidKeyException e) {
        throw new ValidationException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new ValidationException(e);
    } catch (NoSuchProviderException e) {
        throw new ValidationException(e);
    } catch (NoSuchPaddingException e) {
        throw new ValidationException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new ValidationException(e);
    }
}

From source file:com.bitsofproof.supernode.common.ExtendedKey.java

License:Apache License

public static ExtendedKey create(byte[] seed) throws ValidationException {
    try {/*from   w  w  w  .  j a va 2 s . co  m*/
        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 ValidationException("This is rather unlikely, but it did just happen");
        }
        ECKeyPair keyPair = new ECKeyPair(m, true);
        return new ExtendedKey(keyPair, r, 0, 0, 0);
    } catch (NoSuchAlgorithmException e) {
        throw new ValidationException(e);
    } catch (NoSuchProviderException e) {
        throw new ValidationException(e);
    } catch (InvalidKeyException e) {
        throw new ValidationException(e);
    }
}

From source file:com.bitsofproof.supernode.common.ExtendedKey.java

License:Apache License

private ExtendedKey generateKey(int sequence) throws ValidationException {
    try {//from   w  w  w  . j a  v  a  2s  . c o  m
        if ((sequence & 0x80000000) != 0 && master.getPrivate() == null) {
            throw new ValidationException("need private key for private generation");
        }
        Mac mac = Mac.getInstance("HmacSHA512", "BC");
        SecretKey key = new SecretKeySpec(chainCode, "HmacSHA512");
        mac.init(key);

        byte[] extended;
        byte[] pub = master.getPublic();
        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.getPrivate();
            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 ValidationException("This is rather unlikely, but it did just happen");
        }
        if (master.getPrivate() != null) {
            BigInteger k = m.add(new BigInteger(1, master.getPrivate())).mod(curve.getN());
            if (k.compareTo(BigInteger.ZERO) == 0) {
                throw new ValidationException("This is rather unlikely, but it did just happen");
            }
            return new ExtendedKey(new ECKeyPair(k, true), r, depth, parent, sequence);
        } else {
            ECPoint q = curve.getG().multiply(m).add(curve.getCurve().decodePoint(pub));
            if (q.isInfinity()) {
                throw new ValidationException("This is rather unlikely, but it did just happen");
            }
            pub = q.getEncoded(true);
            return new ExtendedKey(new ECPublicKey(pub, true), r, depth, parent, sequence);
        }
    } catch (NoSuchAlgorithmException e) {
        throw new ValidationException(e);
    } catch (NoSuchProviderException e) {
        throw new ValidationException(e);
    } catch (InvalidKeyException e) {
        throw new ValidationException(e);
    }
}

From source file:com.bitsofproof.supernode.wallet.ShamirsSecretSharing.java

License:Apache License

public static byte[] reconstructFromMnemonicShares(List<String> shareList, String passphrase)
        throws ValidationException {
    SecretShare[] shares = new SecretShare[shareList.size()];
    int i = 0;//  w  w  w  .  j  a  v  a2s . co m
    for (String m : shareList) {
        byte[] e = BIP39.decode(m, passphrase);
        shares[i] = new SecretShare();
        shares[i].x = e[0];
        shares[i].dl = e[1];
        shares[i].yl = e[2];
        shares[i].y = Arrays.copyOfRange(e, 3, shares[i].yl + 3);
        ++i;
    }
    return reconstruct(shares);
}

From source file:com.bitsofproof.supernode.wallet.ShamirsSecretSharing.java

License:Apache License

public static byte[] reconstruct(SecretShare[] shares) throws ValidationException {
    for (int i = 0; i < shares.length - 1; ++i) {
        for (int j = 0; j < shares.length; ++j) {
            if (i != j && shares[i].x == shares[j].x) {
                throw new ValidationException("Shares are not unique");
            }//from   w ww .  java 2 s  .co m
        }
    }
    BigInteger[] y = new BigInteger[shares.length];
    for (int i = 0; i < shares.length; ++i) {
        y[i] = new BigInteger(shares[i].y);
    }
    int d, i;
    for (d = 1; d < shares.length; d++) {
        for (i = 0; i < shares.length - d; i++) {
            int j = i + d;
            BigInteger num = BigInteger.valueOf(shares[j].x).multiply(y[i])
                    .subtract(BigInteger.valueOf(shares[i].x).multiply(y[i + 1]));
            BigInteger den = BigInteger.valueOf(shares[j].x).subtract(BigInteger.valueOf(shares[i].x));
            y[i] = num.divide(den);
        }
    }
    byte[] result = y[0].toByteArray();
    if (result.length > shares[0].dl) {
        result = Arrays.copyOfRange(result, result.length - shares[0].dl, result.length);
    }
    if (result.length < shares[0].dl) {
        byte[] tmp = new byte[shares[0].dl];
        System.arraycopy(result, 0, tmp, shares[0].dl - result.length, result.length);
        result = tmp;
    }
    return result;
}

From source file:com.github.horrorho.inflatabledonkey.chunk.engine.ChunkEncryptionKeys.java

License:Open Source License

static Optional<byte[]> unwrapType2(Optional<byte[]> kek, byte[] keyData) {
    if (!kek.isPresent()) {
        logger.warn("-- unwrapType2() - kek required, but not present");
        return Optional.empty();
    }//www .  j av  a2s .  c  o m

    if (keyData.length < 0x19) {
        logger.warn("-- unwrapType2() - key data too short: 0x{}", Hex.toHexString(keyData));
    }

    byte[] wrappedKey = Arrays.copyOfRange(keyData, 0x01, 0x19);
    logger.debug("-- key() - wrapped key: 0x{} kek: 0x{}", Hex.toHexString(wrappedKey),
            kek.map(Hex::toHexString).orElse("NULL"));

    Optional<byte[]> unwrappedKey = RFC3394Wrap.unwrapAES(kek.get(), wrappedKey);
    logger.debug("-- key() - unwrapped key: 0x{}", unwrappedKey.map(Hex::toHexString).orElse("NULL"));

    return unwrappedKey;
}