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 int[] concatenate(int[] a, int[] b) 

Source Link

Usage

From source file:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java

License:Open Source License

public static String getEncryptedKey(final String certArn, final String certPem) throws AuthException {
    final ServerCertificate targetCert = lookupServerCertificate(certArn);
    // generate symmetric key
    final MessageDigest digest = Digest.SHA256.get();
    final byte[] salt = new byte[32];
    Crypto.getSecureRandomSupplier().get().nextBytes(salt);
    digest.update(salt);/* w  w  w  .  j a v a 2  s.com*/
    final SecretKey symmKey = new SecretKeySpec(digest.digest(), "AES");

    try {
        // encrypt the server pk using symm key
        Cipher cipher = Ciphers.AES_CBC.get();
        final byte[] iv = new byte[16];
        Crypto.getSecureRandomSupplier().get().nextBytes(iv);
        cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv));
        final byte[] cipherText = cipher.doFinal(Base64.encode(targetCert.getPrivateKey().getBytes()));
        final String encPrivKey = new String(Base64.encode(Arrays.concatenate(iv, cipherText)));

        // encrypt the symmetric key using the certPem
        X509Certificate x509Cert = PEMFiles.getCert(B64.standard.dec(certPem));
        cipher = Ciphers.RSA_PKCS1.get();
        cipher.init(Cipher.ENCRYPT_MODE, x509Cert.getPublicKey());
        byte[] symmkey = cipher.doFinal(symmKey.getEncoded());
        final String b64SymKey = new String(Base64.encode(symmkey));

        return String.format("%s\n%s", b64SymKey, encPrivKey);
    } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
    }
}

From source file:com.eucalyptus.auth.euare.persist.DatabaseAccountProxy.java

License:Open Source License

@Override
public ServerCertificate addServerCertificate(String certName, String certBody, String certChain,
        String certPath, String pk) throws AuthException {
    synchronized (getLock()) {
        if (!ServerCertificateEntity.isCertificateNameValid(certName))
            throw new AuthException(AuthException.INVALID_SERVER_CERT_NAME);
        if (!ServerCertificateEntity.isCertificatePathValid(certPath))
            throw new AuthException(AuthException.INVALID_SERVER_CERT_PATH);

        try {/*from w  w  w .ja v  a  2 s  .  c o  m*/
            ServerCertificates.verifyCertificate(certBody, pk, certChain);
        } catch (final AuthException ex) {
            throw ex;
        } catch (final Exception ex) {
            throw new AuthException(AuthException.SERVER_CERT_INVALID_FORMAT);
        }

        String encPk = null;
        String sessionKey = null;
        try {
            // generate symmetric key
            final MessageDigest digest = Digest.SHA256.get();
            final byte[] salt = new byte[32];
            Crypto.getSecureRandomSupplier().get().nextBytes(salt);
            //digest.update( this.lookupAdmin().getPassword().getBytes( Charsets.UTF_8 ) );
            digest.update(salt);
            final SecretKey symmKey = new SecretKeySpec(digest.digest(), "AES");

            // encrypt the server pk
            Cipher cipher = Ciphers.AES_GCM.get();
            final byte[] iv = new byte[32];
            Crypto.getSecureRandomSupplier().get().nextBytes(iv);
            cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv),
                    Crypto.getSecureRandomSupplier().get());
            final byte[] cipherText = cipher.doFinal(pk.getBytes());
            encPk = new String(Base64.encode(Arrays.concatenate(iv, cipherText)));

            final PublicKey euarePublicKey = SystemCredentials.lookup(Euare.class).getCertificate()
                    .getPublicKey();
            cipher = Ciphers.RSA_PKCS1.get();
            cipher.init(Cipher.WRAP_MODE, euarePublicKey, Crypto.getSecureRandomSupplier().get());
            byte[] wrappedKeyBytes = cipher.wrap(symmKey);
            sessionKey = new String(Base64.encode(wrappedKeyBytes));
        } catch (final Exception e) {
            LOG.error("Failed to encrypt key", e);
            throw Exceptions.toUndeclared(e);
        }

        try {
            final ServerCertificate found = lookupServerCertificate(certName);
            if (found != null)
                throw new AuthException(AuthException.SERVER_CERT_ALREADY_EXISTS);
        } catch (final NoSuchElementException ex) {
            ;
        } catch (final AuthException ex) {
            if (!AuthException.SERVER_CERT_NO_SUCH_ENTITY.equals(ex.getMessage()))
                throw ex;
        } catch (final Exception ex) {
            throw ex;
        }

        final String certId = Identifiers.generateIdentifier("ASC");
        ServerCertificateEntity entity = null;
        try (final TransactionResource db = Entities.transactionFor(ServerCertificateEntity.class)) {
            final UserFullName accountAdmin = UserFullName.getInstance(this.lookupAdmin());
            entity = new ServerCertificateEntity(accountAdmin, certName);
            entity.setCertBody(certBody);
            entity.setCertChain(certChain);
            entity.setCertPath(certPath);
            entity.setPrivateKey(encPk);
            entity.setSessionKey(sessionKey);
            entity.setCertId(certId);
            Entities.persist(entity);
            db.commit();
        } catch (final Exception ex) {
            LOG.error("Failed to persist server certificate entity", ex);
            throw Exceptions.toUndeclared(ex);
        }

        return ServerCertificates.ToServerCertificate.INSTANCE.apply(entity);
    }
}

