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

472 lines
19 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-05 01:30:58 +02:00
import java.io.IOException;
2018-06-04 19:45:18 +02:00
import java.io.OutputStream;
import java.util.ArrayList;
2018-06-04 19:45:18 +02:00
import java.util.HashSet;
import java.util.Iterator;
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;
2020-08-24 16:26:29 +02:00
import javax.annotation.Nonnull;
2018-06-05 01:30:58 +02:00
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
2018-06-04 19:45:18 +02:00
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor;
import org.pgpainless.algorithm.CompressionAlgorithm;
import org.pgpainless.algorithm.HashAlgorithm;
import org.pgpainless.algorithm.KeyFlag;
2020-12-16 16:33:14 +01:00
import org.pgpainless.algorithm.SignatureType;
import org.pgpainless.algorithm.SymmetricKeyAlgorithm;
import org.pgpainless.decryption_verification.OpenPgpMetadata;
2020-08-24 14:55:06 +02:00
import org.pgpainless.exception.SecretKeyNotFoundException;
import org.pgpainless.key.OpenPgpV4Fingerprint;
import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.util.selection.key.PublicKeySelectionStrategy;
import org.pgpainless.util.selection.key.SecretKeySelectionStrategy;
import org.pgpainless.util.selection.key.impl.EncryptionKeySelectionStrategy;
import org.pgpainless.util.selection.key.impl.NoRevocation;
import org.pgpainless.util.selection.key.impl.SignatureKeySelectionStrategy;
import org.pgpainless.util.selection.key.impl.And;
import org.pgpainless.util.selection.keyring.PublicKeyRingSelectionStrategy;
import org.pgpainless.util.selection.keyring.SecretKeyRingSelectionStrategy;
import org.pgpainless.util.MultiMap;
import org.pgpainless.util.Passphrase;
2018-06-04 19:45:18 +02:00
public class EncryptionBuilder implements EncryptionBuilderInterface {
private final EncryptionStream.Purpose purpose;
2018-06-04 19:45:18 +02:00
private OutputStream outputStream;
private final Set<PGPPublicKey> encryptionKeys = new HashSet<>();
private final Set<Passphrase> encryptionPassphrases = new HashSet<>();
2020-08-24 14:55:06 +02:00
private boolean detachedSignature = false;
2020-12-16 16:33:14 +01:00
private SignatureType signatureType = SignatureType.BINARY_DOCUMENT;
2018-06-04 19:45:18 +02:00
private final Set<PGPSecretKey> signingKeys = new HashSet<>();
2018-06-07 18:12:13 +02:00
private SecretKeyRingProtector signingKeysDecryptor;
2018-06-05 01:30:58 +02:00
private SymmetricKeyAlgorithm symmetricKeyAlgorithm = SymmetricKeyAlgorithm.AES_128;
private HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256;
private CompressionAlgorithm compressionAlgorithm = CompressionAlgorithm.UNCOMPRESSED;
2018-06-04 19:45:18 +02:00
private boolean asciiArmor = false;
private OpenPgpMetadata.FileInfo fileInfo;
2018-06-04 19:45:18 +02:00
public EncryptionBuilder() {
this.purpose = EncryptionStream.Purpose.COMMUNICATIONS;
}
public EncryptionBuilder(@Nonnull EncryptionStream.Purpose purpose) {
this.purpose = purpose;
}
2018-06-04 19:45:18 +02:00
@Override
public ToRecipients onOutputStream(@Nonnull OutputStream outputStream, OpenPgpMetadata.FileInfo fileInfo) {
2018-06-04 19:45:18 +02:00
this.outputStream = outputStream;
this.fileInfo = fileInfo;
2018-06-04 19:45:18 +02:00
return new ToRecipientsImpl();
}
class ToRecipientsImpl implements ToRecipients {
@Override
public WithAlgorithms toRecipients(@Nonnull PGPPublicKey... keys) {
if (keys.length != 0) {
List<PGPPublicKey> encryptionKeys = new ArrayList<>();
for (PGPPublicKey k : keys) {
if (encryptionKeySelector().accept(k)) {
encryptionKeys.add(k);
} else {
throw new IllegalArgumentException("Key " + k.getKeyID() + " is not a valid encryption key.");
}
2018-06-11 01:33:49 +02:00
}
if (encryptionKeys.isEmpty()) {
throw new IllegalArgumentException("No valid encryption keys found!");
}
EncryptionBuilder.this.encryptionKeys.addAll(encryptionKeys);
}
2018-06-04 19:45:18 +02:00
return new WithAlgorithmsImpl();
}
@Override
public WithAlgorithms toRecipients(@Nonnull PGPPublicKeyRing... keys) {
if (keys.length != 0) {
List<PGPPublicKey> encryptionKeys = new ArrayList<>();
for (PGPPublicKeyRing ring : keys) {
for (PGPPublicKey k : ring) {
if (encryptionKeySelector().accept(k)) {
encryptionKeys.add(k);
}
2018-06-04 19:45:18 +02:00
}
}
if (encryptionKeys.isEmpty()) {
throw new IllegalArgumentException("No valid encryption keys found!");
}
EncryptionBuilder.this.encryptionKeys.addAll(encryptionKeys);
}
return new WithAlgorithmsImpl();
}
@Override
public WithAlgorithms toRecipients(@Nonnull PGPPublicKeyRingCollection... keys) {
if (keys.length != 0) {
List<PGPPublicKey> encryptionKeys = new ArrayList<>();
for (PGPPublicKeyRingCollection collection : keys) {
for (PGPPublicKeyRing ring : collection) {
for (PGPPublicKey k : ring) {
if (encryptionKeySelector().accept(k)) {
encryptionKeys.add(k);
}
}
}
}
if (encryptionKeys.isEmpty()) {
throw new IllegalArgumentException("No valid encryption keys found!");
}
EncryptionBuilder.this.encryptionKeys.addAll(encryptionKeys);
}
2018-06-07 18:12:13 +02:00
return new WithAlgorithmsImpl();
2018-06-04 19:45:18 +02:00
}
@Override
public <O> WithAlgorithms toRecipients(@Nonnull PublicKeyRingSelectionStrategy<O> ringSelectionStrategy,
@Nonnull MultiMap<O, PGPPublicKeyRingCollection> keys) {
if (keys.isEmpty()) {
throw new IllegalArgumentException("Recipient map MUST NOT be empty.");
}
2018-06-11 01:33:49 +02:00
MultiMap<O, PGPPublicKeyRing> acceptedKeyRings = ringSelectionStrategy.selectKeyRingsFromCollections(keys);
for (O identifier : acceptedKeyRings.keySet()) {
Set<PGPPublicKeyRing> acceptedSet = acceptedKeyRings.get(identifier);
for (PGPPublicKeyRing ring : acceptedSet) {
for (PGPPublicKey k : ring) {
if (encryptionKeySelector().accept(k)) {
2018-06-11 01:33:49 +02:00
EncryptionBuilder.this.encryptionKeys.add(k);
2018-06-07 18:12:13 +02:00
}
}
}
2018-06-04 19:45:18 +02:00
}
if (EncryptionBuilder.this.encryptionKeys.isEmpty()) {
throw new IllegalArgumentException("No valid encryption keys found!");
}
2018-06-11 01:33:49 +02:00
return new WithAlgorithmsImpl();
2018-06-04 19:45:18 +02:00
}
@Override
public WithAlgorithms forPassphrases(Passphrase... passphrases) {
List<Passphrase> passphraseList = new ArrayList<>();
for (Passphrase passphrase : passphrases) {
if (passphrase.isEmpty()) {
throw new IllegalArgumentException("Passphrase must not be empty.");
}
passphraseList.add(passphrase);
}
EncryptionBuilder.this.encryptionPassphrases.addAll(passphraseList);
return new WithAlgorithmsImpl();
}
2018-06-04 19:45:18 +02:00
@Override
2020-08-24 14:55:06 +02:00
public DetachedSign doNotEncrypt() {
return new DetachedSignImpl();
2018-06-04 19:45:18 +02:00
}
}
class WithAlgorithmsImpl implements WithAlgorithms {
@Override
public WithAlgorithms andToSelf(@Nonnull PGPPublicKey... keys) {
if (keys.length == 0) {
throw new IllegalArgumentException("Recipient list MUST NOT be empty.");
}
2018-06-11 01:33:49 +02:00
for (PGPPublicKey k : keys) {
if (encryptionKeySelector().accept(k)) {
2018-06-11 01:33:49 +02:00
EncryptionBuilder.this.encryptionKeys.add(k);
} else {
throw new IllegalArgumentException("Key " + k.getKeyID() + " is not a valid encryption key.");
}
}
2018-06-07 18:12:13 +02:00
return this;
}
@Override
public WithAlgorithms andToSelf(@Nonnull PGPPublicKeyRing... keys) {
if (keys.length == 0) {
throw new IllegalArgumentException("Recipient list MUST NOT be empty.");
}
for (PGPPublicKeyRing ring : keys) {
2018-06-07 18:12:13 +02:00
for (Iterator<PGPPublicKey> i = ring.getPublicKeys(); i.hasNext(); ) {
PGPPublicKey key = i.next();
if (encryptionKeySelector().accept(key)) {
2018-06-07 18:12:13 +02:00
EncryptionBuilder.this.encryptionKeys.add(key);
}
}
}
2018-06-04 19:45:18 +02:00
return this;
}
2018-07-08 18:05:55 +02:00
@Override
public WithAlgorithms andToSelf(@Nonnull PGPPublicKeyRingCollection keys) {
2018-07-08 18:05:55 +02:00
for (PGPPublicKeyRing ring : keys) {
for (Iterator<PGPPublicKey> i = ring.getPublicKeys(); i.hasNext(); ) {
PGPPublicKey key = i.next();
if (encryptionKeySelector().accept(key)) {
2018-07-08 18:05:55 +02:00
EncryptionBuilder.this.encryptionKeys.add(key);
}
}
}
return this;
}
@Override
public <O> WithAlgorithms andToSelf(@Nonnull PublicKeyRingSelectionStrategy<O> ringSelectionStrategy,
@Nonnull MultiMap<O, PGPPublicKeyRingCollection> keys) {
if (keys.isEmpty()) {
throw new IllegalArgumentException("Recipient list MUST NOT be empty.");
}
2018-06-11 01:33:49 +02:00
MultiMap<O, PGPPublicKeyRing> acceptedKeyRings =
ringSelectionStrategy.selectKeyRingsFromCollections(keys);
2018-06-11 01:33:49 +02:00
for (O identifier : acceptedKeyRings.keySet()) {
Set<PGPPublicKeyRing> acceptedSet = acceptedKeyRings.get(identifier);
for (PGPPublicKeyRing k : acceptedSet) {
for (Iterator<PGPPublicKey> i = k.getPublicKeys(); i.hasNext(); ) {
PGPPublicKey key = i.next();
if (encryptionKeySelector().accept(key)) {
2018-06-11 01:33:49 +02:00
EncryptionBuilder.this.encryptionKeys.add(key);
}
}
}
}
return this;
}
2018-06-04 19:45:18 +02:00
@Override
2020-08-24 14:55:06 +02:00
public DetachedSign usingAlgorithms(@Nonnull SymmetricKeyAlgorithm symmetricKeyAlgorithm,
@Nonnull HashAlgorithm hashAlgorithm,
@Nonnull CompressionAlgorithm compressionAlgorithm) {
2018-06-04 19:45:18 +02:00
EncryptionBuilder.this.symmetricKeyAlgorithm = symmetricKeyAlgorithm;
EncryptionBuilder.this.hashAlgorithm = hashAlgorithm;
EncryptionBuilder.this.compressionAlgorithm = compressionAlgorithm;
2020-08-24 14:55:06 +02:00
return new DetachedSignImpl();
2018-06-04 19:45:18 +02:00
}
@Override
2020-08-24 14:55:06 +02:00
public DetachedSign usingSecureAlgorithms() {
2018-06-07 18:12:13 +02:00
EncryptionBuilder.this.symmetricKeyAlgorithm = SymmetricKeyAlgorithm.AES_256;
EncryptionBuilder.this.hashAlgorithm = HashAlgorithm.SHA512;
EncryptionBuilder.this.compressionAlgorithm = CompressionAlgorithm.UNCOMPRESSED;
2020-08-24 14:55:06 +02:00
return new DetachedSignImpl();
}
@Override
public ToRecipients and() {
return new ToRecipientsImpl();
}
2020-08-24 14:55:06 +02:00
}
class DetachedSignImpl implements DetachedSign {
@Override
public SignWith createDetachedSignature() {
EncryptionBuilder.this.detachedSignature = true;
2018-06-07 18:12:13 +02:00
return new SignWithImpl();
2018-06-04 19:45:18 +02:00
}
2020-08-24 14:55:06 +02:00
@Override
public Armor doNotSign() {
return new ArmorImpl();
}
@Override
2020-12-16 16:33:14 +01:00
public DocumentType signWith(@Nonnull SecretKeyRingProtector decryptor, @Nonnull PGPSecretKey... keys) {
2020-08-24 14:55:06 +02:00
return new SignWithImpl().signWith(decryptor, keys);
}
@Override
2020-12-16 16:33:14 +01:00
public DocumentType signWith(@Nonnull SecretKeyRingProtector decryptor, @Nonnull PGPSecretKeyRing... keyRings) {
2020-08-24 14:55:06 +02:00
return new SignWithImpl().signWith(decryptor, keyRings);
}
@Override
2020-12-16 16:33:14 +01:00
public <O> DocumentType signWith(@Nonnull SecretKeyRingSelectionStrategy<O> selectionStrategy,
@Nonnull SecretKeyRingProtector decryptor,
@Nonnull MultiMap<O, PGPSecretKeyRingCollection> keys)
throws SecretKeyNotFoundException {
2020-08-24 14:55:06 +02:00
return new SignWithImpl().signWith(selectionStrategy, decryptor, keys);
}
2018-06-07 18:12:13 +02:00
}
class SignWithImpl implements SignWith {
2018-06-04 19:45:18 +02:00
@Override
2020-12-16 16:33:14 +01:00
public DocumentType signWith(@Nonnull SecretKeyRingProtector decryptor,
@Nonnull PGPSecretKey... keys) {
if (keys.length == 0) {
throw new IllegalArgumentException("Recipient list MUST NOT be empty.");
}
2018-06-11 01:33:49 +02:00
for (PGPSecretKey s : keys) {
if (EncryptionBuilder.this.signingKeySelector().accept(s)) {
2018-06-11 01:33:49 +02:00
signingKeys.add(s);
} else {
throw new IllegalArgumentException("Key " + s.getKeyID() + " is not a valid signing key.");
}
}
EncryptionBuilder.this.signingKeysDecryptor = decryptor;
2020-12-16 16:33:14 +01:00
return new DocumentTypeImpl();
2018-06-04 19:45:18 +02:00
}
@Override
2020-12-16 16:33:14 +01:00
public DocumentType signWith(@Nonnull SecretKeyRingProtector decryptor,
@Nonnull PGPSecretKeyRing... keys) {
if (keys.length == 0) {
throw new IllegalArgumentException("Recipient list MUST NOT be empty.");
}
2018-06-07 18:12:13 +02:00
for (PGPSecretKeyRing key : keys) {
for (Iterator<PGPSecretKey> i = key.getSecretKeys(); i.hasNext(); ) {
PGPSecretKey s = i.next();
if (EncryptionBuilder.this.signingKeySelector().accept(s)) {
2018-06-07 18:12:13 +02:00
EncryptionBuilder.this.signingKeys.add(s);
2018-06-04 19:45:18 +02:00
}
}
}
2018-06-07 18:12:13 +02:00
EncryptionBuilder.this.signingKeysDecryptor = decryptor;
2020-12-16 16:33:14 +01:00
return new DocumentTypeImpl();
2018-06-04 19:45:18 +02:00
}
@Override
2020-12-16 16:33:14 +01:00
public <O> DocumentType signWith(@Nonnull SecretKeyRingSelectionStrategy<O> ringSelectionStrategy,
@Nonnull SecretKeyRingProtector decryptor,
@Nonnull MultiMap<O, PGPSecretKeyRingCollection> keys) {
if (keys.isEmpty()) {
throw new IllegalArgumentException("Recipient list MUST NOT be empty.");
}
2018-06-11 01:33:49 +02:00
MultiMap<O, PGPSecretKeyRing> acceptedKeyRings =
ringSelectionStrategy.selectKeyRingsFromCollections(keys);
2018-06-11 01:33:49 +02:00
for (O identifier : acceptedKeyRings.keySet()) {
Set<PGPSecretKeyRing> acceptedSet = acceptedKeyRings.get(identifier);
for (PGPSecretKeyRing k : acceptedSet) {
for (Iterator<PGPSecretKey> i = k.getSecretKeys(); i.hasNext(); ) {
PGPSecretKey s = i.next();
if (EncryptionBuilder.this.<O>signingKeySelector().accept(s)) {
2018-06-11 01:33:49 +02:00
EncryptionBuilder.this.signingKeys.add(s);
2018-06-07 18:12:13 +02:00
}
}
}
2018-06-04 19:45:18 +02:00
}
2020-12-16 16:33:14 +01:00
return new DocumentTypeImpl();
}
}
class DocumentTypeImpl implements DocumentType {
@Override
public Armor signBinaryDocument() {
EncryptionBuilder.this.signatureType = SignatureType.BINARY_DOCUMENT;
return new ArmorImpl();
}
@Override
public Armor signCanonicalText() {
EncryptionBuilder.this.signatureType = SignatureType.CANONICAL_TEXT_DOCUMENT;
2018-06-11 01:33:49 +02:00
return new ArmorImpl();
2018-06-04 19:45:18 +02:00
}
}
class ArmorImpl implements Armor {
@Override
public EncryptionStream asciiArmor() throws IOException, PGPException {
2018-06-04 19:45:18 +02:00
EncryptionBuilder.this.asciiArmor = true;
return build();
}
@Override
public EncryptionStream noArmor() throws IOException, PGPException {
2018-06-04 19:45:18 +02:00
EncryptionBuilder.this.asciiArmor = false;
return build();
}
private EncryptionStream build() throws IOException, PGPException {
2018-06-05 01:30:58 +02:00
2020-08-24 14:55:06 +02:00
Map<OpenPgpV4Fingerprint, PGPPrivateKey> privateKeys = new ConcurrentHashMap<>();
2018-06-05 01:30:58 +02:00
for (PGPSecretKey secretKey : signingKeys) {
PBESecretKeyDecryptor decryptor = signingKeysDecryptor.getDecryptor(secretKey.getKeyID());
PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor);
privateKeys.put(new OpenPgpV4Fingerprint(secretKey), privateKey);
2018-06-05 01:30:58 +02:00
}
return new EncryptionStream(
2018-06-04 19:45:18 +02:00
EncryptionBuilder.this.outputStream,
EncryptionBuilder.this.encryptionKeys,
EncryptionBuilder.this.encryptionPassphrases,
2020-08-24 14:55:06 +02:00
EncryptionBuilder.this.detachedSignature,
2020-12-16 16:33:14 +01:00
signatureType,
2018-06-05 01:30:58 +02:00
privateKeys,
2018-06-04 19:45:18 +02:00
EncryptionBuilder.this.symmetricKeyAlgorithm,
EncryptionBuilder.this.hashAlgorithm,
EncryptionBuilder.this.compressionAlgorithm,
EncryptionBuilder.this.asciiArmor,
fileInfo);
2018-06-04 19:45:18 +02:00
}
}
2018-06-11 01:33:49 +02:00
PublicKeySelectionStrategy encryptionKeySelector() {
KeyFlag[] flags = mapPurposeToKeyFlags(purpose);
return new And.PubKeySelectionStrategy(
new NoRevocation.PubKeySelectionStrategy(),
new EncryptionKeySelectionStrategy(flags));
}
SecretKeySelectionStrategy signingKeySelector() {
return new And.SecKeySelectionStrategy(
new NoRevocation.SecKeySelectionStrategy(),
new SignatureKeySelectionStrategy());
}
private static KeyFlag[] mapPurposeToKeyFlags(EncryptionStream.Purpose purpose) {
KeyFlag[] flags;
switch (purpose) {
case COMMUNICATIONS:
flags = new KeyFlag[] {KeyFlag.ENCRYPT_COMMS};
break;
case STORAGE:
flags = new KeyFlag[] {KeyFlag.ENCRYPT_STORAGE};
break;
case STORAGE_AND_COMMUNICATIONS:
flags = new KeyFlag[] {KeyFlag.ENCRYPT_COMMS, KeyFlag.ENCRYPT_STORAGE};
break;
default:
throw new AssertionError("Illegal purpose enum value encountered.");
}
return flags;
2018-06-11 01:33:49 +02:00
}
}