Example usage for org.bouncycastle.openpgp PGPLiteralData BINARY

List of usage examples for org.bouncycastle.openpgp PGPLiteralData BINARY

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPLiteralData BINARY.

Prototype

char BINARY

To view the source code for org.bouncycastle.openpgp PGPLiteralData BINARY.

Click Source Link

Document

Format tag for binary literal data

Usage

From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java

License:Apache License

/**
 * PGP Encrypt a stream.//from ww w .  j  av a  2s.com
 *
 * @param plainTextStream The stream that contains the plain-text data.
 * @param publicKey       The public key to use for encryption.
 * @param armoured        {@code true}: ASCII armor the encrypted data.
 *
 * @return The encrypted data stream.
 *
 * @throws NoSuchProviderException
 * @throws IOException
 * @throws PGPException
 */
public static InputStream encrypt(final InputStream plainTextStream, final PGPPublicKey publicKey,
        final boolean armoured) throws IOException, NoSuchProviderException, PGPException {

    /* Compress and extract literal data packets that can be encrypted. */
    PGPEncryptedDataGenerator encryptedDataGenerator = null;
    try (ByteArrayOutputStream decryptedStream = new ByteArrayOutputStream();
            ByteArrayOutputStream encryptedByteStream = new ByteArrayOutputStream()) {
        PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
        PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZLIB);
        OutputStream literalStream = literalDataGenerator.open(compressor.open(decryptedStream),
                PGPLiteralData.BINARY, "", new Date(), new byte[4096]);
        ByteStreams.copy(plainTextStream, literalStream);
        compressor.close();

        /* Encrypt compressed data. */
        encryptedDataGenerator = new PGPEncryptedDataGenerator(SymmetricKeyAlgorithmTags.CAST5,
                new SecureRandom(), BouncyCastleProvider.PROVIDER_NAME);
        encryptedDataGenerator.addMethod(publicKey);

        /* Create the encrypted output stream, armour if necessary. */
        OutputStream encryptedStream = encryptedByteStream;
        if (armoured)
            encryptedStream = new ArmoredOutputStream(encryptedStream);

        /* Create and write out the encrypted file. */
        OutputStream encryptionStream = encryptedDataGenerator.open(encryptedStream, new byte[4096]);
        ByteStreams.copy(new ByteArrayInputStream(decryptedStream.toByteArray()), encryptionStream);

        return new ByteArrayInputStream(encryptedByteStream.toByteArray());
    } finally {
        if (encryptedDataGenerator != null)
            encryptedDataGenerator.close();
    }
}

From source file:com.verhas.licensor.License.java

License:Open Source License

/**
 * Encode the currently loaded/created license.
 * //from   ww w.j  av a 2 s.c  om
 * @param keyPassPhraseString
 *            the pass phrase to the signing key that was loaded.
 * @return the license encoded as ascii string.
 * @throws java.io.IOException
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.NoSuchProviderException
 * @throws org.bouncycastle.openpgp.PGPException
 * @throws java.security.SignatureException
 */
public String encodeLicense(final String keyPassPhraseString) throws IOException, NoSuchAlgorithmException,
        NoSuchProviderException, PGPException, SignatureException {

    final char[] keyPassPhrase = keyPassPhraseString.toCharArray();
    final String licensePlain = getLicenseString();
    final ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    final OutputStream out = new ArmoredOutputStream(baOut);

    final PGPPrivateKey pgpPrivKey = key.extractPrivateKey(keyPassPhrase, "BC");
    final PGPSignatureGenerator sGen = new PGPSignatureGenerator(key.getPublicKey().getAlgorithm(),
            hashAlgorithm, "BC");

    sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

    @SuppressWarnings("unchecked")
    final Iterator<String> it = key.getPublicKey().getUserIDs();
    if (it.hasNext()) {
        final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

        spGen.setSignerUserID(false, it.next());
        sGen.setHashedSubpackets(spGen.generate());
    }

    final PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);

    final BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out));

    sGen.generateOnePassVersion(false).encode(bOut);

    final PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
    final OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, "licenseFileName-Ignored", new Date(),
            new byte[1024]);
    final InputStream fIn = new ByteArrayInputStream(licensePlain.getBytes("utf-8"));
    int ch = 0;
    while ((ch = fIn.read()) >= 0) {
        lOut.write(ch);
        sGen.update((byte) ch);
    }
    lGen.close();
    sGen.generate().encode(bOut);
    cGen.close();
    out.close();
    return new String(baOut.toByteArray());
}

From source file:crypttools.PGPCryptoBC.java

