Example usage for org.bouncycastle.openpgp.operator.jcajce JcePublicKeyKeyEncryptionMethodGenerator JcePublicKeyKeyEncryptionMethodGenerator

List of usage examples for org.bouncycastle.openpgp.operator.jcajce JcePublicKeyKeyEncryptionMethodGenerator JcePublicKeyKeyEncryptionMethodGenerator

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.jcajce JcePublicKeyKeyEncryptionMethodGenerator JcePublicKeyKeyEncryptionMethodGenerator.

Prototype

public JcePublicKeyKeyEncryptionMethodGenerator(PGPPublicKey key) 

Source Link

Document

Create a public key encryption method generator with the method to be based on the passed in key.

Usage

From source file:com.goodvikings.cryptim.api.KeyRing.java

License:BEER-WARE LICENSE

public void signEncryptMessage(InputStream in, OutputStream out, String jid)
        throws IOException, PGPException, SignatureException {
    out = new ArmoredOutputStream(out);

    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SYMM_ALG)
            .setWithIntegrityPacket(true).setSecureRandom(rand).setProvider(PROVIDER));
    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(keys.get(jid)).setProvider(PROVIDER));

    OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]);
    OutputStream compressedData = new PGPCompressedDataGenerator(COMP_ALG).open(encryptedOut);

    PGPSignatureGenerator sGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(kp.getPrivateKey().getPublicKeyPacket().getAlgorithm(), HASH_ALG)
                    .setProvider(PROVIDER));
    sGen.init(PGPSignature.BINARY_DOCUMENT, kp.getPrivateKey());
    sGen.generateOnePassVersion(false).encode(compressedData);

    OutputStream finalOut = new PGPLiteralDataGenerator().open(compressedData, PGPLiteralData.BINARY, "",
            new Date(), new byte[BUFFER_SIZE]);

    byte[] buf = new byte[BUFFER_SIZE];
    int len;//  w  w w  . j a v a2s .c  o  m
    while ((len = in.read(buf)) > 0) {
        finalOut.write(buf, 0, len);
        sGen.update(buf, 0, len);
    }

    in.close();

    finalOut.close();
    sGen.generate().encode(compressedData);
    compressedData.close();
    encryptedOut.close();
    out.close();
}

From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java

License:Open Source License

public String getEncryptedMessage(byte[] data) {
    Security.addProvider(new BouncyCastleProvider());

    try {/*  w  w  w  .  j  a  v a 2 s.c o  m*/

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        OutputStream out = new ArmoredOutputStream(baos);
        byte[] compressedData = compressFile(data, CompressionAlgorithmTags.ZIP);
        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128).setWithIntegrityPacket(true)
                        .setSecureRandom(new SecureRandom()).setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(this.publicKey).setProvider("BC"));
        OutputStream cOut = encGen.open(out, compressedData.length);
        cOut.write(compressedData);
        cOut.close();
        out.close();
        baos.flush();
        return new String(baos.toByteArray());
    } catch (PGPException | IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:divconq.pgp.EncryptedFileStream.java

License:Open Source License

public void addPublicKey(PGPPublicKey pubKey) {
    this.methods.add(new JcePublicKeyKeyEncryptionMethodGenerator(pubKey));
}

From source file:divconq.pgp.EncryptedFileStream.java

License:Open Source License

public void loadPublicKey(Path keyring) throws IOException, PGPException {
    // TODO move some of this to dcPGPUtil
    PGPPublicKey pubKey = null;//w w w.j av a 2  s. c om

    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring.toFile()));

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
            org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator());

    //
    // we just loop through the collection till we find a key suitable for encryption, in the real
    // world you would probably want to be a bit smarter about this.
    //

    @SuppressWarnings("rawtypes")
    Iterator keyRingIter = pgpPub.getKeyRings();

    while (keyRingIter.hasNext() && (pubKey == null)) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();

        @SuppressWarnings("rawtypes")
        Iterator keyIter = keyRing.getPublicKeys();

        while (keyIter.hasNext() && (pubKey == null)) {
            PGPPublicKey key = (PGPPublicKey) keyIter.next();

            if (key.isEncryptionKey())
                pubKey = key;
        }
    }

    if (pubKey == null)
        throw new IllegalArgumentException("Can't find encryption key in key ring.");

    this.methods.add(new JcePublicKeyKeyEncryptionMethodGenerator(pubKey));
}

From source file:divconq.test.pgp.PGPWriter.java

License:Open Source License

/**
 * Start here with an open for a given recipient (public) key.
 * /*from  w  w w . j  a v  a2s  . c o  m*/
 * @param key encrypt to this key
 * @throws IOException if there are problems encoding the packets
 * @throws PGPException problems with key or crypto
 */
