1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2025-12-10 06:11:08 +01:00

Allow encryption and decryption using symmetric passphrases in the main API

This commit is contained in:
Paul Schaub 2020-12-26 19:04:27 +01:00
parent ce4f98423f
commit 7d374f10a7
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311
10 changed files with 303 additions and 84 deletions

View file

@ -116,7 +116,10 @@ public class PGPainless {
*
* @throws IOException IO is dangerous.
* @throws PGPException PGP is brittle.
* @deprecated use {@link #encryptAndOrSign()} instead and provide a passphrase in
* {@link org.pgpainless.encryption_signing.EncryptionBuilderInterface.ToRecipients#forPassphrases(Passphrase...)}.
*/
@Deprecated
public static byte[] encryptWithPassword(@Nonnull byte[] data, @Nonnull Passphrase password, @Nonnull SymmetricKeyAlgorithm algorithm) throws IOException, PGPException {
return SymmetricEncryptorDecryptor.symmetricallyEncrypt(data, password,
algorithm, CompressionAlgorithm.UNCOMPRESSED);
@ -131,7 +134,10 @@ public class PGPainless {
* @return decrypted data.
* @throws IOException IO is dangerous.
* @throws PGPException PGP is brittle.
* @deprecated Use {@link #decryptAndOrVerify()} instead and provide the decryption passphrase in
* {@link org.pgpainless.decryption_verification.DecryptionBuilder.DecryptWith#decryptWith(Passphrase)}.
*/
@Deprecated
public static byte[] decryptWithPassword(@Nonnull byte[] data, @Nonnull Passphrase password) throws IOException, PGPException {
return SymmetricEncryptorDecryptor.symmetricallyDecrypt(data, password);
}

View file

@ -37,12 +37,14 @@ import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator;
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator;
import org.pgpainless.key.OpenPgpV4Fingerprint;
import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.util.Passphrase;
public class DecryptionBuilder implements DecryptionBuilderInterface {
private InputStream inputStream;
private PGPSecretKeyRingCollection decryptionKeys;
private SecretKeyRingProtector decryptionKeyDecryptor;
private Passphrase decryptionPassphrase;
private List<PGPSignature> detachedSignatures;
private Set<PGPPublicKeyRing> verificationKeys = new HashSet<>();
private MissingPublicKeyCallback missingPublicKeyCallback = null;
@ -64,6 +66,15 @@ public class DecryptionBuilder implements DecryptionBuilderInterface {
return new VerifyImpl();
}
@Override
public Verify decryptWith(@Nonnull Passphrase passphrase) {
if (passphrase.isEmpty()) {
throw new IllegalArgumentException("Passphrase MUST NOT be empty.");
}
DecryptionBuilder.this.decryptionPassphrase = passphrase;
return new VerifyImpl();
}
@Override
public Verify doNotDecrypt() {
DecryptionBuilder.this.decryptionKeys = null;
@ -194,7 +205,7 @@ public class DecryptionBuilder implements DecryptionBuilderInterface {
@Override
public DecryptionStream build() throws IOException, PGPException {
return DecryptionStreamFactory.create(inputStream,
decryptionKeys, decryptionKeyDecryptor, detachedSignatures, verificationKeys, missingPublicKeyCallback);
decryptionKeys, decryptionKeyDecryptor, decryptionPassphrase, detachedSignatures, verificationKeys, missingPublicKeyCallback);
}
}
}

View file

@ -31,6 +31,7 @@ import org.bouncycastle.openpgp.PGPSignature;
import org.pgpainless.key.OpenPgpV4Fingerprint;
import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.key.protection.UnprotectedKeysProtector;
import org.pgpainless.util.Passphrase;
public interface DecryptionBuilderInterface {
@ -67,6 +68,15 @@ public interface DecryptionBuilderInterface {
*/
Verify decryptWith(@Nonnull SecretKeyRingProtector decryptor, @Nonnull PGPSecretKeyRingCollection secretKeyRings);
/**
* Decrypt the encrypted data using a passphrase.
* Note: The passphrase MUST NOT be empty.
*
* @param passphrase passphrase
* @return api handle
*/
Verify decryptWith(@Nonnull Passphrase passphrase);
Verify doNotDecrypt();
}

View file

@ -30,12 +30,14 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPOnePassSignature;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPPBEEncryptedData;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
@ -45,15 +47,19 @@ import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator;
import org.bouncycastle.openpgp.operator.PBEDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider;
import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.bc.BcPBEDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider;
import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory;
import org.pgpainless.algorithm.CompressionAlgorithm;
import org.pgpainless.algorithm.SymmetricKeyAlgorithm;
import org.pgpainless.key.OpenPgpV4Fingerprint;
import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.util.Passphrase;
public final class DecryptionStreamFactory {
@ -62,6 +68,7 @@ public final class DecryptionStreamFactory {
private final PGPSecretKeyRingCollection decryptionKeys;
private final SecretKeyRingProtector decryptionKeyDecryptor;
private final Passphrase decryptionPassphrase;
private final Set<PGPPublicKeyRing> verificationKeys = new HashSet<>();
private final MissingPublicKeyCallback missingPublicKeyCallback;
@ -72,10 +79,12 @@ public final class DecryptionStreamFactory {
private DecryptionStreamFactory(@Nullable PGPSecretKeyRingCollection decryptionKeys,
@Nullable SecretKeyRingProtector decryptor,
@Nullable Passphrase decryptionPassphrase,
@Nullable Set<PGPPublicKeyRing> verificationKeys,
@Nullable MissingPublicKeyCallback missingPublicKeyCallback) {
this.decryptionKeys = decryptionKeys;
this.decryptionKeyDecryptor = decryptor;
this.decryptionPassphrase = decryptionPassphrase;
this.verificationKeys.addAll(verificationKeys != null ? verificationKeys : Collections.emptyList());
this.missingPublicKeyCallback = missingPublicKeyCallback;
}
@ -83,13 +92,14 @@ public final class DecryptionStreamFactory {
public static DecryptionStream create(@Nonnull InputStream inputStream,
@Nullable PGPSecretKeyRingCollection decryptionKeys,
@Nullable SecretKeyRingProtector decryptor,
@Nullable Passphrase decryptionPassphrase,
@Nullable List<PGPSignature> detachedSignatures,
@Nullable Set<PGPPublicKeyRing> verificationKeys,
@Nullable MissingPublicKeyCallback missingPublicKeyCallback)
throws IOException, PGPException {
InputStream pgpInputStream;
DecryptionStreamFactory factory = new DecryptionStreamFactory(decryptionKeys, decryptor, verificationKeys,
missingPublicKeyCallback);
DecryptionStreamFactory factory = new DecryptionStreamFactory(decryptionKeys, decryptor,
decryptionPassphrase, verificationKeys, missingPublicKeyCallback);
if (detachedSignatures != null) {
pgpInputStream = inputStream;
@ -171,7 +181,7 @@ public final class DecryptionStreamFactory {
private InputStream decrypt(@Nonnull PGPEncryptedDataList encryptedDataList)
throws PGPException {
Iterator<?> encryptedDataIterator = encryptedDataList.getEncryptedDataObjects();
Iterator<PGPEncryptedData> encryptedDataIterator = encryptedDataList.getEncryptedDataObjects();
if (!encryptedDataIterator.hasNext()) {
throw new PGPException("Decryption failed - EncryptedDataList has no items");
}
@ -179,19 +189,38 @@ public final class DecryptionStreamFactory {
PGPPrivateKey decryptionKey = null;
PGPPublicKeyEncryptedData encryptedSessionKey = null;
while (encryptedDataIterator.hasNext()) {
PGPPublicKeyEncryptedData encryptedData = (PGPPublicKeyEncryptedData) encryptedDataIterator.next();
long keyId = encryptedData.getKeyID();
PGPEncryptedData encryptedData = encryptedDataIterator.next();
resultBuilder.addRecipientKeyId(keyId);
LOGGER.log(LEVEL, "PGPEncryptedData is encrypted for key " + Long.toHexString(keyId));
if (encryptedData instanceof PGPPBEEncryptedData) {
PGPSecretKey secretKey = decryptionKeys.getSecretKey(keyId);
if (secretKey != null) {
LOGGER.log(LEVEL, "Found respective secret key " + Long.toHexString(keyId));
// Watch out! This assignment is possibly done multiple times.
encryptedSessionKey = encryptedData;
decryptionKey = secretKey.extractPrivateKey(decryptionKeyDecryptor.getDecryptor(keyId));
resultBuilder.setDecryptionFingerprint(new OpenPgpV4Fingerprint(secretKey));
PGPPBEEncryptedData pbeEncryptedData = (PGPPBEEncryptedData) encryptedData;
if (decryptionPassphrase != null) {
PBEDataDecryptorFactory passphraseDecryptor = new BcPBEDataDecryptorFactory(
decryptionPassphrase.getChars(), new BcPGPDigestCalculatorProvider());
SymmetricKeyAlgorithm symmetricKeyAlgorithm = SymmetricKeyAlgorithm.fromId(
pbeEncryptedData.getSymmetricAlgorithm(passphraseDecryptor));
resultBuilder.setSymmetricKeyAlgorithm(symmetricKeyAlgorithm);
resultBuilder.setIntegrityProtected(pbeEncryptedData.isIntegrityProtected());
return pbeEncryptedData.getDataStream(passphraseDecryptor);
}
} else if (encryptedData instanceof PGPPublicKeyEncryptedData) {
PGPPublicKeyEncryptedData publicKeyEncryptedData = (PGPPublicKeyEncryptedData) encryptedData;
long keyId = publicKeyEncryptedData.getKeyID();
resultBuilder.addRecipientKeyId(keyId);
LOGGER.log(LEVEL, "PGPEncryptedData is encrypted for key " + Long.toHexString(keyId));
if (decryptionKeys != null) {
PGPSecretKey secretKey = decryptionKeys.getSecretKey(keyId);
if (secretKey != null) {
LOGGER.log(LEVEL, "Found respective secret key " + Long.toHexString(keyId));
// Watch out! This assignment is possibly done multiple times.
encryptedSessionKey = publicKeyEncryptedData;
decryptionKey = secretKey.extractPrivateKey(decryptionKeyDecryptor.getDecryptor(keyId));
resultBuilder.setDecryptionFingerprint(new OpenPgpV4Fingerprint(secretKey));
}
}
}
}
@ -200,6 +229,7 @@ public final class DecryptionStreamFactory {
}
PublicKeyDataDecryptorFactory keyDecryptor = new BcPublicKeyDataDecryptorFactory(decryptionKey);
SymmetricKeyAlgorithm symmetricKeyAlgorithm = SymmetricKeyAlgorithm
.fromId(encryptedSessionKey.getSymmetricAlgorithm(keyDecryptor));

View file

@ -17,8 +17,10 @@ package org.pgpainless.encryption_signing;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@ -49,11 +51,13 @@ import org.pgpainless.key.selection.key.util.And;
import org.pgpainless.key.selection.keyring.PublicKeyRingSelectionStrategy;
import org.pgpainless.key.selection.keyring.SecretKeyRingSelectionStrategy;
import org.pgpainless.util.MultiMap;
import org.pgpainless.util.Passphrase;
public class EncryptionBuilder implements EncryptionBuilderInterface {
private OutputStream outputStream;
private final Set<PGPPublicKey> encryptionKeys = new HashSet<>();
private final Set<Passphrase> encryptionPassphrases = new HashSet<>();
private boolean detachedSignature = false;
private SignatureType signatureType = SignatureType.BINARY_DOCUMENT;
private final Set<PGPSecretKey> signingKeys = new HashSet<>();
@ -73,16 +77,20 @@ public class EncryptionBuilder implements EncryptionBuilderInterface {
@Override
public WithAlgorithms toRecipients(@Nonnull PGPPublicKey... keys) {
for (PGPPublicKey k : keys) {
if (encryptionKeySelector().accept(null, k)) {
EncryptionBuilder.this.encryptionKeys.add(k);
} else {
throw new IllegalArgumentException("Key " + k.getKeyID() + " is not a valid encryption key.");
if (keys.length != 0) {
List<PGPPublicKey> encryptionKeys = new ArrayList<>();
for (PGPPublicKey k : keys) {
if (encryptionKeySelector().accept(null, k)) {
encryptionKeys.add(k);
} else {
throw new IllegalArgumentException("Key " + k.getKeyID() + " is not a valid encryption key.");
}
}
}
if (EncryptionBuilder.this.encryptionKeys.isEmpty()) {
throw new IllegalStateException("No valid encryption keys found!");
if (encryptionKeys.isEmpty()) {
throw new IllegalStateException("No valid encryption keys found!");
}
EncryptionBuilder.this.encryptionKeys.addAll(encryptionKeys);
}
return new WithAlgorithmsImpl();
@ -90,16 +98,19 @@ public class EncryptionBuilder implements EncryptionBuilderInterface {
@Override
public WithAlgorithms toRecipients(@Nonnull PGPPublicKeyRing... keys) {
for (PGPPublicKeyRing ring : keys) {
for (PGPPublicKey k : ring) {
if (encryptionKeySelector().accept(null, k)) {
EncryptionBuilder.this.encryptionKeys.add(k);
if (keys.length != 0) {
List<PGPPublicKey> encryptionKeys = new ArrayList<>();
for (PGPPublicKeyRing ring : keys) {
for (PGPPublicKey k : ring) {
if (encryptionKeySelector().accept(null, k)) {
encryptionKeys.add(k);
}
}
}
}
if (EncryptionBuilder.this.encryptionKeys.isEmpty()) {
throw new IllegalStateException("No valid encryption keys found!");
if (encryptionKeys.isEmpty()) {
throw new IllegalStateException("No valid encryption keys found!");
}
EncryptionBuilder.this.encryptionKeys.addAll(encryptionKeys);
}
return new WithAlgorithmsImpl();
@ -107,18 +118,23 @@ public class EncryptionBuilder implements EncryptionBuilderInterface {
@Override
public WithAlgorithms toRecipients(@Nonnull PGPPublicKeyRingCollection... keys) {
for (PGPPublicKeyRingCollection collection : keys) {
for (PGPPublicKeyRing ring : collection) {
for (PGPPublicKey k : ring) {
if (encryptionKeySelector().accept(null, k)) {
EncryptionBuilder.this.encryptionKeys.add(k);
if (keys.length != 0) {
List<PGPPublicKey> encryptionKeys = new ArrayList<>();
for (PGPPublicKeyRingCollection collection : keys) {
for (PGPPublicKeyRing ring : collection) {
for (PGPPublicKey k : ring) {
if (encryptionKeySelector().accept(null, k)) {
encryptionKeys.add(k);
}
}
}
}
}
if (EncryptionBuilder.this.encryptionKeys.isEmpty()) {
throw new IllegalStateException("No valid encryption keys found!");
if (encryptionKeys.isEmpty()) {
throw new IllegalStateException("No valid encryption keys found!");
}
EncryptionBuilder.this.encryptionKeys.addAll(encryptionKeys);
}
return new WithAlgorithmsImpl();
@ -149,6 +165,19 @@ public class EncryptionBuilder implements EncryptionBuilderInterface {
return new WithAlgorithmsImpl();
}
@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();
}
@Override
public DetachedSign doNotEncrypt() {
return new DetachedSignImpl();
@ -243,6 +272,11 @@ public class EncryptionBuilder implements EncryptionBuilderInterface {
return new DetachedSignImpl();
}
@Override
public ToRecipients and() {
return new ToRecipientsImpl();
}
}
class DetachedSignImpl implements DetachedSign {
@ -379,6 +413,7 @@ public class EncryptionBuilder implements EncryptionBuilderInterface {
return new EncryptionStream(
EncryptionBuilder.this.outputStream,
EncryptionBuilder.this.encryptionKeys,
EncryptionBuilder.this.encryptionPassphrases,
EncryptionBuilder.this.detachedSignature,
signatureType,
privateKeys,

View file

@ -36,6 +36,7 @@ import org.pgpainless.key.protection.UnprotectedKeysProtector;
import org.pgpainless.key.selection.keyring.PublicKeyRingSelectionStrategy;
import org.pgpainless.key.selection.keyring.SecretKeyRingSelectionStrategy;
import org.pgpainless.util.MultiMap;
import org.pgpainless.util.Passphrase;
public interface EncryptionBuilderInterface {
@ -85,6 +86,15 @@ public interface EncryptionBuilderInterface {
<O> WithAlgorithms toRecipients(@Nonnull PublicKeyRingSelectionStrategy<O> selectionStrategy,
@Nonnull MultiMap<O, PGPPublicKeyRingCollection> keys);
/**
* Encrypt to one or more symmetric passphrases.
* Note that the passphrases MUST NOT be empty.
*
* @param passphrases passphrase
* @return api handle
*/
WithAlgorithms forPassphrases(Passphrase... passphrases);
/**
* Instruct the {@link EncryptionStream} to not encrypt any data.
*
@ -150,6 +160,8 @@ public interface EncryptionBuilderInterface {
*/
DetachedSign usingSecureAlgorithms();
ToRecipients and();
}
interface DetachedSign extends SignWith {

View file

@ -37,6 +37,7 @@ import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.operator.bc.BcPBEKeyEncryptionMethodGenerator;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator;
@ -47,6 +48,7 @@ import org.pgpainless.algorithm.SymmetricKeyAlgorithm;
import org.pgpainless.decryption_verification.DetachedSignature;
import org.pgpainless.decryption_verification.OpenPgpMetadata;
import org.pgpainless.key.OpenPgpV4Fingerprint;
import org.pgpainless.util.Passphrase;
/**
* This class is based upon Jens Neuhalfen's Bouncy-GPG PGPEncryptingStream.
@ -63,6 +65,7 @@ public final class EncryptionStream extends OutputStream {
private final HashAlgorithm hashAlgorithm;
private final CompressionAlgorithm compressionAlgorithm;
private final Set<PGPPublicKey> encryptionKeys;
private final Set<Passphrase> encryptionPassphrases;
private final boolean detachedSignature;
private final SignatureType signatureType;
private final Map<OpenPgpV4Fingerprint, PGPPrivateKey> signingKeys;
@ -86,6 +89,7 @@ public final class EncryptionStream extends OutputStream {
EncryptionStream(@Nonnull OutputStream targetOutputStream,
@Nonnull Set<PGPPublicKey> encryptionKeys,
@Nonnull Set<Passphrase> encryptionPassphrases,
boolean detachedSignature,
SignatureType signatureType,
@Nonnull Map<OpenPgpV4Fingerprint, PGPPrivateKey> signingKeys,
@ -99,6 +103,7 @@ public final class EncryptionStream extends OutputStream {
this.hashAlgorithm = hashAlgorithm;
this.compressionAlgorithm = compressionAlgorithm;
this.encryptionKeys = Collections.unmodifiableSet(encryptionKeys);
this.encryptionPassphrases = Collections.unmodifiableSet(encryptionPassphrases);
this.detachedSignature = detachedSignature;
this.signatureType = signatureType;
this.signingKeys = Collections.unmodifiableMap(signingKeys);
@ -126,7 +131,7 @@ public final class EncryptionStream extends OutputStream {
}
private void prepareEncryption() throws IOException, PGPException {
if (encryptionKeys.isEmpty()) {
if (encryptionKeys.isEmpty() && encryptionPassphrases.isEmpty()) {
return;
}
@ -143,6 +148,10 @@ public final class EncryptionStream extends OutputStream {
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key));
}
for (Passphrase passphrase : encryptionPassphrases) {
encryptedDataGenerator.addMethod(new BcPBEKeyEncryptionMethodGenerator(passphrase.getChars()));
}
publicKeyEncryptedStream = encryptedDataGenerator.open(outermostStream, new byte[BUFFER_SIZE]);
outermostStream = publicKeyEncryptedStream;
}