License:Open Source License

public String signData(String data, String passphrase) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    InputStream keyInputStream = new ByteArrayInputStream(this.armoredSecretKey);
    PGPSecretKey pgpSecretKey = readSecretKey(keyInputStream);
    PGPPrivateKey pgpPrivateKey = pgpSecretKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passphrase.toCharArray()));
    PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(pgpSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                    .setProvider("BC"));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, pgpPrivateKey);

    @SuppressWarnings("unchecked")
    Iterator<String> it = pgpSecretKey.getPublicKey().getUserIDs();
    if (it.hasNext()) {
        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, it.next());
        signatureGenerator.setHashedSubpackets(spGen.generate());
    }/*from   w w  w  . ja  va  2s . c o m*/
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = new ArmoredOutputStream(byteOutputStream);
    PGPCompressedDataGenerator compressDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);
    BCPGOutputStream bcOutputStream = new BCPGOutputStream(compressDataGenerator.open(outputStream));
    signatureGenerator.generateOnePassVersion(false).encode(bcOutputStream);

    PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
    File fileToSign = File.createTempFile("temp", ".scrap");
    FileUtils.writeStringToFile(fileToSign, data);

    OutputStream literalDataGenOutputStream = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY,
            fileToSign);
    FileInputStream fis = new FileInputStream(fileToSign);
    int ch;
    while ((ch = fis.read()) >= 0) {
        literalDataGenOutputStream.write(ch);
        signatureGenerator.update((byte) ch);
    }

    literalDataGenerator.close();
    fis.close();

    signatureGenerator.generate().encode(bcOutputStream);
    compressDataGenerator.close();
    outputStream.close();

    fileToSign.delete();
    return new String(byteOutputStream.toByteArray(), "UTF-8");
}

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

License:Open Source License

static byte[] compressFile(byte[] data, int algorithm) throws IOException {
    byte[] buffer = new byte[4096];
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm);
    PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
    OutputStream pOut = lData.open(comData.open(bOut), PGPLiteralData.BINARY, "fancyfile", new Date(), buffer);

    //        PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY,
    //            data);
    pOut.write(data);/*  w w  w.jav  a  2s .c om*/
    pOut.close();
    comData.close();
    return bOut.toByteArray();
}

From source file:divconq.pgp.EncryptedFileStream.java

License:Open Source License

public void writeFirstLiteral(int dataLength) {
    // --- data packet ---
    byte[] encName = Utf8Encoder.encode(this.fileName);

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

    // if less than 512 assume this is all there will be, because we cannot stream with numbers smaller than 512 for initial
    if (dataLength < (512 - headerlen)) {
        this.packetsize = dataLength + headerlen;

        this.writeDataPacketLength(this.packetsize);
    } else {//from w  w  w.  j a va  2 s .  co m
        int length = dataLength + headerlen;
        int power = 0;

        for (power = 0; (length != 1) && (power < 16); power++)
            length >>>= 1;

        this.packetsize = 1 << power;

        this.writeDataInternal((byte) (0xE0 | power)); // partial packet length
    }

    byte[] hdr = new byte[headerlen];

    hdr[0] = (byte) PGPLiteralData.BINARY; // data format
    hdr[1] = (byte) encName.length; // file name

    for (int i = 0; i < encName.length; i++)
        hdr[2 + i] = encName[i];

    hdr[headerlen - 4] = (byte) (this.modificationTime >> 24);
    hdr[headerlen - 3] = (byte) (this.modificationTime >> 16);
    hdr[headerlen - 2] = (byte) (this.modificationTime >> 8);
    hdr[headerlen - 1] = (byte) this.modificationTime;

    this.writeDataInternal(hdr, 0, headerlen);

    this.packetpos = headerlen;
}

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

License:Open Source License