From source file:com.eucalyptus.cloud.run.ClusterAllocator.java

License:Open Source License

private void setupCredentialMessages() {
    try {/*from  www  .  jav a  2  s  .  c o m*/
        final User owner = Accounts.lookupUserById(this.allocInfo.getOwnerFullName().getUserId());
        if (!owner.isSystemAdmin())
            return;
    } catch (final AuthException ex) {
        return;
    }
    // determine if credential setup is requested
    if (allocInfo.getUserData() == null
            || allocInfo.getUserData().length < VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString()
                    .length())
        return;
    String userData = new String(allocInfo.getUserData(), 0,
            VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString().length());
    if (!userData.startsWith(VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString()))
        return;
    userData = new String(allocInfo.getUserData());
    String payload = null;
    if (userData.length() > VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString().length()) {
        payload = userData.substring(VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString().length())
                .trim();
    }
    this.allocInfo.setUserDataAsString(payload);
    // create rsa keypair
    try {
        final KeyPair kp = Certs.generateKeyPair();
        final X509Certificate kpCert = Certs.generateCertificate(kp,
                String.format("Certificate-for-%s/%s", this.allocInfo.getOwnerFullName().getAccountName(),
                        this.allocInfo.getOwnerFullName().getUserName()));

        // call iam:signCertificate with the pub key
        final String b64PubKey = B64.standard.encString(PEMFiles.getBytes(kpCert));
        final ServiceConfiguration euare = Topology.lookup(Euare.class);
        final SignCertificateType req = new SignCertificateType();
        req.setCertificate(b64PubKey);

        final SignCertificateResponseType resp = AsyncRequests.sendSync(euare, req);
        final String token = resp.getSignCertificateResult().getSignature(); //in Base64

        // use NODECERT to encrypt the pk
        // generate symmetric key
        final MessageDigest digest = Digest.SHA256.get();
        final byte[] salt = new byte[32];
        Crypto.getSecureRandomSupplier().get().nextBytes(salt);
        digest.update(salt);
        final SecretKey symmKey = new SecretKeySpec(digest.digest(), "AES");

        // encrypt the server pk
        Cipher cipher = Ciphers.AES_GCM.get();
        final byte[] iv = new byte[12];
        Crypto.getSecureRandomSupplier().get().nextBytes(iv);
        cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv));
        final byte[] cipherText = cipher.doFinal(Base64.encode(PEMFiles.getBytes(kp.getPrivate())));
        final String encPrivKey = new String(Base64.encode(Arrays.concatenate(iv, cipherText)));

        // encrypt the token from EUARE
        cipher = Ciphers.AES_GCM.get();
        cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv));
        final byte[] byteToken = cipher.doFinal(token.getBytes());
        final String encToken = new String(Base64.encode(Arrays.concatenate(iv, byteToken)));

        // encrypt the symmetric key
        X509Certificate nodeCert = this.allocInfo.getPartition().getNodeCertificate();
        cipher = Ciphers.RSA_PKCS1.get();
        cipher.init(Cipher.ENCRYPT_MODE, nodeCert.getPublicKey());
        byte[] symmkey = cipher.doFinal(symmKey.getEncoded());
        final String encSymmKey = new String(Base64.encode(symmkey));

        X509Certificate euareCert = SystemCredentials.lookup(Euare.class).getCertificate();
        final String b64EuarePubkey = B64.standard.encString(PEMFiles.getBytes(euareCert));

        // EUARE's pubkey, VM's pubkey, token from EUARE(ENCRYPTED), SYM_KEY(ENCRYPTED), VM_KEY(ENCRYPTED)
        // each field all in B64
        final String credential = String.format("%s\n%s\n%s\n%s\n%s", b64EuarePubkey, b64PubKey, encToken, // iam token
                encSymmKey, encPrivKey);
        this.allocInfo.setCredential(credential);
    } catch (final Exception ex) {
        LOG.error("failed to setup instance credential", ex);
    }
}

