Search in sources :

Example 1 with ArmoredOutputStream

use of org.bouncycastle.bcpg.ArmoredOutputStream in project camel by apache.

the class PGPKeyAccessDataFormat method marshal.

public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
    //NOPMD
    List<String> userids = determineEncryptionUserIds(exchange);
    List<PGPPublicKey> keys = publicKeyAccessor.getEncryptionKeys(exchange, userids);
    if (keys.isEmpty()) {
        throw new IllegalArgumentException("Cannot PGP encrypt message. No public encryption key found for the User Ids " + userids + " in the public keyring. Either specify other User IDs or add correct public keys to the keyring.");
    }
    exchange.getOut().setHeader(NUMBER_OF_ENCRYPTION_KEYS, Integer.valueOf(keys.size()));
    InputStream input = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
    if (armored) {
        outputStream = new ArmoredOutputStream(outputStream);
    }
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(findAlgorithm(exchange)).setWithIntegrityPacket(integrity).setSecureRandom(new SecureRandom()).setProvider(getProvider()));
    // several keys can be added
    for (PGPPublicKey key : keys) {
        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key));
    }
    OutputStream encOut = encGen.open(outputStream, new byte[BUFFER_SIZE]);
    OutputStream comOut;
    if (withCompressedDataPacket) {
        PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange));
        comOut = new BufferedOutputStream(comData.open(encOut));
    } else {
        comOut = encOut;
        LOG.debug("No Compressed Data packet is added");
    }
    List<PGPSignatureGenerator> sigGens = createSignatureGenerator(exchange, comOut);
    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    String fileName = findFileName(exchange);
    OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, fileName, new Date(), new byte[BUFFER_SIZE]);
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            litOut.write(buffer, 0, bytesRead);
            if (sigGens != null && !sigGens.isEmpty()) {
                for (PGPSignatureGenerator sigGen : sigGens) {
                    // not nested therefore it is the same for all
                    // can this be improved that we only do it for one sigGen and set the result on the others?
                    sigGen.update(buffer, 0, bytesRead);
                }
            }
            litOut.flush();
        }
    } finally {
        IOHelper.close(litOut);
        if (sigGens != null && !sigGens.isEmpty()) {
            // reverse order
            for (int i = sigGens.size() - 1; i > -1; i--) {
                PGPSignatureGenerator sigGen = sigGens.get(i);
                sigGen.generate().encode(comOut);
            }
        }
        IOHelper.close(comOut, encOut, outputStream, input);
    }
}
Also used : PGPSignatureGenerator(org.bouncycastle.openpgp.PGPSignatureGenerator) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) PGPCompressedDataGenerator(org.bouncycastle.openpgp.PGPCompressedDataGenerator) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) SecureRandom(java.security.SecureRandom) PGPLiteralDataGenerator(org.bouncycastle.openpgp.PGPLiteralDataGenerator) PGPEncryptedDataGenerator(org.bouncycastle.openpgp.PGPEncryptedDataGenerator) Date(java.util.Date) JcePublicKeyKeyEncryptionMethodGenerator(org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator) BufferedOutputStream(java.io.BufferedOutputStream) JcePGPDataEncryptorBuilder(org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder)

Example 2 with ArmoredOutputStream

use of org.bouncycastle.bcpg.ArmoredOutputStream in project nifi by apache.

the class PGPUtil method encrypt.