public void open(int algorithm, PGPKeyEncryptionMethodGenerator... methods)
        throws IOException, PGPException, IllegalStateException {
    if (methods.length == 0)
        throw new IllegalStateException("no encryption methods specified");

    this.algorithm = algorithm;

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

    // TODO this condition untested and perhaps not helpful, review (PBE - password based encryption)
    if ((methods.length == 1) && (methods[0] instanceof PBEKeyEncryptionMethodGenerator)) {
        PBEKeyEncryptionMethodGenerator m = (PBEKeyEncryptionMethodGenerator) methods[0];

        this.key = m.getKey(algorithm);

        this.writePacket(m.generate(algorithm, null));
    } else {/*from w ww.  j a v  a 2 s  .  c om*/
        this.key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand);

        byte[] sessionInfo = this.createSessionInfo();

        for (int i = 0; i < methods.length; i++) {
            PGPKeyEncryptionMethodGenerator m = (PGPKeyEncryptionMethodGenerator) methods[i];

            this.writePacket(m.generate(algorithm, sessionInfo));
        }
    }

    int packet1 = this.out.writerIndex();

    System.out.println("packet 1: " + packet1 + " final bytes: "
            + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet1 - 5, 5));

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

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

        DefaultJcaJceHelper helper = new DefaultJcaJceHelper();

        this.cipher = helper.createCipher(cName);

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

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

        //
        // we have to add block size + 2 for the generated IV and + 1 + 22 if integrity protected
        //

        this.ensureBuffer(this.cipher.getBlockSize() + 2 + 1 + 22);

        this.startPartialPacket(PacketTags.SYM_ENC_INTEGRITY_PRO); //, this.cipher.getBlockSize() + 2 + 1 + 22);

        this.out.writeByte(1); // version number

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

        this.rand.nextBytes(inLineIv);

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

        // TODO
        byte[] any = this.cipher.update(inLineIv);

        if (any != null)
            this.out.writeBytes(any); // we may include this in digest, TODO review
    } catch (InvalidKeyException e) {
        throw new PGPException("invalid key: " + e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new PGPException("imvalid algorithm parameter: " + e.getMessage(), e);
    } catch (GeneralSecurityException e) {
        throw new PGPException("cannot create cipher: " + e.getMessage(), e);
    }

    int packet2 = this.out.writerIndex();

    System.out.println("packet 2: first bytes: "
            + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet1, 25));
    System.out.println("packet 2: " + packet2 + " final bytes: "
            + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet2 - 5, 5));

    // *******************************************************************
    // TODO compress packet, if any
    // *******************************************************************

    int packet3 = this.out.writerIndex();

    //System.out.println("packet 3: first bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet2, 25));
    //System.out.println("packet 3: " + packet3 + " final bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet3 - 5, 5));

    // *******************************************************************
    // literal packet start
    // *******************************************************************

    this.startPartialPacket(PacketTags.LITERAL_DATA);

    byte[] encName = Utf8Encoder.encode(this.fileName);

    // TODO don't hard code
    int len = 1 + 1 + encName.length + 4 + 99; // type + name length + name + mod time + file content

    //out.writeByte(len);

    this.writeNewPacketLength(len);

    out.writeByte(PGPLiteralData.BINARY);

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

    out.writeBytes(encName);

    long modDate = this.modificationTime / 1000;

    out.writeByte((byte) (modDate >> 24));
    out.writeByte((byte) (modDate >> 16));
    out.writeByte((byte) (modDate >> 8));
    out.writeByte((byte) (modDate));

    int packet4 = this.out.writerIndex();

    System.out.println("packet 4: first bytes: "
            + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet3, 25));
    System.out.println("packet 4: " + packet4 + " final bytes: "
            + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet4 - 5, 5));

    // TODO new SHA1PGPDigestCalculator();
    //if (digestCalc != null)
    //   genOut = new TeeOutputStream(digestCalc.getOutputStream(), genOut);
}

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  w  ww  .  j  av a2  s .  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 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//from  w w  w .j  a va 2s .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 
    // *******************************************************************

    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:dorkbox.util.crypto.CryptoPGP.java

License:Apache License

/**
 * Sign a message using our private PGP key file, with a variety of options
 *///  ww w.  j  a  v  a2 s .  c o m