From source file:com.github.flbaue.jcrypttool.v2.domain.AesEncryptionService.java

License:Apache License

@Override
public String encryptString(final String string, final String password) throws EncryptionFailedException {
    try {/* w w  w  . j a  v  a2s. c om*/
        final byte[] salt = generateSalt();
        final byte[] key = generateKey(password, salt);
        final byte[] iv = generateIV();
        final byte[] outputInitBlock = generateOutputInitBlock(salt, iv);

        final PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                new CBCBlockCipher(new AESEngine()), new PKCS7Padding());

        final KeyParameter keyParam = new KeyParameter(key);
        final CipherParameters params = new ParametersWithIV(keyParam, iv);
        cipher.init(true, params);

        final byte in[] = string.getBytes();
        final byte out[] = new byte[cipher.getOutputSize(in.length)];
        final int len1 = cipher.processBytes(in, 0, in.length, out, 0);

        cipher.doFinal(out, len1);

        final byte[] result = Arrays.concatenate(outputInitBlock, out);

        return Base64.toBase64String(result);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidCipherTextException e) {
        throw new EncryptionFailedException(e);
    }
}

From source file:com.github.flbaue.jcrypttool.v2.domain.AesEncryptionService.java

License:Apache License

private byte[] generateOutputInitBlock(byte[] salt, byte[] iv) {
    return Arrays.concatenate(salt, iv);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.xts.XTSAESBlockCipherTest.java

public XTSAESBlockCipherTest() throws IOException {
    // Key = key1 | key2
    byte[] keyData = Arrays.concatenate(VECTOR_4.key1(), VECTOR_4.key2());
    key = new KeyParameter(keyData);
    dataUnitLength = VECTOR_4.ctx().length;

    // Vectors 4, 5, 6 are sequential 512 byte data units starting from data unit sequence number 0.
    ByteArrayOutputStream ptxs = new ByteArrayOutputStream();
    ptxs.write(VECTOR_4.ptx());/*from   w ww  . j  a v a 2 s .c o m*/
    ptxs.write(VECTOR_5.ptx());
    ptxs.write(VECTOR_6.ptx());
    ptx = ptxs.toByteArray();

    ByteArrayOutputStream ctxs = new ByteArrayOutputStream();
    ctxs.write(VECTOR_4.ctx());
    ctxs.write(VECTOR_5.ctx());
    ctxs.write(VECTOR_6.ctx());
    ctx = ctxs.toByteArray();
}

From source file:com.github.horrorho.inflatabledonkey.dataprotection.DPAESXTSCipher.java

License:Open Source License

static byte[] tweakFunction(long tweakValue) {
    byte[] bs = Pack.longToLittleEndian(tweakValue);
    return Arrays.concatenate(bs, bs);
}

From source file:org.hyperledger.fabric.sdk.helper.SDKUtil.java

License:Open Source License

/**
 * Generate hash of a chain code directory
 * @param rootDir Root directory/*from  www  .  j  a  v a 2  s  .  c om*/
 * @param chaincodeDir Chain code directory
 * @param hash Previous hash (if any)
 * @return hash of the directory
 * @throws IOException
 */
public static String generateDirectoryHash(String rootDir, String chaincodeDir, String hash)
        throws IOException {
    // Generate the project directory
    Path projectPath = null;
    if (rootDir == null) {
        projectPath = Paths.get(chaincodeDir);
    } else {
        projectPath = Paths.get(rootDir, chaincodeDir);
    }

    File dir = projectPath.toFile();
    if (!dir.exists() || !dir.isDirectory()) {
        throw new IOException(String.format("The chaincode path \"%s\" is invalid", projectPath));
    }

    StringBuilder hashBuilder = new StringBuilder(hash);
    Files.walk(projectPath).sorted(Comparator.naturalOrder()).filter(Files::isRegularFile).map(Path::toFile)
            .forEach(file -> {
                try {
                    byte[] buf = readFile(file);
                    byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes());
                    hashBuilder.setLength(0);
                    hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest())));
                } catch (IOException ex) {
                    throw new RuntimeException(
                            String.format("Error while reading file %s", file.getAbsolutePath()), ex);
                }
            });

    // If original hash and final hash are the same, it indicates that no new contents were found
    if (hashBuilder.toString().equals(hash)) {
        throw new IOException(String.format("The chaincode directory \"%s\" has no files", projectPath));
    }
    return hashBuilder.toString();
}