public static void encrypt(InputStream in, OutputStream out, String algorithm, String provider, int cipher, String filename, PGPKeyEncryptionMethodGenerator encryptionMethodGenerator) throws IOException, PGPException {
    if (StringUtils.isEmpty(algorithm)) {
        throw new IllegalArgumentException("The algorithm must be specified");
    }
    final boolean isArmored = EncryptContent.isPGPArmoredAlgorithm(algorithm);
    OutputStream output = out;
    if (isArmored) {
        output = new ArmoredOutputStream(out);
    }
    // Default value, do not allow null encryption
    if (cipher == PGPEncryptedData.NULL) {
        logger.warn("Null encryption not allowed; defaulting to AES-128");
        cipher = PGPEncryptedData.AES_128;
    }
    try {
        // TODO: Can probably hard-code provider to BC and remove one method parameter
        PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(cipher).setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(provider));
        encryptedDataGenerator.addMethod(encryptionMethodGenerator);
        try (OutputStream encryptedOut = encryptedDataGenerator.open(output, new byte[BUFFER_SIZE])) {
            PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZIP, Deflater.BEST_SPEED);
            try (OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BUFFER_SIZE])) {
                PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
                try (OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, filename, new Date(), new byte[BUFFER_SIZE])) {
                    final byte[] buffer = new byte[BLOCK_SIZE];
                    int len;
                    while ((len = in.read(buffer)) > -1) {
                        literalOut.write(buffer, 0, len);
                    }
                }
            }
        }
    } finally {
        if (isArmored) {
            output.close();
        }
    }
}
Also used : OutputStream(java.io.OutputStream) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) PGPCompressedDataGenerator(org.bouncycastle.openpgp.PGPCompressedDataGenerator) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) SecureRandom(java.security.SecureRandom) PGPLiteralDataGenerator(org.bouncycastle.openpgp.PGPLiteralDataGenerator) PGPEncryptedDataGenerator(org.bouncycastle.openpgp.PGPEncryptedDataGenerator) Date(java.util.Date) JcePGPDataEncryptorBuilder(org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder)

Example 3 with ArmoredOutputStream

use of org.bouncycastle.bcpg.ArmoredOutputStream in project gerrit by GerritCodeReview.

the class GpgKeys method toJson.

public static GpgKeyInfo toJson(PGPPublicKey key, CheckResult checkResult) throws IOException {
    GpgKeyInfo info = new GpgKeyInfo();
    if (key != null) {
        info.id = PublicKeyStore.keyIdToString(key.getKeyID());
        info.fingerprint = Fingerprint.toString(key.getFingerprint());
        Iterator<String> userIds = key.getUserIDs();
        info.userIds = ImmutableList.copyOf(userIds);
        try (ByteArrayOutputStream out = new ByteArrayOutputStream(4096)) {
            try (ArmoredOutputStream aout = new ArmoredOutputStream(out)) {
                // This is not exactly the key stored in the store, but is equivalent. In
                // particular, it will have a Bouncy Castle version string. The armored
                // stream reader in PublicKeyStore doesn't give us an easy way to extract
                // the original ASCII armor.
                key.encode(aout);
            }
            info.key = new String(out.toByteArray(), UTF_8);
        }
    }
    info.status = checkResult.getStatus();
    info.problems = checkResult.getProblems();
    return info;
}
Also used : ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) IdString(com.google.gerrit.extensions.restapi.IdString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GpgKeyInfo(com.google.gerrit.extensions.common.GpgKeyInfo)

Example 4 with ArmoredOutputStream

use of org.bouncycastle.bcpg.ArmoredOutputStream in project gradle by gradle.

the class WriteDependencyVerificationFile method writeAsciiArmoredKeyRingFile.

private void writeAsciiArmoredKeyRingFile(File ascii, ImmutableList<PGPPublicKeyRing> allKeyRings) throws IOException {
    if (ascii.exists()) {
        ascii.delete();
    }
    boolean hasKey = false;
    for (PGPPublicKeyRing keyRing : allKeyRings) {
        // First let's write some human readable info about the keyring being serialized
        try (OutputStream out = new FileOutputStream(ascii, true)) {
            if (hasKey) {
                out.write('\n');
            }
            Iterator<PGPPublicKey> pks = keyRing.getPublicKeys();
            while (pks.hasNext()) {
                boolean hasUid = false;
                PGPPublicKey pk = pks.next();
                String keyType = pk.isMasterKey() ? "pub" : "sub";
                out.write((keyType + "    " + SecuritySupport.toLongIdHexString(pk.getKeyID()).toUpperCase() + "\n").getBytes(StandardCharsets.US_ASCII));
                List<String> userIDs = PGPUtils.getUserIDs(pk);
                for (String uid : userIDs) {
                    hasUid = true;
                    out.write(("uid    " + uid + "\n").getBytes(StandardCharsets.US_ASCII));
                }
                if (hasUid) {
                    out.write('\n');
                }
            }
        }
        // Then write the ascii armored keyring
        try (FileOutputStream fos = new FileOutputStream(ascii, true);
            ArmoredOutputStream out = new ArmoredOutputStream(fos)) {
            keyRing.encode(out, true);
        }
        hasKey = true;
    }
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) FileOutputStream(java.io.FileOutputStream) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream)

