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

277 lines
11 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 javax.annotation.Nonnull;
2018-06-04 19:45:18 +02:00
import java.io.IOException;
import java.io.OutputStream;
2018-06-05 01:30:58 +02:00
import java.util.ArrayList;
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.HashSet;
2018-06-05 01:30:58 +02:00
import java.util.List;
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;
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;
2020-08-24 14:55:06 +02:00
import org.bouncycastle.openpgp.PGPSecretKey;
2018-06-05 01:30:58 +02:00
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
2020-08-24 14:55:06 +02:00
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator;
2018-06-05 01:30:58 +02:00
import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator;
import org.pgpainless.algorithm.CompressionAlgorithm;
import org.pgpainless.algorithm.HashAlgorithm;
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-08-24 14:55:06 +02:00
import org.pgpainless.key.OpenPgpV4Fingerprint;
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
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;
2020-08-24 14:55:06 +02:00
private final boolean detachedSignature;
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,
2020-08-24 14:55:06 +02:00
boolean detachedSignature,
@Nonnull Map<OpenPgpV4Fingerprint, PGPPrivateKey> signingKeys,
@Nonnull SymmetricKeyAlgorithm symmetricKeyAlgorithm,
@Nonnull HashAlgorithm hashAlgorithm,
@Nonnull CompressionAlgorithm compressionAlgorithm,
boolean asciiArmor)
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);
2020-08-24 14:55:06 +02:00
this.detachedSignature = detachedSignature;
this.signingKeys = Collections.unmodifiableMap(signingKeys);
2020-01-10 15:43:22 +01:00
this.asciiArmor = asciiArmor;
outermostStream = targetOutputStream;
prepareArmor();
prepareEncryption();
prepareSigning();
prepareCompression();
prepareOnePassSignatures();
prepareLiteralDataProcessing();
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 = new ArmoredOutputStream(outermostStream);
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()) {
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);
BcPGPDataEncryptorBuilder dataEncryptorBuilder =
new BcPGPDataEncryptorBuilder(symmetricKeyAlgorithm.getAlgorithmId());
2018-06-05 01:30:58 +02:00
2020-01-10 15:43:22 +01:00
dataEncryptorBuilder.setWithIntegrityPacket(true);
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()));
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key));
2018-06-05 01:30:58 +02:00
}
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-01-10 15:43:22 +01:00
BcPGPContentSignerBuilder contentSignerBuilder = new BcPGPContentSignerBuilder(
privateKey.getPublicKeyPacket().getAlgorithm(), hashAlgorithm.getAlgorithmId());
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder);
signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, 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-21 15:19:07 +02:00
LOGGER.log(LEVEL, "Compress using " + compressionAlgorithm);
2018-06-05 01:30:58 +02:00
compressedDataGenerator = new PGPCompressedDataGenerator(
compressionAlgorithm.getAlgorithmId());
2020-01-10 15:43:22 +01:00
basicCompressionStream = new BCPGOutputStream(compressedDataGenerator.open(outermostStream));
}
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()) {
2018-06-05 01:30:58 +02:00
signatureGenerator.generateOnePassVersion(false).encode(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 prepareLiteralDataProcessing() throws IOException {
2018-06-05 01:30:58 +02:00
literalDataGenerator = new PGPLiteralDataGenerator();
literalDataStream = literalDataGenerator.open(basicCompressionStream,
PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[BUFFER_SIZE]);
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 {
literalDataStream.write(data);
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 {
literalDataStream.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 {
literalDataStream.flush();
}
@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(basicCompressionStream);
}
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
}