From source file:org.hyperledger.fabric.sdk.helper.Utils.java

License:Open Source License

/**
 * Generate hash of a chaincode directory
 *
 * @param rootDir      Root directory/*www .j  a  v  a 2 s.c  om*/
 * @param chaincodeDir Channel code directory
 * @param hash         Previous hash (if any)
 * @return hash of the directory
 * @throws IOException
 */
public static String generateDirectoryHash(String rootDir, String chaincodeDir, String hash)
        throws IOException {
    // Generate the project directory
    Path projectPath = null;
    if (rootDir == null) {
        projectPath = Paths.get(chaincodeDir);
    } else {
        projectPath = Paths.get(rootDir, chaincodeDir);
    }

    File dir = projectPath.toFile();
    if (!dir.exists() || !dir.isDirectory()) {
        throw new IOException(String.format("The chaincode path \"%s\" is invalid", projectPath));
    }

    StringBuilder hashBuilder = new StringBuilder(hash);
    Files.walk(projectPath).sorted(Comparator.naturalOrder()).filter(Files::isRegularFile).map(Path::toFile)
            .forEach(file -> {
                try {
                    byte[] buf = readFile(file);
                    byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes(UTF_8));
                    hashBuilder.setLength(0);
                    hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest())));
                } catch (IOException ex) {
                    throw new RuntimeException(
                            String.format("Error while reading file %s", file.getAbsolutePath()), ex);
                }
            });

    // If original hash and final hash are the same, it indicates that no new contents were found
    if (hashBuilder.toString().equals(hash)) {
        throw new IOException(String.format("The chaincode directory \"%s\" has no files", projectPath));
    }
    return hashBuilder.toString();
}

From source file:org.hyperledger.fabric.sdk.transaction.TransactionBuilder.java

License:Open Source License

/**
 * Create a transaction//from   w w  w.  j  a va 2 s . co  m
 * @param ccType Chaincode type (GOLANG, JAVA etc)
 * @param transactionType The type of transaction (Deploy/Query/Invoke etc)
 * @param name name of the chaincode
 * @param args argument list for the transaction
 * @param codePackage chaincode contents - only used for NetMode deploy transaction
 * @param txId transaction ID
 * @param chaincodePath Chain code path - only used for DevMode deploy transaction
 * @return {@link Fabric.Transaction.Builder}
 */