Example 5 with ArmoredOutputStream

use of org.bouncycastle.bcpg.ArmoredOutputStream in project ant-ivy by apache.

the class OpenPGPSignatureGenerator method sign.

public void sign(File src, File dest) throws IOException {
    OutputStream out = null;
    InputStream in = null;
    InputStream keyIn = null;
    try {
        if (secring == null) {
            secring = System.getProperty("user.home") + "/.gnupg/secring.gpg";
        }
        if (pgpSec == null) {
            keyIn = new FileInputStream(secring);
            pgpSec = readSecretKey(keyIn);
        }
        PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray());
        PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(decryptor);
        PGPSignatureGenerator sGen = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), PGPUtil.SHA1));
        sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
        in = new FileInputStream(src);
        out = new BCPGOutputStream(new ArmoredOutputStream(new FileOutputStream(dest)));
        int ch = 0;
        while ((ch = in.read()) >= 0) {
            sGen.update((byte) ch);
        }
        sGen.generate().encode(out);
    } catch (PGPException e) {
        throw new IOException(e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (keyIn != null) {
            try {
                keyIn.close();
            } catch (IOException e) {
            }
        }
    }
}
Also used : PGPSignatureGenerator(org.bouncycastle.openpgp.PGPSignatureGenerator) PBESecretKeyDecryptor(org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor) BcPGPContentSignerBuilder(org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) BCPGOutputStream(org.bouncycastle.bcpg.BCPGOutputStream) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) BcPGPDigestCalculatorProvider(org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider) BCPGOutputStream(org.bouncycastle.bcpg.BCPGOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) PGPException(org.bouncycastle.openpgp.PGPException) FileOutputStream(java.io.FileOutputStream) BcPBESecretKeyDecryptorBuilder(org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder) PGPPrivateKey(org.bouncycastle.openpgp.PGPPrivateKey)

Aggregations

ArmoredOutputStream (org.bouncycastle.bcpg.ArmoredOutputStream)7 OutputStream (java.io.OutputStream)4 PGPSignatureGenerator (org.bouncycastle.openpgp.PGPSignatureGenerator)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 FileOutputStream (java.io.FileOutputStream)2 InputStream (java.io.InputStream)2 SecureRandom (java.security.SecureRandom)2 Date (java.util.Date)2 BCPGOutputStream (org.bouncycastle.bcpg.BCPGOutputStream)2 PGPCompressedDataGenerator (org.bouncycastle.openpgp.PGPCompressedDataGenerator)2 PGPEncryptedDataGenerator (org.bouncycastle.openpgp.PGPEncryptedDataGenerator)2 PGPLiteralDataGenerator (org.bouncycastle.openpgp.PGPLiteralDataGenerator)2 PGPPublicKey (org.bouncycastle.openpgp.PGPPublicKey)2 BcPGPContentSignerBuilder (org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder)2 JcePGPDataEncryptorBuilder (org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder)2 GpgKeyInfo (com.google.gerrit.extensions.common.GpgKeyInfo)1 IdString (com.google.gerrit.extensions.restapi.IdString)1 PublicKeyStore.keyIdToString (com.google.gerrit.gpg.PublicKeyStore.keyIdToString)1 PublicKeyStore.keyToString (com.google.gerrit.gpg.PublicKeyStore.keyToString)1 BufferedOutputStream (java.io.BufferedOutputStream)1