pgpainless/pgpainless-core/src/test/java/org/pgpainless/encryption_signing/EncryptDecryptTest.java

263 lines
12 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.
*/
2020-01-11 13:11:14 +01:00
package org.pgpainless.encryption_signing;
2018-06-07 18:12:13 +02:00
2020-11-13 16:31:59 +01:00
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
2018-06-07 18:12:13 +02:00
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
2018-06-08 15:29:09 +02:00
import java.nio.charset.Charset;
2018-06-10 17:12:44 +02:00
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
2020-08-24 14:55:06 +02:00
import java.util.Collections;
import java.util.Set;
2018-06-10 17:12:44 +02:00
import java.util.logging.Logger;
2018-06-07 18:12:13 +02:00
2020-08-24 14:55:06 +02:00
import org.bouncycastle.bcpg.ArmoredOutputStream;
2018-06-07 18:12:13 +02:00
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
2020-08-24 14:55:06 +02:00
import org.bouncycastle.openpgp.PGPSignature;
2018-06-07 18:12:13 +02:00
import org.bouncycastle.util.io.Streams;
2020-11-13 16:31:59 +01:00
import org.junit.jupiter.api.Test;
2020-01-11 13:11:14 +01:00
import org.pgpainless.PGPainless;
import org.pgpainless.algorithm.KeyFlag;
import org.pgpainless.algorithm.SymmetricKeyAlgorithm;
import org.pgpainless.decryption_verification.DecryptionStream;
import org.pgpainless.decryption_verification.OpenPgpMetadata;
2020-08-24 14:55:06 +02:00
import org.pgpainless.key.OpenPgpV4Fingerprint;
import org.pgpainless.key.TestKeys;
import org.pgpainless.key.collection.PGPKeyRing;
import org.pgpainless.key.generation.KeySpec;
import org.pgpainless.key.generation.type.ElGamal_GENERAL;
2020-11-07 18:24:12 +01:00
import org.pgpainless.key.generation.type.KeyType;
import org.pgpainless.key.generation.type.length.ElGamalLength;
import org.pgpainless.key.generation.type.length.RsaLength;
import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.key.protection.UnprotectedKeysProtector;
import org.pgpainless.util.BCUtil;
2018-06-07 18:12:13 +02:00
public class EncryptDecryptTest {
2018-06-07 18:12:13 +02:00
private static final Logger LOGGER = Logger.getLogger(EncryptDecryptTest.class.getName());
// Don't use StandardCharsets.UTF_8 because of Android API level.
2018-06-10 17:12:44 +02:00
private static final Charset UTF8 = Charset.forName("UTF-8");
2018-06-07 18:12:13 +02:00
private static final String testMessage =
"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.";
2018-06-28 13:23:40 +02:00
@Test
public void freshKeysRsaToElGamalTest()
throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException {
PGPKeyRing sender = PGPainless.generateKeyRing().simpleRsaKeyRing("romeo@montague.lit", RsaLength._3072);
PGPKeyRing recipient = PGPainless.generateKeyRing()
2018-06-28 13:23:40 +02:00
.withSubKey(KeySpec.getBuilder(ElGamal_GENERAL.withLength(ElGamalLength._3072)).withKeyFlags(KeyFlag.ENCRYPT_STORAGE, KeyFlag.ENCRYPT_COMMS).withDefaultAlgorithms())
2020-11-07 18:24:12 +01:00
.withMasterKey(KeySpec.getBuilder(KeyType.RSA(RsaLength._4096)).withKeyFlags(KeyFlag.SIGN_DATA, KeyFlag.CERTIFY_OTHER).withDefaultAlgorithms())
2018-06-28 13:23:40 +02:00
.withPrimaryUserId("juliet@capulet.lit").withoutPassphrase().build();
encryptDecryptForSecretKeyRings(sender, recipient);
}
2018-06-10 17:12:44 +02:00
@Test
public void freshKeysRsaToRsaTest()
throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException {
2020-04-11 11:35:48 +02:00
PGPKeyRing sender = PGPainless.generateKeyRing().simpleRsaKeyRing("romeo@montague.lit", RsaLength._3072);
PGPKeyRing recipient = PGPainless.generateKeyRing().simpleRsaKeyRing("juliet@capulet.lit", RsaLength._3072);
2018-06-10 17:12:44 +02:00
encryptDecryptForSecretKeyRings(sender, recipient);
2018-06-07 18:12:13 +02:00
}
@Test
public void freshKeysEcToEcTest()
throws IOException, PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
PGPKeyRing sender = PGPainless.generateKeyRing().simpleEcKeyRing("romeo@montague.lit");
PGPKeyRing recipient = PGPainless.generateKeyRing().simpleEcKeyRing("juliet@capulet.lit");
2018-06-10 17:12:44 +02:00
encryptDecryptForSecretKeyRings(sender, recipient);
2018-06-07 18:12:13 +02:00
}
@Test
public void freshKeysEcToRsaTest()
throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException {
PGPKeyRing sender = PGPainless.generateKeyRing().simpleEcKeyRing("romeo@montague.lit");
2020-04-11 11:35:48 +02:00
PGPKeyRing recipient = PGPainless.generateKeyRing().simpleRsaKeyRing("juliet@capulet.lit", RsaLength._3072);
2018-06-07 18:12:13 +02:00
encryptDecryptForSecretKeyRings(sender, recipient);
2018-06-10 17:12:44 +02:00
}
2018-06-07 18:12:13 +02:00
2018-06-10 17:12:44 +02:00
@Test
public void freshKeysRsaToEcTest()
throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException {
2020-04-11 11:35:48 +02:00
PGPKeyRing sender = PGPainless.generateKeyRing().simpleRsaKeyRing("romeo@montague.lit", RsaLength._3072);
PGPKeyRing recipient = PGPainless.generateKeyRing().simpleEcKeyRing("juliet@capulet.lit");
2018-06-07 18:12:13 +02:00
encryptDecryptForSecretKeyRings(sender, recipient);
2018-06-10 17:12:44 +02:00
}
2018-06-07 18:12:13 +02:00
@Test
public void existingRsaKeysTest() throws IOException, PGPException {
PGPKeyRing sender = new PGPKeyRing(TestKeys.getJulietPublicKeyRing(), TestKeys.getJulietSecretKeyRing());
PGPKeyRing recipient = new PGPKeyRing(TestKeys.getRomeoPublicKeyRing(), TestKeys.getRomeoSecretKeyRing());
encryptDecryptForSecretKeyRings(sender, recipient);
}
private void encryptDecryptForSecretKeyRings(PGPKeyRing sender, PGPKeyRing recipient)
throws PGPException, IOException {
PGPSecretKeyRing recipientSec = recipient.getSecretKeys();
PGPSecretKeyRing senderSec = sender.getSecretKeys();
PGPPublicKeyRing recipientPub = recipient.getPublicKeys();
PGPPublicKeyRing senderPub = sender.getPublicKeys();
2018-06-07 18:12:13 +02:00
2018-06-10 17:12:44 +02:00
SecretKeyRingProtector keyDecryptor = new UnprotectedKeysProtector();
2018-06-07 18:12:13 +02:00
2018-06-21 15:35:40 +02:00
byte[] secretMessage = testMessage.getBytes(UTF8);
2018-06-07 18:12:13 +02:00
2018-06-10 17:12:44 +02:00
ByteArrayOutputStream envelope = new ByteArrayOutputStream();
2018-06-07 18:12:13 +02:00
EncryptionStream encryptor = PGPainless.createEncryptor()
2018-06-10 17:12:44 +02:00
.onOutputStream(envelope)
2018-06-11 01:33:49 +02:00
.toRecipients(recipientPub)
2018-06-10 17:12:44 +02:00
.usingSecureAlgorithms()
.signWith(keyDecryptor, senderSec)
2018-06-10 17:12:44 +02:00
.noArmor();
2018-06-07 18:12:13 +02:00
Streams.pipeAll(new ByteArrayInputStream(secretMessage), encryptor);
encryptor.close();
byte[] encryptedSecretMessage = envelope.toByteArray();
OpenPgpMetadata encryptionResult = encryptor.getResult();
2020-08-24 14:55:06 +02:00
assertFalse(encryptionResult.getSignatures().isEmpty());
for (OpenPgpV4Fingerprint fingerprint : encryptionResult.getVerifiedSignatures().keySet()) {
assertTrue(BCUtil.keyRingContainsKeyWithId(senderPub, fingerprint.getKeyId()));
}
assertFalse(encryptionResult.getRecipientKeyIds().isEmpty());
for (long keyId : encryptionResult.getRecipientKeyIds()) {
assertTrue(BCUtil.keyRingContainsKeyWithId(recipientPub, keyId));
}
assertEquals(SymmetricKeyAlgorithm.AES_256, encryptionResult.getSymmetricKeyAlgorithm());
2018-06-10 17:12:44 +02:00
// Juliet trieth to comprehend Romeos words
2018-06-07 18:12:13 +02:00
2018-06-10 17:12:44 +02:00
ByteArrayInputStream envelopeIn = new ByteArrayInputStream(encryptedSecretMessage);
2018-06-11 01:33:49 +02:00
DecryptionStream decryptor = PGPainless.createDecryptor()
2018-06-10 17:12:44 +02:00
.onInputStream(envelopeIn)
.decryptWith(keyDecryptor, BCUtil.keyRingsToKeyRingCollection(recipientSec))
2018-07-08 19:31:53 +02:00
.verifyWith(BCUtil.keyRingsToKeyRingCollection(senderPub))
2018-06-07 18:12:13 +02:00
.ignoreMissingPublicKeys()
.build();
2018-06-21 15:35:40 +02:00
ByteArrayOutputStream decryptedSecretMessage = new ByteArrayOutputStream();
2018-06-10 17:12:44 +02:00
Streams.pipeAll(decryptor, decryptedSecretMessage);
2018-06-07 18:12:13 +02:00
decryptor.close();
assertArrayEquals(secretMessage, decryptedSecretMessage.toByteArray());
OpenPgpMetadata result = decryptor.getResult();
assertTrue(result.containsVerifiedSignatureFrom(senderPub));
assertTrue(result.isIntegrityProtected());
assertTrue(result.isSigned());
assertTrue(result.isEncrypted());
assertTrue(result.isVerified());
2018-06-07 18:12:13 +02:00
}
2020-08-24 14:55:06 +02:00
@Test
public void testDetachedSignatureCreationAndVerification() throws IOException, PGPException {
PGPKeyRing signingKeys = new PGPKeyRing(TestKeys.getJulietPublicKeyRing(), TestKeys.getJulietSecretKeyRing());
SecretKeyRingProtector keyRingProtector = new UnprotectedKeysProtector();
byte[] data = testMessage.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
ByteArrayOutputStream dummyOut = new ByteArrayOutputStream();
EncryptionStream signer = PGPainless.createEncryptor().onOutputStream(dummyOut)
.doNotEncrypt()
.createDetachedSignature()
.signWith(keyRingProtector, signingKeys.getSecretKeys())
.noArmor();
Streams.pipeAll(inputStream, signer);
signer.close();
OpenPgpMetadata metadata = signer.getResult();
Set<PGPSignature> signatureSet = metadata.getSignatures();
ByteArrayOutputStream sigOut = new ByteArrayOutputStream();
ArmoredOutputStream armorOut = new ArmoredOutputStream(sigOut);
signatureSet.iterator().next().encode(armorOut);
armorOut.close();
String armorSig = sigOut.toString();
2020-08-24 16:26:29 +02:00
// CHECKSTYLE:OFF
2020-08-24 14:55:06 +02:00
System.out.println(armorSig);
2020-08-24 16:26:29 +02:00
// CHECKSTYLE:ON
2020-08-24 14:55:06 +02:00
inputStream = new ByteArrayInputStream(testMessage.getBytes());
DecryptionStream verifier = PGPainless.createDecryptor().onInputStream(inputStream)
.doNotDecrypt()
.verifyDetachedSignature(new ByteArrayInputStream(armorSig.getBytes()))
.verifyWith(Collections.singleton(signingKeys.getPublicKeys()))
.ignoreMissingPublicKeys()
.build();
dummyOut = new ByteArrayOutputStream();
Streams.pipeAll(verifier, dummyOut);
verifier.close();
metadata = verifier.getResult();
assertFalse(metadata.getVerifiedSignatures().isEmpty());
}
2020-08-30 13:16:47 +02:00
@Test
public void testOnePassSignatureCreationAndVerification() throws IOException, PGPException {
PGPKeyRing signingKeys = new PGPKeyRing(TestKeys.getJulietPublicKeyRing(), TestKeys.getJulietSecretKeyRing());
SecretKeyRingProtector keyRingProtector = new UnprotectedKeysProtector();
byte[] data = testMessage.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
ByteArrayOutputStream signOut = new ByteArrayOutputStream();
EncryptionStream signer = PGPainless.createEncryptor().onOutputStream(signOut)
.doNotEncrypt()
.signWith(keyRingProtector, signingKeys.getSecretKeys())
.asciiArmor();
Streams.pipeAll(inputStream, signer);
signer.close();
// CHECKSTYLE:OFF
System.out.println(signOut.toString());
// CHECKSTYLE:ON
inputStream = new ByteArrayInputStream(signOut.toByteArray());
DecryptionStream verifier = PGPainless.createDecryptor().onInputStream(inputStream)
.doNotDecrypt()
.verifyWith(Collections.singleton(signingKeys.getPublicKeys()))
.ignoreMissingPublicKeys()
.build();
signOut = new ByteArrayOutputStream();
Streams.pipeAll(verifier, signOut);
verifier.close();
OpenPgpMetadata metadata = verifier.getResult();
assertFalse(metadata.getVerifiedSignatures().isEmpty());
}
2018-06-07 18:12:13 +02:00
}