@SuppressWarnings("Duplicates")
public static byte[] sign(InputStream privateKeyInputStream, String userId, char[] password,
        InputStream message, int signatureType, boolean compressSignature, boolean asciiArmoredOutput,
        boolean includeDataInSignature, boolean generateUserIdSubPacket, boolean generateOnePassVersion)
        throws PGPException {

    List<PGPSecretKey> secretKeys = getSecretKeys(privateKeyInputStream, userId);
    PGPSignatureGenerator signature = createSignature(secretKeys, password, signatureType,
            generateUserIdSubPacket);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = byteArrayOutputStream;
    if (asciiArmoredOutput) {
        outputStream = new ArmoredOutputStream(byteArrayOutputStream);
    }

    PGPCompressedDataGenerator compressedDataGenerator = null;
    BCPGOutputStream bcOutputStream;

    if (compressSignature) {
        compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);
        try {
            bcOutputStream = new BCPGOutputStream(compressedDataGenerator.open(outputStream));
        } catch (IOException e) {
            throw new PGPException("Unable to open compression stream in the signature", e);
        }
    } else {
        bcOutputStream = new BCPGOutputStream(outputStream);
    }

    if (generateOnePassVersion) {
        try {
            signature.generateOnePassVersion(false).encode(bcOutputStream);
        } catch (IOException e) {
            throw new PGPException("Unable to generate OnePass signature header", e);
        }
    }

    PGPLiteralDataGenerator literalDataGenerator = null;
    OutputStream literalDataOutput = null;

    if (includeDataInSignature) {
        literalDataGenerator = new PGPLiteralDataGenerator();
        try {
            literalDataOutput = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY, "_CONSOLE",
                    message.available(), new Date());
        } catch (IOException e1) {
            throw new PGPException("Unable to generate Literal Data signature header", e1);
        }
    }

    try {
        byte[] buffer = new byte[4096];
        int read;

        // update bytes in the streams
        if (literalDataOutput != null) {
            while ((read = message.read(buffer)) > 0) {
                literalDataOutput.write(buffer, 0, read);
                signature.update(buffer, 0, read);
            }
            literalDataOutput.flush();
        } else {

            while ((read = message.read(buffer)) > 0) {
                signature.update(buffer, 0, read);
            }
        }

        // close generators and update signature
        if (literalDataGenerator != null) {
            literalDataGenerator.close();
        }

        signature.generate().encode(bcOutputStream);

        if (compressedDataGenerator != null) {
            compressedDataGenerator.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IO.close(bcOutputStream);
        IO.close(outputStream);
        IO.close(literalDataOutput);
    }

    return byteArrayOutputStream.toByteArray();
}

From source file:dorkbox.util.crypto.CryptoPGP.java

License:Apache License

/**
 * Sign a message using our private PGP key file, with a variety of options
 *//*  w  w  w .ja va 2 s. co  m*/
@SuppressWarnings("Duplicates")
public static byte[] sign(InputStream privateKeyInputStream, String userId, char[] password, File fileMessage,
        int signatureType, boolean compressSignature, boolean asciiArmoredOutput,
        boolean includeDataInSignature, boolean generateUserIdSubPacket, boolean generateOnePassVersion)
        throws PGPException {

    List<PGPSecretKey> secretKeys = getSecretKeys(privateKeyInputStream, userId);
    PGPSignatureGenerator signature = createSignature(secretKeys, password, signatureType,
            generateUserIdSubPacket);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = byteArrayOutputStream;
    if (asciiArmoredOutput) {
        outputStream = new ArmoredOutputStream(byteArrayOutputStream);
    }

    PGPCompressedDataGenerator compressedDataGenerator = null;
    BCPGOutputStream bcOutputStream;

    if (compressSignature) {
        compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);
        try {
            bcOutputStream = new BCPGOutputStream(compressedDataGenerator.open(outputStream));
        } catch (IOException e) {
            throw new PGPException("Unable to open compression stream in the signature", e);
        }
    } else {
        bcOutputStream = new BCPGOutputStream(outputStream);
    }

    if (generateOnePassVersion) {
        try {
            signature.generateOnePassVersion(false).encode(bcOutputStream);
        } catch (IOException e) {
            throw new PGPException("Unable to generate OnePass signature header", e);
        }
    }

    PGPLiteralDataGenerator literalDataGenerator = null;
    OutputStream literalDataOutput = null;

    if (includeDataInSignature) {
        literalDataGenerator = new PGPLiteralDataGenerator();
        try {
            literalDataOutput = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY, fileMessage);
        } catch (IOException e1) {
            throw new PGPException("Unable to generate Literal Data signature header", e1);
        }
    }

    try {
        final FileInputStream fileInputStream = new FileInputStream(fileMessage);

        byte[] buffer = new byte[4096];
        int read;

        // update bytes in the streams
        if (literalDataOutput != null) {
            while ((read = fileInputStream.read(buffer)) > 0) {
                literalDataOutput.write(buffer, 0, read);
                signature.update(buffer, 0, read);
            }
            literalDataOutput.flush();
        } else {

            while ((read = fileInputStream.read(buffer)) > 0) {
                signature.update(buffer, 0, read);
            }
        }

        // close generators and update signature
        if (literalDataGenerator != null) {
            literalDataGenerator.close();
        }

        signature.generate().encode(bcOutputStream);

        if (compressedDataGenerator != null) {
            compressedDataGenerator.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IO.close(bcOutputStream);
        IO.close(outputStream);
        IO.close(literalDataOutput);
    }

    return byteArrayOutputStream.toByteArray();
}