1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2024-06-13 07:04:51 +02:00
pgpainless/pgpainless-core/src/test/java/org/pgpainless/decryption_verification/CleartextSignatureVerificationTest.java

264 lines
12 KiB
Java
Raw Normal View History

2021-10-07 15:48:52 +02:00
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
2021-05-29 14:13:08 +02:00
package org.pgpainless.decryption_verification;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
2021-05-29 14:13:08 +02:00
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignature;
2021-07-31 20:40:31 +02:00
import org.bouncycastle.util.io.Streams;
import org.junit.jupiter.api.Test;
import org.pgpainless.PGPainless;
import org.pgpainless.algorithm.DocumentSignatureType;
import org.pgpainless.decryption_verification.cleartext_signatures.InMemoryMultiPassStrategy;
import org.pgpainless.decryption_verification.cleartext_signatures.MultiPassStrategy;
import org.pgpainless.encryption_signing.EncryptionStream;
import org.pgpainless.encryption_signing.ProducerOptions;
import org.pgpainless.encryption_signing.SigningOptions;
import org.pgpainless.key.TestKeys;
import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.signature.consumer.CertificateValidator;
import org.pgpainless.signature.SignatureUtils;
import org.pgpainless.signature.consumer.SignatureVerifier;
import org.pgpainless.util.ArmorUtils;
2021-05-29 14:13:08 +02:00
import org.pgpainless.util.TestUtils;
public class CleartextSignatureVerificationTest {
public static final byte[] MESSAGE_BODY = ("Ah, Juliet, if the measure of thy joy\n" +
"Be heaped like mine, and that thy skill be more\n" +
"To blazon it, then sweeten with thy breath\n" +
"This neighbor air, and let rich musics tongue\n" +
"Unfold the imagined happiness that both\n" +
"Receive in either by this dear encounter.").getBytes(StandardCharsets.UTF_8);
public static final byte[] MESSAGE_SIGNED = ("-----BEGIN PGP SIGNED MESSAGE-----\n" +
"Hash: SHA512\n" +
"\n" +
"Ah, Juliet, if the measure of thy joy\n" +
"Be heaped like mine, and that thy skill be more\n" +
"To blazon it, then sweeten with thy breath\n" +
"This neighbor air, and let rich musics tongue\n" +
"Unfold the imagined happiness that both\n" +
"Receive in either by this dear encounter.\n" +
"-----BEGIN PGP SIGNATURE-----\n" +
"\n" +
"iHUEARMKAB0WIQRPZlxNwsRmC8ZCXkFXNuaTGs83DAUCYJ/x5gAKCRBXNuaTGs83\n" +
"DFRwAP9/4wMvV3WcX59Clo7mkRce6iwW3VBdiN+yMu3tjmHB2wD/RfE28Q1v4+eo\n" +
"ySNgbyvqYYsNr0fnBwaG3aaj+u5ExiE=\n" +
"=Z2SO\n" +
"-----END PGP SIGNATURE-----").getBytes(StandardCharsets.UTF_8);
public static final byte[] SIGNATURE = ("-----BEGIN PGP SIGNATURE-----\n" +
"\n" +
"iHUEARMKAB0WIQRPZlxNwsRmC8ZCXkFXNuaTGs83DAUCYJ/x5gAKCRBXNuaTGs83\n" +
"DFRwAP9/4wMvV3WcX59Clo7mkRce6iwW3VBdiN+yMu3tjmHB2wD/RfE28Q1v4+eo\n" +
"ySNgbyvqYYsNr0fnBwaG3aaj+u5ExiE=\n" +
"=Z2SO\n" +
"-----END PGP SIGNATURE-----").getBytes(StandardCharsets.UTF_8);
public static final String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public static final Random random = new Random();
@Test
2021-12-28 13:32:50 +01:00
public void cleartextSignVerification_InMemoryMultiPassStrategy()
throws IOException, PGPException {
PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing();
ConsumerOptions options = new ConsumerOptions()
.addVerificationCert(signingKeys);
InMemoryMultiPassStrategy multiPassStrategy = MultiPassStrategy.keepMessageInMemory();
options.setMultiPassStrategy(multiPassStrategy);
DecryptionStream decryptionStream = PGPainless.decryptAndOrVerify()
.onInputStream(new ByteArrayInputStream(MESSAGE_SIGNED))
.withOptions(options);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Streams.pipeAll(decryptionStream, out);
decryptionStream.close();
OpenPgpMetadata result = decryptionStream.getResult();
assertTrue(result.isVerified());
PGPSignature signature = result.getVerifiedSignatures().values().iterator().next();
assertEquals(signature.getKeyID(), signingKeys.getPublicKey().getKeyID());
assertArrayEquals(MESSAGE_BODY, out.toByteArray());
}
2021-05-29 14:13:08 +02:00
@Test
2021-12-28 13:32:50 +01:00
public void cleartextSignVerification_FileBasedMultiPassStrategy()
throws IOException, PGPException {
2021-05-29 14:13:08 +02:00
PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing();
ConsumerOptions options = new ConsumerOptions()
.addVerificationCert(signingKeys);
2021-05-29 14:13:08 +02:00
File tempDir = TestUtils.createTempDirectory();
File file = new File(tempDir, "file");
MultiPassStrategy multiPassStrategy = MultiPassStrategy.writeMessageToFile(file);
options.setMultiPassStrategy(multiPassStrategy);
DecryptionStream decryptionStream = PGPainless.decryptAndOrVerify()
.onInputStream(new ByteArrayInputStream(MESSAGE_SIGNED))
.withOptions(options);
2021-05-29 14:13:08 +02:00
ByteArrayOutputStream out = new ByteArrayOutputStream();
Streams.pipeAll(decryptionStream, out);
decryptionStream.close();
OpenPgpMetadata result = decryptionStream.getResult();
assertTrue(result.isVerified());
PGPSignature signature = result.getVerifiedSignatures().values().iterator().next();
2021-05-29 14:13:08 +02:00
assertEquals(signature.getKeyID(), signingKeys.getPublicKey().getKeyID());
FileInputStream fileIn = new FileInputStream(file);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
2021-07-31 20:40:31 +02:00
Streams.pipeAll(fileIn, bytes);
2021-05-29 14:13:08 +02:00
fileIn.close();
assertArrayEquals(MESSAGE_BODY, bytes.toByteArray());
}
@Test
2021-12-28 13:32:50 +01:00
public void verifySignatureDetached()
throws IOException, PGPException {
PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing();
PGPSignature signature = SignatureUtils.readSignatures(SIGNATURE).get(0);
PGPPublicKey signingKey = signingKeys.getPublicKey(signature.getKeyID());
SignatureVerifier.initializeSignatureAndUpdateWithSignedData(signature, new ByteArrayInputStream(MESSAGE_BODY), signingKey);
CertificateValidator.validateCertificateAndVerifyInitializedSignature(signature, signingKeys, PGPainless.getPolicy());
2021-05-29 14:13:08 +02:00
}
2021-08-26 15:07:48 +02:00
public static void main(String[] args) throws IOException {
// CHECKSTYLE:OFF
PGPPublicKeyRing keys = TestKeys.getEmilPublicKeyRing();
System.out.println(ArmorUtils.toAsciiArmoredString(keys));
System.out.println(new String(MESSAGE_SIGNED));
System.out.println(new String(MESSAGE_BODY));
System.out.println(new String(SIGNATURE));
// CHECKSTYLE:ON
}
@Test
2021-12-28 13:32:50 +01:00
public void testOutputOfSigVerification()
throws IOException, PGPException {
PGPSignature signature = SignatureUtils.readSignatures(SIGNATURE).get(0);
ConsumerOptions options = new ConsumerOptions()
.addVerificationCert(TestKeys.getEmilPublicKeyRing())
.addVerificationOfDetachedSignature(signature);
DecryptionStream decryptionStream = PGPainless.decryptAndOrVerify()
.onInputStream(new ByteArrayInputStream(MESSAGE_BODY))
.withOptions(options);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Streams.pipeAll(decryptionStream, out);
decryptionStream.close();
OpenPgpMetadata metadata = decryptionStream.getResult();
assertEquals(1, metadata.getVerifiedSignatures().size());
}
@Test
2021-12-28 13:32:50 +01:00
public void getDecoderStreamMistakensPlaintextForBase64RegressionTest()
throws PGPException, IOException {
2021-12-28 13:53:25 +01:00
String message = "Foo\nBar"; // PGPUtil.getDecoderStream() would have mistaken this for base64 data
ByteArrayInputStream msgIn = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
PGPSecretKeyRing secretKey = TestKeys.getEmilSecretKeyRing();
ByteArrayOutputStream signedOut = new ByteArrayOutputStream();
EncryptionStream signingStream = PGPainless.encryptAndOrSign().onOutputStream(signedOut)
.withOptions(ProducerOptions.sign(SigningOptions.get()
.addDetachedSignature(SecretKeyRingProtector.unprotectedKeys(), secretKey, DocumentSignatureType.CANONICAL_TEXT_DOCUMENT))
.setCleartextSigned());
Streams.pipeAll(msgIn, signingStream);
signingStream.close();
String signed = signedOut.toString();
ByteArrayInputStream signedIn = new ByteArrayInputStream(signed.getBytes(StandardCharsets.UTF_8));
DecryptionStream verificationStream = PGPainless.decryptAndOrVerify()
.onInputStream(signedIn)
.withOptions(new ConsumerOptions()
.addVerificationCert(TestKeys.getEmilPublicKeyRing()));
ByteArrayOutputStream msgOut = new ByteArrayOutputStream();
Streams.pipeAll(verificationStream, msgOut);
verificationStream.close();
OpenPgpMetadata metadata = verificationStream.getResult();
assertTrue(metadata.isVerified());
}
@Test
2021-12-28 13:32:50 +01:00
public void testDecryptionOfVeryLongClearsignedMessage()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
String message = randomString(28, 4000);
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice");
ByteArrayOutputStream out = new ByteArrayOutputStream();
EncryptionStream encryptionStream = PGPainless.encryptAndOrSign()
.onOutputStream(out)
.withOptions(ProducerOptions.sign(
SigningOptions.get()
.addDetachedSignature(SecretKeyRingProtector.unprotectedKeys(),
secretKeys, DocumentSignatureType.CANONICAL_TEXT_DOCUMENT)
).setCleartextSigned());
Streams.pipeAll(new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)), encryptionStream);
encryptionStream.close();
String cleartextSigned = out.toString();
ByteArrayInputStream in = new ByteArrayInputStream(cleartextSigned.getBytes(StandardCharsets.UTF_8));
DecryptionStream decryptionStream = PGPainless.decryptAndOrVerify()
.onInputStream(in)
.withOptions(new ConsumerOptions()
.addVerificationCert(PGPainless.extractCertificate(secretKeys)));
out = new ByteArrayOutputStream();
Streams.pipeAll(decryptionStream, out);
decryptionStream.close();
}
private String randomString(int maxWordLen, int wordCount) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < wordCount; i++) {
sb.append(randomWord(maxWordLen)).append(' ');
int n = random.nextInt(12);
if (n == 11) {
sb.append('\n');
}
}
return sb.toString();
}
private String randomWord(int maxWordLen) {
int len = random.nextInt(maxWordLen);
char[] word = new char[len];
for (int i = 0; i < word.length; i++) {
word[i] = alphabet.charAt(random.nextInt(alphabet.length()));
}
return new String(word);
}
}