pgpainless/pgpainless-core/src/main/java/org/pgpainless/encryption_signing/EncryptionStream.java

330 lines
13 KiB
Java
Raw Normal View History

/*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pgpainless.encryption_signing;
2018-06-04 19:45:18 +02:00
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
2018-06-05 01:30:58 +02:00
import java.util.Date;
2020-08-24 14:55:06 +02:00
import java.util.Map;
2018-06-04 19:45:18 +02:00
import java.util.Set;
2020-08-24 14:55:06 +02:00
import java.util.concurrent.ConcurrentHashMap;
2018-06-21 15:19:07 +02:00
import java.util.logging.Level;
import java.util.logging.Logger;
2020-08-24 16:26:29 +02:00
import javax.annotation.Nonnull;
2018-06-04 19:45:18 +02:00
2018-06-05 01:30:58 +02:00
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.BCPGOutputStream;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPPrivateKey;
2018-06-04 19:45:18 +02:00
import org.bouncycastle.openpgp.PGPPublicKey;
2018-06-05 01:30:58 +02:00
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
2020-12-27 01:56:18 +01:00
import org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator;
import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator;
2018-06-05 01:30:58 +02:00
import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder;
2020-12-27 01:56:18 +01:00
import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;
import org.pgpainless.algorithm.CompressionAlgorithm;
import org.pgpainless.algorithm.HashAlgorithm;
2020-12-16 16:33:14 +01:00
import org.pgpainless.algorithm.SignatureType;
import org.pgpainless.algorithm.SymmetricKeyAlgorithm;
2020-08-24 14:55:06 +02:00
import org.pgpainless.decryption_verification.DetachedSignature;
import org.pgpainless.decryption_verification.OpenPgpMetadata;
2020-12-27 01:56:18 +01:00
import org.pgpainless.implementation.ImplementationFactory;
2020-08-24 14:55:06 +02:00
import org.pgpainless.key.OpenPgpV4Fingerprint;
import org.pgpainless.util.ArmoredOutputStreamFactory;
import org.pgpainless.util.Passphrase;
2018-06-04 19:45:18 +02:00
2018-06-05 01:30:58 +02:00
/**
* This class is based upon Jens Neuhalfen's Bouncy-GPG PGPEncryptingStream.
* @see <a href="https://github.com/neuhalje/bouncy-gpg/blob/master/src/main/java/name/neuhalfen/projects/crypto/bouncycastle/openpgp/encrypting/PGPEncryptingStream.java">Source</a>
*/
2018-07-02 21:40:59 +02:00
public final class EncryptionStream extends OutputStream {
2018-06-04 19:45:18 +02:00
public enum Purpose {
/**
* The stream will encrypt communication that goes over the wire.
* Eg. EMail, Chat...
*/
COMMUNICATIONS,
/**
* The stream will encrypt data that is stored on disk.
* Eg. Encrypted backup...
*/
STORAGE,
/**
* The stream will use keys with either flags to encrypt the data.
*/
STORAGE_AND_COMMUNICATIONS
}
2018-06-21 15:19:07 +02:00
private static final Logger LOGGER = Logger.getLogger(EncryptionStream.class.getName());
private static final Level LEVEL = Level.FINE;
2018-06-05 01:30:58 +02:00
private static final int BUFFER_SIZE = 1 << 8;
2018-06-04 19:45:18 +02:00
2020-01-10 15:43:22 +01:00
private final SymmetricKeyAlgorithm symmetricKeyAlgorithm;
private final HashAlgorithm hashAlgorithm;
private final CompressionAlgorithm compressionAlgorithm;
private final Set<PGPPublicKey> encryptionKeys;
private final Set<Passphrase> encryptionPassphrases;
2020-08-24 14:55:06 +02:00
private final boolean detachedSignature;
2020-12-16 16:33:14 +01:00
private final SignatureType signatureType;
2020-08-24 14:55:06 +02:00
private final Map<OpenPgpV4Fingerprint, PGPPrivateKey> signingKeys;
2020-01-10 15:43:22 +01:00
private final boolean asciiArmor;
private final OpenPgpMetadata.Builder resultBuilder = OpenPgpMetadata.getBuilder();
2020-08-24 14:55:06 +02:00
private Map<OpenPgpV4Fingerprint, PGPSignatureGenerator> signatureGenerators = new ConcurrentHashMap<>();
2018-06-05 01:30:58 +02:00
private boolean closed = false;
2020-01-10 15:43:22 +01:00
OutputStream outermostStream = null;
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
private ArmoredOutputStream armorOutputStream = null;
2018-06-05 01:30:58 +02:00
private OutputStream publicKeyEncryptedStream = null;
private PGPCompressedDataGenerator compressedDataGenerator;
private BCPGOutputStream basicCompressionStream;
private PGPLiteralDataGenerator literalDataGenerator;
private OutputStream literalDataStream;
EncryptionStream(@Nonnull OutputStream targetOutputStream,
@Nonnull Set<PGPPublicKey> encryptionKeys,
@Nonnull Set<Passphrase> encryptionPassphrases,
2020-08-24 14:55:06 +02:00
boolean detachedSignature,
2020-12-16 16:33:14 +01:00
SignatureType signatureType,
2020-08-24 14:55:06 +02:00
@Nonnull Map<OpenPgpV4Fingerprint, PGPPrivateKey> signingKeys,
@Nonnull SymmetricKeyAlgorithm symmetricKeyAlgorithm,
@Nonnull HashAlgorithm hashAlgorithm,
@Nonnull CompressionAlgorithm compressionAlgorithm,
boolean asciiArmor,
@Nonnull String fileName,
boolean forYourEyesOnly)
2018-06-05 01:30:58 +02:00
throws IOException, PGPException {
2020-01-10 15:43:22 +01:00
this.symmetricKeyAlgorithm = symmetricKeyAlgorithm;
this.hashAlgorithm = hashAlgorithm;
this.compressionAlgorithm = compressionAlgorithm;
this.encryptionKeys = Collections.unmodifiableSet(encryptionKeys);
this.encryptionPassphrases = Collections.unmodifiableSet(encryptionPassphrases);
2020-08-24 14:55:06 +02:00
this.detachedSignature = detachedSignature;
2020-12-16 16:33:14 +01:00
this.signatureType = signatureType;
2020-08-24 14:55:06 +02:00
this.signingKeys = Collections.unmodifiableMap(signingKeys);
2020-01-10 15:43:22 +01:00
this.asciiArmor = asciiArmor;
outermostStream = targetOutputStream;
prepareArmor();
prepareEncryption();
prepareSigning();
prepareCompression();
prepareOnePassSignatures();
prepareLiteralDataProcessing(fileName, forYourEyesOnly);
2020-01-10 15:43:22 +01:00
prepareResultBuilder();
}
private void prepareArmor() {
if (!asciiArmor) {
2018-06-21 15:19:07 +02:00
LOGGER.log(LEVEL, "Encryption output will be binary");
2020-01-10 15:43:22 +01:00
return;
2018-06-05 01:30:58 +02:00
}
2020-01-10 15:43:22 +01:00
LOGGER.log(LEVEL, "Wrap encryption output in ASCII armor");
armorOutputStream = ArmoredOutputStreamFactory.get(outermostStream);
2020-01-10 15:43:22 +01:00
outermostStream = armorOutputStream;
}
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
private void prepareEncryption() throws IOException, PGPException {
if (encryptionKeys.isEmpty() && encryptionPassphrases.isEmpty()) {
2020-01-10 15:43:22 +01:00
return;
}
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
LOGGER.log(LEVEL, "At least one encryption key is available -> encrypt using " + symmetricKeyAlgorithm);
2020-12-27 01:56:18 +01:00
PGPDataEncryptorBuilder dataEncryptorBuilder =
ImplementationFactory.getInstance().getPGPDataEncryptorBuilder(symmetricKeyAlgorithm);
// Simplify once https://github.com/bcgit/bc-java/pull/859 is merged
if (dataEncryptorBuilder instanceof BcPGPDataEncryptorBuilder) {
((BcPGPDataEncryptorBuilder) dataEncryptorBuilder).setWithIntegrityPacket(true);
} else if (dataEncryptorBuilder instanceof JcePGPDataEncryptorBuilder) {
((JcePGPDataEncryptorBuilder) dataEncryptorBuilder).setWithIntegrityPacket(true);
}
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
PGPEncryptedDataGenerator encryptedDataGenerator =
new PGPEncryptedDataGenerator(dataEncryptorBuilder);
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
for (PGPPublicKey key : encryptionKeys) {
LOGGER.log(LEVEL, "Encrypt for key " + Long.toHexString(key.getKeyID()));
2020-12-27 01:56:18 +01:00
PublicKeyKeyEncryptionMethodGenerator keyEncryption =
ImplementationFactory.getInstance().getPublicKeyKeyEncryptionMethodGenerator(key);
encryptedDataGenerator.addMethod(keyEncryption);
2018-06-05 01:30:58 +02:00
}
for (Passphrase passphrase : encryptionPassphrases) {
2020-12-27 01:56:18 +01:00
PBEKeyEncryptionMethodGenerator passphraseEncryption =
ImplementationFactory.getInstance().getPBEKeyEncryptionMethodGenerator(passphrase);
encryptedDataGenerator.addMethod(passphraseEncryption);
}
2020-01-10 15:43:22 +01:00
publicKeyEncryptedStream = encryptedDataGenerator.open(outermostStream, new byte[BUFFER_SIZE]);
outermostStream = publicKeyEncryptedStream;
}
private void prepareSigning() throws PGPException {
if (signingKeys.isEmpty()) {
return;
2018-06-05 01:30:58 +02:00
}
2020-01-10 15:43:22 +01:00
LOGGER.log(LEVEL, "At least one signing key is available -> sign " + hashAlgorithm + " hash of message");
2020-08-24 14:55:06 +02:00
for (OpenPgpV4Fingerprint fingerprint : signingKeys.keySet()) {
PGPPrivateKey privateKey = signingKeys.get(fingerprint);
LOGGER.log(LEVEL, "Sign using key " + fingerprint);
2020-12-27 01:56:18 +01:00
PGPContentSignerBuilder contentSignerBuilder = ImplementationFactory.getInstance()
.getPGPContentSignerBuilder(
privateKey.getPublicKeyPacket().getAlgorithm(),
hashAlgorithm.getAlgorithmId());
2020-01-10 15:43:22 +01:00
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder);
2020-12-16 16:33:14 +01:00
signatureGenerator.init(signatureType.getCode(), privateKey);
2020-08-24 14:55:06 +02:00
signatureGenerators.put(fingerprint, signatureGenerator);
2020-01-10 15:43:22 +01:00
}
}
private void prepareCompression() throws IOException {
2018-06-05 01:30:58 +02:00
compressedDataGenerator = new PGPCompressedDataGenerator(
compressionAlgorithm.getAlgorithmId());
if (compressionAlgorithm == CompressionAlgorithm.UNCOMPRESSED) {
return;
}
LOGGER.log(LEVEL, "Compress using " + compressionAlgorithm);
2020-01-10 15:43:22 +01:00
basicCompressionStream = new BCPGOutputStream(compressedDataGenerator.open(outermostStream));
outermostStream = basicCompressionStream;
2020-01-10 15:43:22 +01:00
}
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
private void prepareOnePassSignatures() throws IOException, PGPException {
2020-08-24 14:55:06 +02:00
for (PGPSignatureGenerator signatureGenerator : signatureGenerators.values()) {
signatureGenerator.generateOnePassVersion(false).encode(outermostStream);
2018-06-05 01:30:58 +02:00
}
2020-01-10 15:43:22 +01:00
}
2018-06-05 01:30:58 +02:00
private void prepareLiteralDataProcessing(@Nonnull String fileName, boolean forYourEyesOnly) throws IOException {
2018-06-05 01:30:58 +02:00
literalDataGenerator = new PGPLiteralDataGenerator();
String name = fileName;
if (forYourEyesOnly) {
name = PGPLiteralData.CONSOLE;
}
literalDataStream = literalDataGenerator.open(outermostStream,
PGPLiteralData.BINARY, name, new Date(), new byte[BUFFER_SIZE]);
outermostStream = literalDataStream;
2020-01-10 15:43:22 +01:00
}
2020-01-10 15:43:22 +01:00
private void prepareResultBuilder() {
for (PGPPublicKey recipient : encryptionKeys) {
resultBuilder.addRecipientKeyId(recipient.getKeyID());
}
resultBuilder.setSymmetricKeyAlgorithm(symmetricKeyAlgorithm);
resultBuilder.setCompressionAlgorithm(compressionAlgorithm);
2018-06-04 19:45:18 +02:00
}
@Override
2018-06-05 01:30:58 +02:00
public void write(int data) throws IOException {
outermostStream.write(data);
2018-06-05 01:30:58 +02:00
2020-08-24 14:55:06 +02:00
for (PGPSignatureGenerator signatureGenerator : signatureGenerators.values()) {
2018-06-05 01:30:58 +02:00
byte asByte = (byte) (data & 0xff);
signatureGenerator.update(asByte);
}
}
@Override
public void write(byte[] buffer) throws IOException {
write(buffer, 0, buffer.length);
}
@Override
public void write(byte[] buffer, int off, int len) throws IOException {
outermostStream.write(buffer, 0, len);
2020-08-24 14:55:06 +02:00
for (PGPSignatureGenerator signatureGenerator : signatureGenerators.values()) {
2018-06-05 01:30:58 +02:00
signatureGenerator.update(buffer, 0, len);
}
}
@Override
public void flush() throws IOException {
outermostStream.flush();
2018-06-05 01:30:58 +02:00
}
@Override
public void close() throws IOException {
2020-01-10 15:43:22 +01:00
if (closed) {
return;
}
2018-06-04 19:45:18 +02:00
2020-01-10 15:43:22 +01:00
// Literal Data
literalDataStream.flush();
literalDataStream.close();
literalDataGenerator.close();
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
writeSignatures();
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
// Compressed Data
compressedDataGenerator.close();
// Public Key Encryption
if (publicKeyEncryptedStream != null) {
publicKeyEncryptedStream.flush();
publicKeyEncryptedStream.close();
}
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
// Armor
if (armorOutputStream != null) {
armorOutputStream.flush();
armorOutputStream.close();
}
closed = true;
}
private void writeSignatures() throws IOException {
2020-08-24 14:55:06 +02:00
for (OpenPgpV4Fingerprint fingerprint : signatureGenerators.keySet()) {
PGPSignatureGenerator signatureGenerator = signatureGenerators.get(fingerprint);
2020-01-10 15:43:22 +01:00
try {
PGPSignature signature = signatureGenerator.generate();
2020-08-24 14:55:06 +02:00
if (!detachedSignature) {
signature.encode(outermostStream);
2020-08-24 14:55:06 +02:00
}
resultBuilder.addDetachedSignature(new DetachedSignature(signature, fingerprint));
2020-01-10 15:43:22 +01:00
} catch (PGPException e) {
throw new IOException(e);
2018-06-05 01:30:58 +02:00
}
}
2018-06-04 19:45:18 +02:00
}
public OpenPgpMetadata getResult() {
if (!closed) {
throw new IllegalStateException("EncryptionStream must be closed before accessing the Result.");
}
return resultBuilder.build();
}
2018-06-04 19:45:18 +02:00
}