Example usage for org.bouncycastle.util Arrays concatenate

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

Introduction

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

Prototype

public static byte[] concatenate(byte[] a, byte[] b, byte[] c) 

Source Link

Usage

From source file:co.rsk.mine.MinerUtils.java

License:Open Source License

public static co.rsk.bitcoinj.core.BtcTransaction getBitcoinMergedMiningCoinbaseTransaction(
        co.rsk.bitcoinj.core.NetworkParameters params, byte[] blockHashForMergedMining) {
    co.rsk.bitcoinj.core.BtcTransaction coinbaseTransaction = new co.rsk.bitcoinj.core.BtcTransaction(params);
    //Add a random number of random bytes before the RSK tag
    SecureRandom random = new SecureRandom();
    byte[] prefix = new byte[random.nextInt(1000)];
    random.nextBytes(prefix);/* www  . j a va 2 s . c o  m*/
    byte[] bytes = Arrays.concatenate(prefix, RskMiningConstants.RSK_TAG, blockHashForMergedMining);
    // Add the Tag to the scriptSig of first input
    co.rsk.bitcoinj.core.TransactionInput ti = new co.rsk.bitcoinj.core.TransactionInput(params,
            coinbaseTransaction, bytes);
    coinbaseTransaction.addInput(ti);
    ByteArrayOutputStream scriptPubKeyBytes = new ByteArrayOutputStream();
    co.rsk.bitcoinj.core.BtcECKey key = new co.rsk.bitcoinj.core.BtcECKey();
    try {
        co.rsk.bitcoinj.script.Script.writeBytes(scriptPubKeyBytes, key.getPubKey());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    scriptPubKeyBytes.write(co.rsk.bitcoinj.script.ScriptOpCodes.OP_CHECKSIG);
    coinbaseTransaction.addOutput(new co.rsk.bitcoinj.core.TransactionOutput(params, coinbaseTransaction,
            co.rsk.bitcoinj.core.Coin.valueOf(50, 0), scriptPubKeyBytes.toByteArray()));
    return coinbaseTransaction;
}

From source file:com.picdrop.helper.TestHelper.java

static public byte[] createFileContent(byte[] data, String boundary, String contentType, String fileName) {
    String start = "--" + boundary + "\r\n Content-Disposition: form-data; name=\"file\"; filename=\""
            + fileName + "\"\r\n" + "Content-type: " + contentType + "\r\n"
            + "Content-Transfer-Encoding: binary\r\n\r\n";

    String end = "\r\n--" + boundary + "--"; // correction suggested @butfly 
    return Arrays.concatenate(start.getBytes(), data, end.getBytes());
}

From source file:de.fichtelmax.asn1.ber.BERObjectTest.java

License:Open Source License

@Test
public void toStringShouldUseCompleteASN1() {
    // not really ASN1/TLV - should not be neccessary for data object
    byte[] type = new byte[] { 0x01 };
    byte[] length = new byte[] { 0x02 };
    byte[] value = new byte[] { 0x03 };

    cut = new BERObject(type, length, value);

    assertThat(cut.toString(),/*from   w ww .  ja va2  s .c om*/
            containsString(DatatypeConverter.printBase64Binary(Arrays.concatenate(type, length, value))));
}

From source file:org.jpos.ee.UserManager.java

License:Open Source License

private String genV1Hash(String password, byte[] salt) throws BLException {
    try {//from ww  w .  java  2s.c  o  m
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        int iterations = VERSION.ONE.getIterations();
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, VERSION.ONE.getKeylength());
        return org.bouncycastle.util.encoders.Base64
                .toBase64String(Arrays.concatenate(new byte[] { VERSION.ONE.getVersion() },
                        VERSION.ONE.getSalt(salt), skf.generateSecret(spec).getEncoded()));
    } catch (Exception e) {
        throw new BLException(e.getLocalizedMessage());
    }
}

From source file:org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection.java

License:Open Source License

/**
 * Call DECIPHER command/*from  www . j  a  v  a 2  s .c  o  m*/
 *
 * @param encryptedSessionKey the encoded session key
 * @param publicKey
 * @return the decoded session key
 */