protected Fabric.Transaction.Builder createTransactionBuilder(Chaincode.ChaincodeSpec.Type ccType,
        Fabric.Transaction.Type transactionType, String name, List<String> args, byte[] codePackage,
        String txId, String chaincodePath) throws CryptoException, IOException {
    // build chaincodeId
    Chaincode.ChaincodeID.Builder chaincodeIDBuilder = Chaincode.ChaincodeID.newBuilder().setName(name);
    if (chaincodePath != null) {
        chaincodeIDBuilder = chaincodeIDBuilder.setPath(chaincodePath);
    }
    Chaincode.ChaincodeID chaincodeID = chaincodeIDBuilder.build();

    // build chaincodeInput
    List<ByteString> argList = new ArrayList<>(args.size());
    for (String arg : args) {
        argList.add(ByteString.copyFrom(arg.getBytes()));
    }
    Chaincode.ChaincodeInput chaincodeInput = Chaincode.ChaincodeInput.newBuilder().addAllArgs(argList).build();

    // Construct the ChaincodeSpec
    ChaincodeSpec chaincodeSpec = Chaincode.ChaincodeSpec.newBuilder().setType(ccType)
            .setChaincodeID(chaincodeID).setCtorMsg(chaincodeInput).build();

    // create payload
    ByteString payload = null;

    switch (transactionType.getNumber()) {
    case Fabric.Transaction.Type.CHAINCODE_DEPLOY_VALUE:
        // Construct the ChaincodeDeploymentSpec (i.e. the payload)
        ChaincodeDeploymentSpec.Builder chaincodeDeploymentSpecBuilder = Chaincode.ChaincodeDeploymentSpec
                .newBuilder().setChaincodeSpec(chaincodeSpec);

        if (codePackage != null && codePackage.length > 0) {
            chaincodeDeploymentSpecBuilder = chaincodeDeploymentSpecBuilder
                    .setCodePackage(ByteString.copyFrom(codePackage));
        }
        payload = chaincodeDeploymentSpecBuilder.build().toByteString();
        break;
    case Fabric.Transaction.Type.CHAINCODE_QUERY_VALUE:
    case Fabric.Transaction.Type.CHAINCODE_INVOKE_VALUE:
        // Construct the ChaincodeDeploymentSpec (i.e. the payload)
        payload = Chaincode.ChaincodeInvocationSpec.newBuilder().setChaincodeSpec(chaincodeSpec).build()
                .toByteString();
        break;
    }

    // public or confidential?
    ConfidentialityLevel confidentialityLevel = request.isConfidential()
            ? Chaincode.ConfidentialityLevel.CONFIDENTIAL
            : Chaincode.ConfidentialityLevel.PUBLIC;

    // Initialize a transaction structure
    Fabric.Transaction.Builder txBuilder = Fabric.Transaction.newBuilder().setType(transactionType)
            .setChaincodeID(chaincodeID.toByteString()).setTxid(txId).setTimestamp(SDKUtil.generateTimestamp())
            .setConfidentialityLevel(confidentialityLevel);

    if (payload != null) {
        txBuilder = txBuilder.setPayload(payload);
    }

    if (request.getMetadata() != null && request.getMetadata().length > 0) {
        txBuilder.setMetadata(ByteString.copyFrom(request.getMetadata()));
    }

    if (request.getUserCert() != null) {
        byte[] certRaw = context.getTCert().getCert();
        logger.debug("========== Invoker Cert: " + Hex.toHexString(certRaw));
        byte[] nonceRaw = context.getNonce();
        byte[] bindingMsg = Arrays.concatenate(certRaw, nonceRaw);
        logger.debug("========== Binding Msg [%s]" + Hex.toHexString(bindingMsg));
        byte[] binding = context.getChain().getCryptoPrimitives().hash(bindingMsg);
        logger.debug("========== Binding: " + Hex.toHexString(binding));
        byte[] ctor = chaincodeSpec.getCtorMsg().toByteArray();
        logger.debug("========== Ctor: " + Hex.toHexString(ctor));
        byte[] txmsg = Arrays.concatenate(ctor, binding);
        logger.debug("========== Payload||binding: " + Hex.toHexString(txmsg));
        BigInteger[] mdsig = context.getChain().getCryptoPrimitives()
                .ecdsaSign(request.getUserCert().getPrivateKey(), txmsg);
        byte[] sigma = context.getChain().getCryptoPrimitives()
                .toDER(new byte[][] { mdsig[0].toByteArray(), mdsig[1].toByteArray() });
        logger.debug("========== Sigma: " + Hex.toHexString(sigma));
        txBuilder.setMetadata(ByteString.copyFrom(sigma));
    }

    return txBuilder;
}