public void open(PGPPublicKey key) throws IOException, PGPException {
    this.open(PGPEncryptedData.AES_256, new JcePublicKeyKeyEncryptionMethodGenerator(key));
}

From source file:divconq.test.pgp.PGPWriter2.java

License:Open Source License

@SuppressWarnings("resource")
public void test2(String srcpath, String destpath, String keyring) throws Exception {
    Path src = Paths.get(srcpath);

    // file data 
    byte[] fileData = Files.readAllBytes(src);

    // dest//from  ww w . ja  va 2 s  .c o  m
    OutputStream dest = new BufferedOutputStream(new FileOutputStream(destpath));

    // encryption key
    PGPPublicKey pubKey = null;

    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring));

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
            org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator());

    //
    // we just loop through the collection till we find a key suitable for encryption, in the real
    // world you would probably want to be a bit smarter about this.
    //

    @SuppressWarnings("rawtypes")
    Iterator keyRingIter = pgpPub.getKeyRings();

    while (keyRingIter.hasNext() && (pubKey == null)) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();

        @SuppressWarnings("rawtypes")
        Iterator keyIter = keyRing.getPublicKeys();

        while (keyIter.hasNext() && (pubKey == null)) {
            PGPPublicKey key = (PGPPublicKey) keyIter.next();

            if (key.isEncryptionKey())
                pubKey = key;
        }
    }

    if (pubKey == null)
        throw new IllegalArgumentException("Can't find encryption key in key ring.");

    String fileName = src.getFileName().toString();
    byte[] encName = Utf8Encoder.encode(fileName);
    long modificationTime = System.currentTimeMillis();

    SecureRandom rand = new SecureRandom();
    int algorithm = PGPEncryptedData.AES_256;

    Cipher cipher = null;

    ByteBuf leadingbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb
    ByteBuf encbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb

    // *******************************************************************
    // public key packet
    // *******************************************************************

    PGPKeyEncryptionMethodGenerator method = new JcePublicKeyKeyEncryptionMethodGenerator(pubKey);

    byte[] key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand);

    byte[] sessionInfo = new byte[key.length + 3];

    // add algorithm
    sessionInfo[0] = (byte) algorithm;

    // add key
    System.arraycopy(key, 0, sessionInfo, 1, key.length);

    // add checksum 
    int check = 0;

    for (int i = 1; i != sessionInfo.length - 2; i++)
        check += sessionInfo[i] & 0xff;

    sessionInfo[sessionInfo.length - 2] = (byte) (check >> 8);
    sessionInfo[sessionInfo.length - 1] = (byte) (check);

    ContainedPacket packet1 = method.generate(algorithm, sessionInfo);

    byte[] encoded1 = packet1.getEncoded();

    leadingbuf.writeBytes(encoded1);

    // *******************************************************************
    // encrypt packet, add IV to encryption though
    // *******************************************************************

    leadingbuf.writeByte(0xC0 | PacketTags.SYM_ENC_INTEGRITY_PRO);

    this.writePacketLength(leadingbuf, 0); // 0 = we don't know

    leadingbuf.writeByte(1); // version number

    String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding";

    DefaultJcaJceHelper helper = new DefaultJcaJceHelper();

    cipher = helper.createCipher(cName);

    byte[] iv = new byte[cipher.getBlockSize()];

    cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, key), new IvParameterSpec(iv));

    // ******************** start encryption **********************

    // --- encrypt checksum for encrypt packet, part of the encrypted output --- 

    byte[] inLineIv = new byte[cipher.getBlockSize() + 2];

    rand.nextBytes(inLineIv);

    inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3];
    inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4];

    encbuf.writeBytes(inLineIv);

    System.out.println("bytes written a: " + encbuf.readableBytes());

    // --- data packet ---

    int chunkpos = 0;

    int headerlen = 1 // format
            + 1 // name length
            + encName.length // file name
            + 4; // time

    encbuf.writeByte(0xC0 | PacketTags.LITERAL_DATA);

    int packetsize = 512 - headerlen;

    if (fileData.length - chunkpos < packetsize) {
        packetsize = fileData.length - chunkpos;

        this.writePacketLength(encbuf, headerlen + packetsize);
    } else {
        encbuf.writeByte(0xE9); // 512 packet length
    }

    System.out.println("bytes written b: " + encbuf.readableBytes());

    encbuf.writeByte(PGPLiteralData.BINARY); // data format

    encbuf.writeByte((byte) encName.length); // file name

    encbuf.writeBytes(encName);

    encbuf.writeInt((int) (modificationTime / 1000)); // mod time

    System.out.println("bytes written c: " + encbuf.readableBytes());

    encbuf.writeBytes(fileData, chunkpos, packetsize);

    System.out.println("bytes written d: " + encbuf.readableBytes());

    chunkpos += packetsize;

    // write one or more literal packets
    while (chunkpos < fileData.length) {
        packetsize = 512;

        // check if this is the final packet
        if (fileData.length - chunkpos <= packetsize) {
            packetsize = fileData.length - chunkpos;

            this.writePacketLength(encbuf, packetsize);
        } else {
            encbuf.writeByte(0xE9); // full 512 packet length
        }

        encbuf.writeBytes(fileData, chunkpos, packetsize);

        chunkpos += packetsize;
    }

    // protection packet
    encbuf.writeByte(0xC0 | PacketTags.MOD_DETECTION_CODE);
    encbuf.writeByte(20); // packet length

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.update(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    byte[] rv = md.digest();

    encbuf.writeBytes(rv);

    System.out.println("Pre-Encrypted Hex");

    this.hexDump(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    System.out.println();
    System.out.println();

    // ***** encryption data ready *********

    byte[] encdata = cipher.doFinal(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    // add encrypted data to main buffer
    leadingbuf.writeBytes(encdata);

    System.out.println("Final Hex");

    this.hexDump(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex());

    System.out.println();
    System.out.println();

    // write to file
    dest.write(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex());

    dest.flush();
    dest.close();
}

From source file:divconq.test.pgp.PGPWriter2.java

License:Open Source License

@SuppressWarnings("resource")
public void test1(String srcpath, String destpath, String keyring) throws Exception {
    Path src = Paths.get(srcpath);

    // file data 
    byte[] story = Files.readAllBytes(src);

    // dest/*  ww w  .  j  a  v  a 2s.  c om*/
    OutputStream dest = new BufferedOutputStream(new FileOutputStream(destpath));

    // encryption key
    PGPPublicKey pubKey = null;

    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring));

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
            org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator());

    //
    // we just loop through the collection till we find a key suitable for encryption, in the real
    // world you would probably want to be a bit smarter about this.
    //

    @SuppressWarnings("rawtypes")
    Iterator keyRingIter = pgpPub.getKeyRings();

    while (keyRingIter.hasNext() && (pubKey == null)) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();

        @SuppressWarnings("rawtypes")
        Iterator keyIter = keyRing.getPublicKeys();

        while (keyIter.hasNext() && (pubKey == null)) {
            PGPPublicKey key = (PGPPublicKey) keyIter.next();

            if (key.isEncryptionKey())
                pubKey = key;
        }
    }

    if (pubKey == null)
        throw new IllegalArgumentException("Can't find encryption key in key ring.");

    String fileName = src.getFileName().toString();
    byte[] encName = Utf8Encoder.encode(fileName);
    long modificationTime = System.currentTimeMillis();

    SecureRandom rand = new SecureRandom();
    int algorithm = PGPEncryptedData.AES_256;

    Cipher cipher = null;

    ByteBuf leadingbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb
    ByteBuf encbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb

    // *******************************************************************
    // public key packet
    // *******************************************************************

    PGPKeyEncryptionMethodGenerator method = new JcePublicKeyKeyEncryptionMethodGenerator(pubKey);

    byte[] key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand);

    byte[] sessionInfo = new byte[key.length + 3];

    // add algorithm
    sessionInfo[0] = (byte) algorithm;

    // add key
    System.arraycopy(key, 0, sessionInfo, 1, key.length);

    // add checksum 
    int check = 0;

    for (int i = 1; i != sessionInfo.length - 2; i++)
        check += sessionInfo[i] & 0xff;

    sessionInfo[sessionInfo.length - 2] = (byte) (check >> 8);
    sessionInfo[sessionInfo.length - 1] = (byte) (check);

    ContainedPacket packet1 = method.generate(algorithm, sessionInfo);

    byte[] encoded1 = packet1.getEncoded();

    leadingbuf.writeBytes(encoded1);

    // *******************************************************************
    // encrypt packet, add IV to 
    // *******************************************************************

    String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding";

    DefaultJcaJceHelper helper = new DefaultJcaJceHelper();

    cipher = helper.createCipher(cName);

    byte[] iv = new byte[cipher.getBlockSize()];

    cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, key), new IvParameterSpec(iv));

    // ******************** start encryption **********************

    // --- encrypt checksum for encrypt packet, part of the encrypted output --- 

    byte[] inLineIv = new byte[cipher.getBlockSize() + 2];

    rand.nextBytes(inLineIv);

    inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3];
    inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4];

    encbuf.writeBytes(inLineIv);

    // --- data packet ---

    encbuf.writeByte(0xC0 | PacketTags.LITERAL_DATA);

    this.writePacketLength(encbuf, 1 // format
            + 1 // name length
            + encName.length // file name
            + 4 // time
            + story.length // data
    );

    encbuf.writeByte(PGPLiteralData.BINARY);

    encbuf.writeByte((byte) encName.length);

    encbuf.writeBytes(encName);

    encbuf.writeInt((int) (modificationTime / 1000));

    encbuf.writeBytes(story);

    // protection packet
    encbuf.writeByte(0xC0 | PacketTags.MOD_DETECTION_CODE);
    encbuf.writeByte(20); // packet length

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.update(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    byte[] rv = md.digest();

    encbuf.writeBytes(rv);

    System.out.println("Encrypted Hex");

    this.hexDump(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    System.out.println();
    System.out.println();

    // ***** encryption data ready *********

    byte[] encdata = cipher.doFinal(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex());

    leadingbuf.writeByte(0xC0 | PacketTags.SYM_ENC_INTEGRITY_PRO);

    /*
    this.writePacketLength(leadingbuf, 
     1      // version 
     + encdata.length       // encrypted data
       );
       */

    this.writePacketLength(leadingbuf, 0); // 0 = we don't know

    leadingbuf.writeByte(1); // version number

    // add encrypted data to main buffer
    leadingbuf.writeBytes(encdata);

    System.out.println("Final Hex");

    this.hexDump(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex());

    System.out.println();
    System.out.println();

    // write to file
    dest.write(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex());

    dest.flush();
    dest.close();
}

From source file:google.registry.rde.RydePgpEncryptionOutputStream.java

License:Open Source License

private static OutputStream createDelegate(int bufferSize, OutputStream os, PGPPublicKey receiverKey) {
    try {/* ww  w. j ava2 s  .  c o  m*/
        PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(CIPHER).setWithIntegrityPacket(USE_INTEGRITY_PACKET)
                        .setSecureRandom(SecureRandom.getInstance(RANDOM_SOURCE)).setProvider(PROVIDER_NAME));
        encryptor.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(receiverKey));
        return encryptor.open(os, new byte[bufferSize]);
    } catch (NoSuchAlgorithmException e) {
        throw new ProviderException(e);
    } catch (IOException | PGPException e) {
        throw new RuntimeException(e);
    }
}