public byte[] decryptSessionKey(@NonNull byte[] encryptedSessionKey, CanonicalizedPublicKey publicKey)
        throws IOException {
    final KeyFormat kf = mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT);

    if (!mPw1ValidatedForDecrypt) {
        verifyPinForOther();
    }

    byte[] data;
    byte[] dataLen;
    int pLen = 0;

    X9ECParameters x9Params;

    switch (kf.keyFormatType()) {
    case RSAKeyFormatType:
        data = Arrays.copyOfRange(encryptedSessionKey, 2, encryptedSessionKey.length);
        if (data[0] != 0) {
            data = Arrays.prepend(data, (byte) 0x00);
        }
        break;

    case ECKeyFormatType:
        pLen = ((((encryptedSessionKey[0] & 0xff) << 8) + (encryptedSessionKey[1] & 0xff)) + 7) / 8;
        data = new byte[pLen];

        System.arraycopy(encryptedSessionKey, 2, data, 0, pLen);

        final ECKeyFormat eckf = (ECKeyFormat) kf;
        x9Params = NISTNamedCurves.getByOID(eckf.getCurveOID());

        final ECPoint p = x9Params.getCurve().decodePoint(data);
        if (!p.isValid()) {
            throw new CardException("Invalid EC point!");
        }

        data = p.getEncoded(false);

        if (data.length < 128) {
            dataLen = new byte[] { (byte) data.length };
        } else {
            dataLen = new byte[] { (byte) 0x81, (byte) data.length };
        }
        data = Arrays.concatenate(Hex.decode("86"), dataLen, data);

        if (data.length < 128) {
            dataLen = new byte[] { (byte) data.length };
        } else {
            dataLen = new byte[] { (byte) 0x81, (byte) data.length };
        }
        data = Arrays.concatenate(Hex.decode("7F49"), dataLen, data);

        if (data.length < 128) {
            dataLen = new byte[] { (byte) data.length };
        } else {
            dataLen = new byte[] { (byte) 0x81, (byte) data.length };
        }
        data = Arrays.concatenate(Hex.decode("A6"), dataLen, data);
        break;

    default:
        throw new CardException("Unknown encryption key type!");
    }

    CommandApdu command = commandFactory.createDecipherCommand(data);
    ResponseApdu response = communicate(command);

    if (!response.isSuccess()) {
        throw new CardException("Deciphering with Security token failed on receive", response.getSw());
    }

    switch (mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT).keyFormatType()) {
    case RSAKeyFormatType:
        return response.getData();

    /* From 3.x OpenPGP card specification :
       In case of ECDH the card supports a partial decrypt only.
       With its own private key and the given public key the card calculates a shared secret
       in compliance with the Elliptic Curve Key Agreement Scheme from Diffie-Hellman.
       The shared secret is returned in the response, all other calculation for deciphering
       are done outside of the card.
            
       The shared secret obtained is a KEK (Key Encryption Key) that is used to wrap the
       session key.
            
       From rfc6637#section-13 :
       This document explicitly discourages the use of algorithms other than AES as a KEK algorithm.
       */
    case ECKeyFormatType:
        data = response.getData();

        final byte[] keyEnc = new byte[encryptedSessionKey[pLen + 2]];

        System.arraycopy(encryptedSessionKey, 2 + pLen + 1, keyEnc, 0, keyEnc.length);

        try {
            final MessageDigest kdf = MessageDigest
                    .getInstance(MessageDigestUtils.getDigestName(publicKey.getSecurityTokenHashAlgorithm()));

            kdf.update(new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 1 });
            kdf.update(data);
            kdf.update(publicKey.createUserKeyingMaterial(fingerprintCalculator));

            final byte[] kek = kdf.digest();
            final Cipher c = Cipher.getInstance("AESWrap");

            c.init(Cipher.UNWRAP_MODE,
                    new SecretKeySpec(kek, 0, publicKey.getSecurityTokenSymmetricKeySize() / 8, "AES"));

            final Key paddedSessionKey = c.unwrap(keyEnc, "Session", Cipher.SECRET_KEY);

            Arrays.fill(kek, (byte) 0);

            return PGPPad.unpadSessionData(paddedSessionKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            throw new CardException("Unknown digest/encryption algorithm!");
        } catch (NoSuchPaddingException e) {
            throw new CardException("Unknown padding algorithm!");
        } catch (PGPException e) {
            throw new CardException(e.getMessage());
        } catch (InvalidKeyException e) {
            throw new CardException("Invalid KEK!");
        }

    default:
        throw new CardException("Unknown encryption key type!");
    }
}

From source file:org.sufficientlysecure.keychain.securitytoken.usb.tpdu.Block.java

License:Open Source License

protected Block(BlockChecksumType checksumType, byte nad, byte pcb, byte[] apdu) throws UsbTransportException {
    this.mChecksumType = checksumType;
    if (apdu.length > MAX_PAYLOAD_LEN) {
        throw new UsbTransportException("APDU is too long; should be split");
    }/*from  www .  j a va  2  s .  c  o  m*/
    this.mData = Arrays.concatenate(new byte[] { nad, pcb, (byte) apdu.length }, apdu,
            new byte[mChecksumType.getLength()]);

    int checksumOffset = this.mData.length - mChecksumType.getLength();
    byte[] checksum = mChecksumType.computeChecksum(this.mData, 0, checksumOffset);

    System.arraycopy(checksum, 0, this.mData, checksumOffset, mChecksumType.getLength());
}