From source file:hh.learnj.test.license.test.lincense3j.KeyBasedFileProcessor.java

private static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor,
        boolean withIntegrityCheck) throws IOException, NoSuchProviderException {
    if (armor) {/*from ww w.j a  va 2  s .co m*/
        out = new ArmoredOutputStream(out);
    }

    try {
        byte[] bytes = MyPGPUtil.compressFile(fileName, CompressionAlgorithmTags.ZIP);

        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
                        .setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom())
                        .setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));

        OutputStream cOut = encGen.open(out, bytes.length);

        cOut.write(bytes);
        cOut.close();

        if (armor) {
            out.close();
        }
    } catch (PGPException e) {
        System.err.println(e);
        if (e.getUnderlyingException() != null) {
            e.getUnderlyingException().printStackTrace();
        }
    }
}

From source file:org.apache.camel.converter.crypto.PGPDataFormat.java

License:Apache License

public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
    List<String> userids = determineEncryptionUserIds(exchange);
    List<PGPPublicKey> keys = PGPDataFormatUtil.findPublicKeys(exchange.getContext(), findKeyFileName(exchange),
            findEncryptionKeyRing(exchange), userids, true);
    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.");
    }// w ww .  ja  v a 2  s . c o  m

    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]);

    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange));
    OutputStream comOut = new BufferedOutputStream(comData.open(encOut));

    PGPSignatureGenerator sigGen = createSignatureGenerator(exchange, comOut);

    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    String fileName = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
    if (ObjectHelper.isEmpty(fileName)) {
        // This marks the file as For Your Eyes Only... may cause problems for the receiver if they use
        // an automated process to decrypt as the filename is appended with _CONSOLE
        fileName = PGPLiteralData.CONSOLE;
    }
    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 (sigGen != null) {
                sigGen.update(buffer, 0, bytesRead);
            }
            litOut.flush();
        }
    } finally {
        IOHelper.close(litOut);
        if (sigGen != null) {
            sigGen.generate().encode(comOut);
        }
        IOHelper.close(comOut, encOut, outputStream, input);
    }
}