diff --git a/pg/src/main/java/org/bouncycastle/bcpg/OnePassSignaturePacket.java b/pg/src/main/java/org/bouncycastle/bcpg/OnePassSignaturePacket.java index 666fb22465..cf6189fdd4 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/OnePassSignaturePacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/OnePassSignaturePacket.java @@ -1,21 +1,49 @@ package org.bouncycastle.bcpg; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.io.Streams; + import java.io.ByteArrayOutputStream; import java.io.IOException; /** - * generic signature object + * One-Pass-Signature packet. + * OPS packets are used to enable verification of signed messages in one-pass by providing necessary metadata + * about the signed data up front, so the consumer can start processing the signed data without needing + * to process the signature packet at the end of the data stream first. + * + * There are two versions of this packet currently defined. + * Version 3 OPS packets are used with {@link SignaturePacket SignaturePackets} of version 3 and 4. + * Version 6 OPS packets are used with {@link SignaturePacket SignaturePackets} of version 6. + * It is not clear to me, which version of the OPS packet is intended to be used with version 5 signatures. + * + * @see + * Definition of version 3 OPS packets in RFC4880 + * @see + * Definition of version 3 and 6 OPS packets in crypto-refresh + * @see + * Definition of version 3 and 6 OPS packets in librepgp */ public class OnePassSignaturePacket extends ContainedPacket { - private int version; - private int sigType; - private int hashAlgorithm; - private int keyAlgorithm; - private long keyID; - private int isContaining; - + public static final int VERSION_3 = 3; + public static final int VERSION_6 = 6; + + private final int version; + private final int sigType; + private final int hashAlgorithm; + private final int keyAlgorithm; + private final long keyID; + private final byte[] fingerprint; + private final byte[] salt; + private final int isContaining; + + /** + * Parse a {@link OnePassSignaturePacket} from an OpenPGP packet input stream. + * @param in OpenPGP packet input stream + * @throws IOException when the end of stream is prematurely reached, or when the packet is malformed + */ OnePassSignaturePacket( BCPGInputStream in) throws IOException @@ -26,19 +54,59 @@ public class OnePassSignaturePacket sigType = in.read(); hashAlgorithm = in.read(); keyAlgorithm = in.read(); - - keyID |= (long)in.read() << 56; - keyID |= (long)in.read() << 48; - keyID |= (long)in.read() << 40; - keyID |= (long)in.read() << 32; - keyID |= (long)in.read() << 24; - keyID |= (long)in.read() << 16; - keyID |= (long)in.read() << 8; - keyID |= in.read(); - + + if (version == VERSION_3) + { + keyID = StreamUtil.readKeyID(in); + fingerprint = null; + salt = null; + } + else if (version == VERSION_6) + { + int saltLen = in.read(); + if (saltLen < 0) + { + throw new IOException("Version 6 OPS packet has invalid salt length."); + } + salt = new byte[saltLen]; + in.readFully(salt); + + fingerprint = new byte[32]; + in.readFully(fingerprint); + + // TODO: Replace with FingerprintUtil + keyID = ((fingerprint[0] & 0xffL) << 56) | + ((fingerprint[1] & 0xffL) << 48) | + ((fingerprint[2] & 0xffL) << 40) | + ((fingerprint[3] & 0xffL) << 32) | + ((fingerprint[4] & 0xffL) << 24) | + ((fingerprint[5] & 0xffL) << 16) | + ((fingerprint[6] & 0xffL) << 8) | + ((fingerprint[7] & 0xffL)); + } + else + { + Streams.drain(in); + throw new UnsupportedPacketVersionException("Unsupported OnePassSignature packet version encountered: " + version); + } + isContaining = in.read(); } - + + /** + * Create a version 3 {@link OnePassSignaturePacket}. + * Version 3 OPS packets are used with version 3 and version 4 {@link SignaturePacket SignaturePackets}. + * + * To create an OPS packet for use with a version 6 {@link SignaturePacket}, + * see {@link OnePassSignaturePacket#OnePassSignaturePacket(int, int, int, byte[], byte[], boolean)}. + * + * @param sigType signature type + * @param hashAlgorithm hash algorithm tag + * @param keyAlgorithm public key algorithm tag + * @param keyID id of the signing key + * @param isNested if false, there is another OPS packet after this one, which applies to the same data. + * it true, the corresponding signature is calculated also over succeeding additional OPS packets. + */ public OnePassSignaturePacket( int sigType, int hashAlgorithm, @@ -48,14 +116,64 @@ public OnePassSignaturePacket( { super(ONE_PASS_SIGNATURE); - this.version = 3; + this.version = VERSION_3; this.sigType = sigType; this.hashAlgorithm = hashAlgorithm; this.keyAlgorithm = keyAlgorithm; this.keyID = keyID; + this.fingerprint = null; + this.salt = null; this.isContaining = (isNested) ? 0 : 1; } - + + /** + * Create a version 6 {@link OnePassSignaturePacket}. + * + * @param sigType signature type + * @param hashAlgorithm hash algorithm tag + * @param keyAlgorithm public key algorithm tag + * @param salt random salt. The length of this array depends on the hash algorithm in use. + * @param fingerprint 32 octet fingerprint of the (v6) signing key + * @param isNested if false, there is another OPS packet after this one, which applies to the same data. + * it true, the corresponding signature is calculated also over succeeding additional OPS packets. + */ + public OnePassSignaturePacket( + int sigType, + int hashAlgorithm, + int keyAlgorithm, + byte[] salt, + byte[] fingerprint, + boolean isNested) + { + super(ONE_PASS_SIGNATURE); + + this.version = VERSION_6; + this.sigType = sigType; + this.hashAlgorithm = hashAlgorithm; + this.keyAlgorithm = keyAlgorithm; + this.salt = salt; + this.fingerprint = fingerprint; + this.isContaining = (isNested) ? 0 : 1; + // TODO: Replace with FingerprintUtil + keyID = ((fingerprint[0] & 0xffL) << 56) | + ((fingerprint[1] & 0xffL) << 48) | + ((fingerprint[2] & 0xffL) << 40) | + ((fingerprint[3] & 0xffL) << 32) | + ((fingerprint[4] & 0xffL) << 24) | + ((fingerprint[5] & 0xffL) << 16) | + ((fingerprint[6] & 0xffL) << 8) | + ((fingerprint[7] & 0xffL)); + } + + /** + * Return the packet version. + * @return version + */ + public int getVersion() + { + return version; + } + /** * Return the signature type. * @return the signature type @@ -66,7 +184,8 @@ public int getSignatureType() } /** - * return the encryption algorithm tag + * Return the ID of the public key encryption algorithm. + * @return public key algorithm tag */ public int getKeyAlgorithm() { @@ -74,7 +193,8 @@ public int getKeyAlgorithm() } /** - * return the hashAlgorithm tag + * Return the algorithm ID of the hash algorithm. + * @return hash algorithm tag */ public int getHashAlgorithm() { @@ -82,16 +202,37 @@ public int getHashAlgorithm() } /** - * @return long + * Return the key-id of the signing key. + * @return key id */ public long getKeyID() { return keyID; } + /** + * Return the version 6 fingerprint of the issuer. + * Only for version 6 packets. + * @return 32 bytes issuer fingerprint + */ + public byte[] getFingerprint() + { + return Arrays.clone(fingerprint); + } + + /** + * Return the salt used in the signature. + * Only for version 6 packets. + * @return salt + */ + public byte[] getSalt() + { + return Arrays.clone(salt); + } + /** * Return true, if the signature contains any signatures that follow. - * An bracketing OPS is followed by additional OPS packets and is calculated over all the data between itself + * A bracketing OPS is followed by additional OPS packets and is calculated over all the data between itself * and its corresponding signature (it is an attestation for encapsulated signatures). * * @return true if encapsulating, false otherwise @@ -102,7 +243,9 @@ public boolean isContaining() } /** - * + * Encode the contents of this packet into the given packet output stream. + * + * @param out OpenPGP packet output stream */ public void encode( BCPGOutputStream out) @@ -116,7 +259,16 @@ public void encode( pOut.write(hashAlgorithm); pOut.write(keyAlgorithm); - StreamUtil.writeKeyID(pOut, keyID); + if (version == VERSION_3) + { + StreamUtil.writeKeyID(pOut, keyID); + } + else if (version == VERSION_6) + { + pOut.write(salt.length); + pOut.write(salt); + pOut.write(fingerprint); + } pOut.write(isContaining); diff --git a/pg/src/main/java/org/bouncycastle/bcpg/SignaturePacket.java b/pg/src/main/java/org/bouncycastle/bcpg/SignaturePacket.java index f2b7c2aa95..52bb39e959 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/SignaturePacket.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/SignaturePacket.java @@ -19,7 +19,7 @@ public class SignaturePacket public static final int VERSION_2 = 2; public static final int VERSION_3 = 3; public static final int VERSION_4 = 4; // https://datatracker.ietf.org/doc/rfc4880/ - public static final int VERSION_5 = 5; // https://datatracker.ietf.org/doc/draft-koch-openpgp-2015-rfc4880bis/ + public static final int VERSION_5 = 5; // https://datatracker.ietf.org/doc/draft-koch-librepgp/ public static final int VERSION_6 = 6; // https://datatracker.ietf.org/doc/draft-ietf-openpgp-crypto-refresh/ private int version; @@ -33,6 +33,7 @@ public class SignaturePacket private SignatureSubpacket[] hashedData; private SignatureSubpacket[] unhashedData; private byte[] signatureEncoding; + private byte[] salt; // v6 only SignaturePacket( BCPGInputStream in) @@ -41,147 +42,265 @@ public class SignaturePacket super(SIGNATURE); version = in.read(); - - if (version == VERSION_3 || version == VERSION_2) + switch (version) { - int l = in.read(); - - signatureType = in.read(); - creationTime = (((long)in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read()) * 1000; - - keyID = StreamUtil.readKeyID(in); - keyAlgorithm = in.read(); - hashAlgorithm = in.read(); + case VERSION_2: + case VERSION_3: + parseV2_V3(in); + break; + case VERSION_4: + case VERSION_5: + parseV4_V5(in); + break; + case VERSION_6: + parseV6(in); + break; + default: + Streams.drain(in); + throw new UnsupportedPacketVersionException("unsupported version: " + version); } - else if (version == VERSION_4) - { - signatureType = in.read(); - keyAlgorithm = in.read(); - hashAlgorithm = in.read(); + } - int hashedLength = (in.read() << 8) | in.read(); - byte[] hashed = new byte[hashedLength]; + /** + * Parse a version 2 or version 3 signature. + * @param in input stream which already skipped over the version number + * @throws IOException if the packet is malformed + * + * @see + * Version 3 packet format + */ + private void parseV2_V3(BCPGInputStream in) + throws IOException + { + int l = in.read(); // length l MUST be 5 - in.readFully(hashed); + signatureType = in.read(); + creationTime = StreamUtil.readTime(in); - // - // read the signature sub packet data. - // - SignatureSubpacket sub; - SignatureSubpacketInputStream sIn = new SignatureSubpacketInputStream( - new ByteArrayInputStream(hashed)); + keyID = StreamUtil.readKeyID(in); + keyAlgorithm = in.read(); + hashAlgorithm = in.read(); - Vector v = new Vector(); - while ((sub = sIn.readPacket()) != null) - { - v.addElement(sub); - } + // left 16 bits of the signed hash value + fingerPrint = new byte[2]; + in.readFully(fingerPrint); - hashedData = new SignatureSubpacket[v.size()]; + parseSignature(in); + } - for (int i = 0; i != hashedData.length; i++) - { - SignatureSubpacket p = (SignatureSubpacket)v.elementAt(i); - if (p instanceof IssuerKeyID) - { - keyID = ((IssuerKeyID)p).getKeyID(); - } - else if (p instanceof SignatureCreationTime) - { - creationTime = ((SignatureCreationTime)p).getTime().getTime(); - } + /** + * Parse a version 4 or version 5 signature. + * The difference between version 4 and 5 is that a version 5 signature contains additional metadata. + * @param in input stream which already skipped over the version number + * @throws IOException if the packet is malformed + * + * @see + * Version 4 packet format + * @see + * Version 5 packet format + */ + private void parseV4_V5(BCPGInputStream in) + throws IOException + { + signatureType = in.read(); + keyAlgorithm = in.read(); + hashAlgorithm = in.read(); - hashedData[i] = p; - } + parseSubpackets(in); - int unhashedLength = (in.read() << 8) | in.read(); - byte[] unhashed = new byte[unhashedLength]; + // left 16 bits of the signed hash value + fingerPrint = new byte[2]; + in.readFully(fingerPrint); - in.readFully(unhashed); + parseSignature(in); + } + + /** + * Parse a version 6 signature. + * Version 6 signatures do use 4 octet subpacket area length descriptors and contain an additional salt value + * (which may or may not be of size 0, librepgp and crypto-refresh are in disagreement here). + * @param in input stream which already skipped over the version number + * @throws IOException if the packet is malformed + * + * @see + * Version 6 packet format + */ + private void parseV6(BCPGInputStream in) + throws IOException + { + signatureType = in.read(); + keyAlgorithm = in.read(); + hashAlgorithm = in.read(); - sIn = new SignatureSubpacketInputStream( - new ByteArrayInputStream(unhashed)); + parseSubpackets(in); - v.removeAllElements(); - while ((sub = sIn.readPacket()) != null) - { - v.addElement(sub); - } + // left 16 bits of the signed hash value + fingerPrint = new byte[2]; + in.readFully(fingerPrint); - unhashedData = new SignatureSubpacket[v.size()]; + int saltSize = in.read(); + salt = new byte[saltSize]; + in.readFully(salt); - for (int i = 0; i != unhashedData.length; i++) - { - SignatureSubpacket p = (SignatureSubpacket)v.elementAt(i); - if (p instanceof IssuerKeyID) - { - keyID = ((IssuerKeyID)p).getKeyID(); - } + parseSignature(in); + } - unhashedData[i] = p; - } + /** + * Parse the hashed and unhashed signature subpacket areas of the signature. + * Version 4 and 5 signature encode the area length using 2 octets, while version 6 uses 4 octet lengths instead. + * + * @param in input stream which skipped to after the hash algorithm octet + * @throws IOException if the packet is malformed + */ + private void parseSubpackets(BCPGInputStream in) + throws IOException + { + int hashedLength; + if (version == 6) + { + hashedLength = StreamUtil.read4OctetLength(in); } else { - Streams.drain(in); + hashedLength = StreamUtil.read2OctetLength(in); + } + byte[] hashed = new byte[hashedLength]; - throw new UnsupportedPacketVersionException("unsupported version: " + version); + in.readFully(hashed); + + // + // read the signature sub packet data. + // + SignatureSubpacket sub; + SignatureSubpacketInputStream sIn = new SignatureSubpacketInputStream( + new ByteArrayInputStream(hashed)); + + Vector vec = new Vector(); + while ((sub = sIn.readPacket()) != null) + { + vec.addElement(sub); } - fingerPrint = new byte[2]; - in.readFully(fingerPrint); + hashedData = new SignatureSubpacket[vec.size()]; - switch (keyAlgorithm) + for (int i = 0; i != hashedData.length; i++) { - case RSA_GENERAL: - case RSA_SIGN: - MPInteger v = new MPInteger(in); - - signature = new MPInteger[1]; - signature[0] = v; - break; - case DSA: - MPInteger r = new MPInteger(in); - MPInteger s = new MPInteger(in); - - signature = new MPInteger[2]; - signature[0] = r; - signature[1] = s; - break; - case ELGAMAL_ENCRYPT: // yep, this really does happen sometimes. - case ELGAMAL_GENERAL: - MPInteger p = new MPInteger(in); - MPInteger g = new MPInteger(in); - MPInteger y = new MPInteger(in); - - signature = new MPInteger[3]; - signature[0] = p; - signature[1] = g; - signature[2] = y; - break; - case ECDSA: - case EDDSA_LEGACY: - case Ed448: - case Ed25519: - case X448: - case X25519: - MPInteger ecR = new MPInteger(in); - MPInteger ecS = new MPInteger(in); - - signature = new MPInteger[2]; - signature[0] = ecR; - signature[1] = ecS; - break; - default: - if (keyAlgorithm >= PublicKeyAlgorithmTags.EXPERIMENTAL_1 && keyAlgorithm <= PublicKeyAlgorithmTags.EXPERIMENTAL_11) + SignatureSubpacket p = vec.elementAt(i); + if (p instanceof IssuerKeyID) { - signature = null; - signatureEncoding = Streams.readAll(in); + keyID = ((IssuerKeyID)p).getKeyID(); } - else + else if (p instanceof SignatureCreationTime) { - throw new IOException("unknown signature key algorithm: " + keyAlgorithm); + creationTime = ((SignatureCreationTime)p).getTime().getTime(); } + + hashedData[i] = p; + } + + int unhashedLength; + if (version == VERSION_6) + { + unhashedLength = StreamUtil.read4OctetLength(in); + } + else + { + unhashedLength = StreamUtil.read2OctetLength(in); + } + byte[] unhashed = new byte[unhashedLength]; + + in.readFully(unhashed); + + sIn = new SignatureSubpacketInputStream( + new ByteArrayInputStream(unhashed)); + + vec.removeAllElements(); + while ((sub = sIn.readPacket()) != null) + { + vec.addElement(sub); + } + + unhashedData = new SignatureSubpacket[vec.size()]; + + for (int i = 0; i != unhashedData.length; i++) + { + SignatureSubpacket p = vec.elementAt(i); + if (p instanceof IssuerKeyID) + { + keyID = ((IssuerKeyID)p).getKeyID(); + } + + unhashedData[i] = p; + } + } + + /** + * Parse the algorithm-specific signature encoding. + * Ed25519 and Ed448 do not populate the signature MPInteger field, but instead read the raw signature to + * signatureEncoding directly. + * + * @param in input stream which skipped the head of the signature + * @throws IOException if the packet is malformed + */ + private void parseSignature(BCPGInputStream in) + throws IOException + { + switch (keyAlgorithm) + { + case RSA_GENERAL: + case RSA_SIGN: + MPInteger v = new MPInteger(in); + + signature = new MPInteger[1]; + signature[0] = v; + break; + case DSA: + MPInteger r = new MPInteger(in); + MPInteger s = new MPInteger(in); + + signature = new MPInteger[2]; + signature[0] = r; + signature[1] = s; + break; + case ELGAMAL_ENCRYPT: // yep, this really does happen sometimes. + case ELGAMAL_GENERAL: + MPInteger p = new MPInteger(in); + MPInteger g = new MPInteger(in); + MPInteger y = new MPInteger(in); + + signature = new MPInteger[3]; + signature[0] = p; + signature[1] = g; + signature[2] = y; + break; + case Ed448: + signatureEncoding = new byte[org.bouncycastle.math.ec.rfc8032.Ed448.SIGNATURE_SIZE]; + in.readFully(signatureEncoding); + break; + case Ed25519: + signatureEncoding = new byte[org.bouncycastle.math.ec.rfc8032.Ed25519.SIGNATURE_SIZE]; + in.readFully(signatureEncoding); + break; + case ECDSA: + case EDDSA_LEGACY: + + MPInteger ecR = new MPInteger(in); + MPInteger ecS = new MPInteger(in); + + signature = new MPInteger[2]; + signature[0] = ecR; + signature[1] = ecS; + break; + default: + if (keyAlgorithm >= PublicKeyAlgorithmTags.EXPERIMENTAL_1 && keyAlgorithm <= PublicKeyAlgorithmTags.EXPERIMENTAL_11) + { + signature = null; + signatureEncoding = Streams.readAll(in); + } + else + { + throw new IOException("unknown signature key algorithm: " + keyAlgorithm); + } } } @@ -262,6 +381,34 @@ public SignaturePacket( } } + public SignaturePacket( + int version, + int signatureType, + long keyID, + int keyAlgorithm, + int hashAlgorithm, + SignatureSubpacket[] hashedData, + SignatureSubpacket[] unhashedData, + byte[] fingerPrint, + byte[] signatureEncoding) + { + super(SIGNATURE); + + this.version = version; + this.signatureType = signatureType; + this.keyID = keyID; + this.keyAlgorithm = keyAlgorithm; + this.hashAlgorithm = hashAlgorithm; + this.hashedData = hashedData; + this.unhashedData = unhashedData; + this.fingerPrint = fingerPrint; + this.signatureEncoding = Arrays.clone(signatureEncoding); + if (hashedData != null) + { + setCreationTime(); + } + } + /** * get the version number */ @@ -296,6 +443,16 @@ public byte[] getFingerPrint() return Arrays.clone(fingerPrint); } + /** + * Return the signature's salt. + * Only for v6 signatures. + * @return salt + */ + public byte[] getSalt() + { + return salt; + } + /** * return the signature trailer that must be included with the data * to reconstruct the signature @@ -338,19 +495,14 @@ public byte[] getSignatureTrailer() } byte[] data = hOut.toByteArray(); - - sOut.write((byte)(data.length >> 8)); - sOut.write((byte)data.length); + StreamUtil.write2OctetLength(sOut, data.length); sOut.write(data); byte[] hData = sOut.toByteArray(); sOut.write((byte)this.getVersion()); sOut.write((byte)0xff); - sOut.write((byte)(hData.length>> 24)); - sOut.write((byte)(hData.length >> 16)); - sOut.write((byte)(hData.length >> 8)); - sOut.write((byte)(hData.length)); + StreamUtil.write4OctetLength(sOut, hData.length); } catch (IOException e) { @@ -382,6 +534,8 @@ public int getHashAlgorithm() /** * return the signature as a set of integers - note this is normalised to be the * ASN.1 encoding of what appears in the signature packet. + * Note, that Ed25519 and Ed448 returns null, as the raw signature is stored in signatureEncoding only. + * For those, use {@link #getSignatureBytes()} instead. */ public MPInteger[] getSignature() { @@ -447,7 +601,7 @@ public void encode( pOut.write(version); - if (version == 3 || version == 2) + if (version == VERSION_3 || version == VERSION_2) { pOut.write(5); // the length of the next block @@ -461,7 +615,7 @@ public void encode( pOut.write(keyAlgorithm); pOut.write(hashAlgorithm); } - else if (version == 4) + else if (version == VERSION_4 || version == VERSION_5 || version == VERSION_6) { pOut.write(signatureType); pOut.write(keyAlgorithm); @@ -476,8 +630,14 @@ else if (version == 4) byte[] data = sOut.toByteArray(); - pOut.write(data.length >> 8); - pOut.write(data.length); + if (version == VERSION_6) + { + StreamUtil.write4OctetLength(pOut, data.length); + } + else + { + StreamUtil.write2OctetLength(pOut, data.length); + } pOut.write(data); sOut.reset(); @@ -489,8 +649,14 @@ else if (version == 4) data = sOut.toByteArray(); - pOut.write(data.length >> 8); - pOut.write(data.length); + if (version == VERSION_6) + { + StreamUtil.write4OctetLength(pOut, data.length); + } + else + { + StreamUtil.write2OctetLength(pOut, data.length); + } pOut.write(data); } else @@ -500,6 +666,12 @@ else if (version == 4) pOut.write(fingerPrint); + if (version == VERSION_6) + { + pOut.write(salt.length); + pOut.write(salt); + } + if (signature != null) { for (int i = 0; i != signature.length; i++) diff --git a/pg/src/main/java/org/bouncycastle/bcpg/StreamUtil.java b/pg/src/main/java/org/bouncycastle/bcpg/StreamUtil.java index 3d6456cd48..c91961cce0 100644 --- a/pg/src/main/java/org/bouncycastle/bcpg/StreamUtil.java +++ b/pg/src/main/java/org/bouncycastle/bcpg/StreamUtil.java @@ -115,5 +115,38 @@ static void writeTime(BCPGOutputStream pOut, long time) pOut.write((byte)time); } + static long readTime(BCPGInputStream in) + throws IOException + { + return (((long)in.read() << 24) | ((long) in.read() << 16) | ((long) in.read() << 8) | in.read()) * 1000; + } + + static void write2OctetLength(OutputStream pOut, int len) + throws IOException + { + pOut.write(len >> 8); + pOut.write(len); + } + + static int read2OctetLength(InputStream in) + throws IOException + { + return (in.read() << 8) | in.read(); + } + + static void write4OctetLength(OutputStream pOut, int len) + throws IOException + { + pOut.write(len >> 24); + pOut.write(len >> 16); + pOut.write(len >> 8); + pOut.write(len); + } + + static int read4OctetLength(InputStream in) + throws IOException + { + return (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); + } } diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPOnePassSignature.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPOnePassSignature.java index 629677c697..5f6aa5f853 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPOnePassSignature.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPOnePassSignature.java @@ -88,11 +88,47 @@ public boolean verify( return verifier.verify(pgpSig.getSignature()); } + /** + * Return the packet version. + * + * @return packet version + */ + public int getVersion() + { + return sigPack.getVersion(); + } + + /** + * Return the key-ID of the issuer signing key. + * For {@link OnePassSignaturePacket#VERSION_6} packets, the key-ID is derived from the fingerprint. + * + * @return key-ID + */ public long getKeyID() { return sigPack.getKeyID(); } + /** + * Return the issuer key fingerprint. + * Only for {@link OnePassSignaturePacket#VERSION_6} packets. + * @return fingerprint + */ + public byte[] getFingerprint() + { + return sigPack.getFingerprint(); + } + + /** + * Return the salt used in the corresponding signature. + * Only for {@link OnePassSignaturePacket#VERSION_6} packets. + * @return salt + */ + public byte[] getSalt() + { + return sigPack.getSalt(); + } + public int getSignatureType() { return sigPack.getSignatureType(); diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignature.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignature.java index 03c3fb67a9..8428d0efd6 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignature.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignature.java @@ -19,7 +19,6 @@ import org.bouncycastle.bcpg.SignatureSubpacket; import org.bouncycastle.bcpg.TrustPacket; import org.bouncycastle.math.ec.rfc8032.Ed25519; -import org.bouncycastle.math.ec.rfc8032.Ed448; import org.bouncycastle.openpgp.operator.PGPContentVerifier; import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilder; import org.bouncycastle.openpgp.operator.PGPContentVerifierBuilderProvider; @@ -451,8 +450,7 @@ public byte[] getSignature() { signature = BigIntegers.asUnsignedByteArray(sigValues[0].getValue()); } - else if (getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY || - getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed25519) + else if (getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY) { byte[] a = BigIntegers.asUnsignedByteArray(sigValues[0].getValue()); byte[] b = BigIntegers.asUnsignedByteArray(sigValues[1].getValue()); @@ -460,14 +458,6 @@ else if (getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY || System.arraycopy(a, 0, signature, Ed25519.PUBLIC_KEY_SIZE - a.length, a.length); System.arraycopy(b, 0, signature, Ed25519.SIGNATURE_SIZE - b.length, b.length); } - else if (getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed448) - { - byte[] a = BigIntegers.asUnsignedByteArray(sigValues[0].getValue()); - byte[] b = BigIntegers.asUnsignedByteArray(sigValues[1].getValue()); - signature = new byte[Ed448.SIGNATURE_SIZE]; - System.arraycopy(a, 0, signature, Ed448.PUBLIC_KEY_SIZE - a.length, a.length); - System.arraycopy(b, 0, signature, Ed448.SIGNATURE_SIZE - b.length, b.length); - } else { try diff --git a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureGenerator.java b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureGenerator.java index f38f80537b..3f34aaac27 100644 --- a/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureGenerator.java +++ b/pg/src/main/java/org/bouncycastle/openpgp/PGPSignatureGenerator.java @@ -178,9 +178,7 @@ public PGPSignature generate() sigValues = new MPInteger[1]; sigValues[0] = new MPInteger(new BigInteger(1, contentSigner.getSignature())); } - else if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY || - contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed25519 || - contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed448) + else if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY) { byte[] enc = contentSigner.getSignature(); sigValues = new MPInteger[]{ @@ -188,6 +186,12 @@ else if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY new MPInteger(new BigInteger(1, Arrays.copyOfRange(enc, enc.length / 2, enc.length))) }; } + else if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed25519 || + contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.Ed448) + { + // Contrary to EDDSA_LEGACY, the new PK algorithms Ed25519, Ed448 do not use MPI encoding + sigValues = null; + } else { sigValues = PGPUtil.dsaSigToMpi(contentSigner.getSignature()); @@ -199,7 +203,17 @@ else if (contentSigner.getKeyAlgorithm() == PublicKeyAlgorithmTags.EDDSA_LEGACY fingerPrint[0] = digest[0]; fingerPrint[1] = digest[1]; - return new PGPSignature(new SignaturePacket(sigType, contentSigner.getKeyID(), contentSigner.getKeyAlgorithm(), contentSigner.getHashAlgorithm(), hPkts, unhPkts, fingerPrint, sigValues)); + if (sigValues != null) + { + return new PGPSignature(new SignaturePacket(sigType, contentSigner.getKeyID(), contentSigner.getKeyAlgorithm(), + contentSigner.getHashAlgorithm(), hPkts, unhPkts, fingerPrint, sigValues)); + } + else + { + // Ed25519, Ed448 use raw encoding instead of MPI + return new PGPSignature(new SignaturePacket(4, sigType, contentSigner.getKeyID(), contentSigner.getKeyAlgorithm(), + contentSigner.getHashAlgorithm(), hPkts, unhPkts, fingerPrint, contentSigner.getSignature())); + } } /** diff --git a/pg/src/test/java/org/bouncycastle/bcpg/HexDumpUtil.java b/pg/src/test/java/org/bouncycastle/bcpg/HexDumpUtil.java new file mode 100644 index 0000000000..62d70b43a1 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/HexDumpUtil.java @@ -0,0 +1,94 @@ +package org.bouncycastle.bcpg; + +import org.bouncycastle.util.encoders.Hex; + +import java.io.IOException; + +public class HexDumpUtil +{ + + /** + * Return a formatted hex dump of the given byte array. + * @param array byte array + */ + public static String hexdump(byte[] array) + { + return hexdump(0, array); + } + + /** + * Return a formatted hex dump of the given byte array. + * If startIndent is non-zero, the dump is shifted right by startIndent octets. + * @param startIndent shift the octet stream between by a number of bytes + * @param array byte array + */ + public static String hexdump(int startIndent, byte[] array) + { + if (startIndent < 0) + { + throw new IllegalArgumentException("Start-Indent must be a positive number"); + } + if (array == null) + { + return ""; + } + String hex = Hex.toHexString(array); + StringBuilder withWhiteSpace = new StringBuilder(); + // shift the dump a number of octets to the right + for (int i = 0; i < startIndent; i++) + { + withWhiteSpace.append(" "); + } + // Split into hex octets (pairs of two chars) + String[] octets = withWhiteSpace.append(hex).toString().split("(?<=\\G.{2})"); + + StringBuilder out = new StringBuilder(); + int l = 0; + while (l < octets.length) + { + // index row + out.append(String.format("%08X", l)).append(" "); + // first 8 octets of a line + for (int i = l ; i < l + 8 && i < octets.length; i++) + { + out.append(octets[i]).append(" "); + } + out.append(" "); + // second 8 octets of a line + for (int i = l+8; i < l + 16 && i < octets.length; i++) + { + out.append(octets[i]).append(" "); + } + out.append("\n"); + + l += 16; + } + return out.toString(); + } + + /** + * Return a formatted hex dump of the packet encoding of the given packet. + * @param packet packet + * @return formatted hex dump + * @throws IOException if an exception happens during packet encoding + */ + public static String hexdump(ContainedPacket packet) + throws IOException + { + return hexdump(packet.getEncoded()); + } + + /** + * Return a formatted hex dump of the packet encoding of the given packet. + * If startIndent is non-zero, the hex dump is shifted right by the startIndent octets. + * @param startIndent shift the encodings octet stream by a number of bytes + * @param packet packet + * @return formatted hex dump + * @throws IOException if an exception happens during packet encoding + */ + public static String hexdump(int startIndent, ContainedPacket packet) + throws IOException + { + return hexdump(startIndent, packet.getEncoded()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/AbstractPacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/AbstractPacketTest.java new file mode 100644 index 0000000000..2e89f71ef4 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/AbstractPacketTest.java @@ -0,0 +1,133 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.ContainedPacket; +import org.bouncycastle.bcpg.HexDumpUtil; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.test.SimpleTest; + +import java.io.IOException; + +public abstract class AbstractPacketTest + extends SimpleTest +{ + + /** + * Test, whether the first byte array and the second byte array are identical. + * If a mismatch is detected, a formatted hex dump of both arrays is printed to stdout. + * @param first first array + * @param second second array + */ + public void isEncodingEqual(byte[] first, byte[] second) + { + isEncodingEqual(null, first, second); + } + + /** + * Test, whether the first byte array and the second byte array are identical. + * If a mismatch is detected, a formatted hex dump of both arrays is printed to stdout. + * @param message error message to prepend to the hex dump + * @param first first array + * @param second second array + */ + public void isEncodingEqual(String message, byte[] first, byte[] second) + { + StringBuilder sb = new StringBuilder(); + if (message != null) + { + sb.append(message).append("\n"); + } + sb.append("Expected: \n").append(HexDumpUtil.hexdump(first)).append("\n"); + sb.append("Got: \n").append(HexDumpUtil.hexdump(second)); + + isTrue(sb.toString(), first == second || Arrays.areEqual(first, second)); + } + + /** + * Test, whether the encoding of the first and second packet are identical. + * If a mismatch is detected, a formatted hex dump of both packet encodings is printed to stdout. + * @param first first packet + * @param second second packet + */ + public void isEncodingEqual(ContainedPacket first, ContainedPacket second) + throws IOException + { + isEncodingEqual(null, first, second); + } + + /** + * Test, whether the encoding of the first and second packet are identical. + * If a mismatch is detected, a formatted hex dump of both packet encodings is printed to stdout. + * @param message error message to prepend to the hex dump + * @param first first packet + * @param second second packet + */ + public void isEncodingEqual(String message, ContainedPacket first, ContainedPacket second) + throws IOException + { + StringBuilder sb = new StringBuilder(); + if (message != null) + { + sb.append(message).append("\n"); + } + sb.append("Expected: \n").append(HexDumpUtil.hexdump(first)).append("\n"); + sb.append("Got: \n").append(HexDumpUtil.hexdump(second)); + isTrue(sb.toString(), first == second || Arrays.areEqual(first.getEncoded(), second.getEncoded())); + } + + /** + * Test, whether the value is false. + * @param value value + */ + public void isFalse(boolean value) + { + isFalse("Value is not false.", value); + } + + /** + * Test, whether the value is false. + * @param message custom error message + * @param value value + */ + public void isFalse(String message, boolean value) + { + isTrue(message, !value); + } + + /** + * Test, whether the value is null. + * @param value value + */ + public void isNull(Object value) + { + isNull("Value is not null.", value); + } + + /** + * Test, whether the value is null. + * @param message custom error message + * @param value value + */ + public void isNull(String message, Object value) + { + isTrue(message, value == null); + } + + /** + * Test, whether the value is not null. + * @param value value + */ + public void isNotNull(Object value) + { + isNotNull("Value is not null.", value); + } + + /** + * Test, whether the value is not null. + * @param message custom error message + * @param value value + */ + public void isNotNull(String message, Object value) + { + isTrue(message, value != null); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/AllTests.java b/pg/src/test/java/org/bouncycastle/bcpg/test/AllTests.java new file mode 100644 index 0000000000..47dbc11c62 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/AllTests.java @@ -0,0 +1,72 @@ +package org.bouncycastle.bcpg.test; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.test.PrintTestResult; +import org.bouncycastle.util.test.SimpleTestResult; + +import java.security.Security; + +public class AllTests + extends TestCase +{ + + public void testPacketParsing() + { + Security.addProvider(new BouncyCastleProvider()); + + org.bouncycastle.util.test.Test[] tests = new org.bouncycastle.util.test.Test[] + { + new SignaturePacketTest(), + new OnePassSignaturePacketTest(), + new OpenPgpMessageTest() + }; + + for (int i = 0; i != tests.length; i++) + { + SimpleTestResult result = (SimpleTestResult)tests[i].perform(); + + if (!result.isSuccessful()) + { + fail(result.toString()); + } + } + } + + + public static void main(String[] args) + { + PrintTestResult.printResult(junit.textui.TestRunner.run(suite())); + } + + public static Test suite() + { + TestSuite suite = new TestSuite("OpenPGP Packet Tests"); + + suite.addTestSuite(AllTests.class); + + return new BCPacketTests(suite); + } + + static class BCPacketTests + extends TestSetup + { + public BCPacketTests(Test test) + { + super(test); + } + + protected void setUp() + { + Security.addProvider(new BouncyCastleProvider()); + } + + protected void tearDown() + { + Security.removeProvider("BC"); + } + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/OnePassSignaturePacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/OnePassSignaturePacketTest.java new file mode 100644 index 0000000000..9f26357554 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/OnePassSignaturePacketTest.java @@ -0,0 +1,298 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.*; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.util.encoders.Hex; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.SecureRandom; + +public class OnePassSignaturePacketTest + extends AbstractPacketTest +{ + + // Parse v6 OPS packet and compare its values to a known-good test vector + private void testParseV6OnePassSignaturePacket() + throws IOException + { + // Version 6 OnePassSignature packet + // extracted from https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#name-sample-inline-signed-messag + byte[] encOPS = Hex.decode("c44606010a1b2076495f50218890f7f5e2ee3c1822514f70500f551d86e5c921e404e34a53fbaccb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc901"); + // Issuer of the message + byte[] issuerFp = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + // Salt used to generate the signature + byte[] salt = Hex.decode("76495F50218890F7F5E2EE3C1822514F70500F551D86E5C921E404E34A53FBAC"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encOPS); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + // Parse and compare the OnePassSignature packet + OnePassSignaturePacket ops = (OnePassSignaturePacket) pIn.readPacket(); + isEquals("OPS packet MUST be of version 6", + OnePassSignaturePacket.VERSION_6, ops.getVersion()); + isEncodingEqual("OPS packet issuer fingerprint mismatch", + issuerFp, ops.getFingerprint()); + isTrue("OPS packet key-ID mismatch", + // key-ID are the first 8 octets of the fingerprint + Hex.toHexString(issuerFp).startsWith(Long.toHexString(ops.getKeyID()))); + isEncodingEqual("OPS packet salt mismatch", + salt, ops.getSalt()); + isTrue("OPS packet isContaining mismatch", + ops.isContaining()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, true); + ops.encode(pOut); + pOut.close(); + + isEncodingEqual("OPS Packet encoding mismatch", encOPS, bOut.toByteArray()); + } + + private void roundtripV3Packet() + throws IOException + { + OnePassSignaturePacket before = new OnePassSignaturePacket( + PGPSignature.BINARY_DOCUMENT, + HashAlgorithmTags.SHA256, + PublicKeyAlgorithmTags.RSA_GENERAL, + 123L, + true); + + isEquals("Expected OPS version 3", + OnePassSignaturePacket.VERSION_3, before.getVersion()); + isEquals("Signature type mismatch", + PGPSignature.BINARY_DOCUMENT, before.getSignatureType()); + isEquals("Hash Algorithm mismatch", + HashAlgorithmTags.SHA256, before.getHashAlgorithm()); + isEquals("Pulic Key Algorithm mismatch", + PublicKeyAlgorithmTags.RSA_GENERAL, before.getKeyAlgorithm()); + isEquals("Key-ID mismatch", + 123L, before.getKeyID()); + isFalse("OPS is expected to be non-containing", + before.isContaining()); + isNull("OPS v3 MUST NOT have a fingerprint", + before.getFingerprint()); + isNull("OPS v3 MUST NOT have salt", + before.getSalt()); + + for (boolean newTypeIdFormat : new boolean[] {true, false}) + { + // round-trip the packet by encoding and decoding it + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, newTypeIdFormat); + before.encode(pOut); + pOut.close(); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + OnePassSignaturePacket after = (OnePassSignaturePacket) pIn.readPacket(); + + isEquals("round-tripped OPS version mismatch", + before.getVersion(), after.getVersion()); + isEquals("round-tripped OPS signature type mismatch", + before.getSignatureType(), after.getSignatureType()); + isEquals("round-tripped OPS hash algorithm mismatch", + before.getHashAlgorithm(), after.getHashAlgorithm()); + isEquals("round-tripped OPS public key algorithm mismatch", + before.getKeyAlgorithm(), after.getKeyAlgorithm()); + isEquals("round-tripped OPS key-id mismatch", + before.getKeyID(), after.getKeyID()); + isEquals("round-tripped OPS nested flag mismatch", + before.isContaining(), after.isContaining()); + isNull("round-tripped OPS v3 MUST NOT have fingerprint", + after.getFingerprint()); + isNull("round-tripped OPS v3 MUST NOT have salt", + after.getSalt()); + + isEncodingEqual("Packet encoding mismatch", + before, after); + } + } + + private void roundtripV6Packet() + throws IOException + { + byte[] salt = new byte[32]; + byte[] fingerprint = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + long keyID = ((fingerprint[0] & 0xffL) << 56) | + ((fingerprint[1] & 0xffL) << 48) | + ((fingerprint[2] & 0xffL) << 40) | + ((fingerprint[3] & 0xffL) << 32) | + ((fingerprint[4] & 0xffL) << 24) | + ((fingerprint[5] & 0xffL) << 16) | + ((fingerprint[6] & 0xffL) << 8) | + ((fingerprint[7] & 0xffL)); + + new SecureRandom().nextBytes(salt); + OnePassSignaturePacket before = new OnePassSignaturePacket( + PGPSignature.CANONICAL_TEXT_DOCUMENT, + HashAlgorithmTags.SHA512, + PublicKeyAlgorithmTags.EDDSA_LEGACY, + salt, + fingerprint, + false); + + isEquals("Expected OPS version 6", + OnePassSignaturePacket.VERSION_6, before.getVersion()); + isEquals("Signature type mismatch", + PGPSignature.CANONICAL_TEXT_DOCUMENT, before.getSignatureType()); + isEquals("Hash algorithm mismatch", + HashAlgorithmTags.SHA512, before.getHashAlgorithm()); + isEquals("Public key algorithm mismatch", + PublicKeyAlgorithmTags.EDDSA_LEGACY, before.getKeyAlgorithm()); + isEncodingEqual("Salt mismatch", + salt, before.getSalt()); + isEncodingEqual("Fingerprint mismatch", + fingerprint, before.getFingerprint()); + isEquals("Derived key-ID mismatch", + keyID, before.getKeyID()); + isTrue("non-nested OPS is expected to be containing", + before.isContaining()); + + for (boolean newTypeIdFormat : new boolean[] {true, false}) + { + // round-trip the packet by encoding and decoding it + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, newTypeIdFormat); + before.encode(pOut); + pOut.close(); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + OnePassSignaturePacket after = (OnePassSignaturePacket) pIn.readPacket(); + + isEquals("round-tripped OPS version mismatch", + before.getVersion(), after.getVersion()); + isEquals("round-tripped OPS signature type mismatch", + before.getSignatureType(), after.getSignatureType()); + isEquals("round-tripped OPS hash algorithm mismatch", + before.getHashAlgorithm(), after.getHashAlgorithm()); + isEquals("round-tripped OPS public key algorithm mismatch", + before.getKeyAlgorithm(), after.getKeyAlgorithm()); + isEquals("round-tripped OPS key-id mismatch", + before.getKeyID(), after.getKeyID()); + isEquals("round-tripped OPS nested flag mismatch", + before.isContaining(), after.isContaining()); + isEncodingEqual("round-tripped OPS fingerprint mismatch", + before.getFingerprint(), after.getFingerprint()); + isEncodingEqual("round-tripped OPS salt mismatch", + before.getSalt(), after.getSalt()); + + isEncodingEqual(before, after); + } + } + + private void roundtripV6PacketWithZeroLengthSalt() + throws IOException + { + byte[] salt = new byte[0]; + byte[] fingerprint = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + + OnePassSignaturePacket before = new OnePassSignaturePacket( + PGPSignature.CANONICAL_TEXT_DOCUMENT, + HashAlgorithmTags.SHA512, + PublicKeyAlgorithmTags.EDDSA_LEGACY, + salt, + fingerprint, + false); + + isEncodingEqual("Salt mismatch", + salt, before.getSalt()); + + for (boolean newTypeIdFormat : new boolean[] {true, false}) + { + // round-trip the packet by encoding and decoding it + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, newTypeIdFormat); + before.encode(pOut); + pOut.close(); + ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); + BCPGInputStream pIn = new BCPGInputStream(bIn); + OnePassSignaturePacket after = (OnePassSignaturePacket) pIn.readPacket(); + + isEquals("round-tripped OPS version mismatch", + before.getVersion(), after.getVersion()); + isEquals("round-tripped OPS signature type mismatch", + before.getSignatureType(), after.getSignatureType()); + isEquals("round-tripped OPS hash algorithm mismatch", + before.getHashAlgorithm(), after.getHashAlgorithm()); + isEquals("round-tripped OPS public key algorithm mismatch", + before.getKeyAlgorithm(), after.getKeyAlgorithm()); + isEquals("round-tripped OPS key-id mismatch", + before.getKeyID(), after.getKeyID()); + isEquals("round-tripped OPS nested flag mismatch", + before.isContaining(), after.isContaining()); + isEncodingEqual("round-tripped OPS fingerprint mismatch", + before.getFingerprint(), after.getFingerprint()); + isEncodingEqual("round-tripped OPS salt mismatch", + before.getSalt(), after.getSalt()); + } + } + + private void parsingOfPacketWithUnknownVersionFails() + { + // Version 0x99 OnePassSignature packet + byte[] encOPS = Hex.decode("c44699010a1b2076495f50218890f7f5e2ee3c1822514f70500f551d86e5c921e404e34a53fbaccb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc901"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encOPS); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + try + { + pIn.readPacket(); + fail("Expected UnsupportedPacketVersionException"); + } + catch (IOException e) + { + fail("Expected UnsupportedPacketVersionException", e); + } + catch (UnsupportedPacketVersionException e) + { + // expected + } + } + + private void parsingOfPacketWithTruncatedFingerprintFails() + { + // Version 6 OnePassSignature packet with truncated fingerprint field (20 bytes instead of 32) + // This error would happen, if a v6 OPS packet was generated with a v4 fingerprint. + // extracted from https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#name-sample-inline-signed-messag + byte[] encOPS = Hex.decode("c44606010a1b2076495f50218890f7f5e2ee3c1822514f70500f551d86e5c921e404e34a53fbaccb186c4f0609a697e4d52dfa6c722b0c1f1e27c101"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encOPS); + BCPGInputStream pIn = new BCPGInputStream(bIn); + + try + { + pIn.readPacket(); + fail("Expected IOException"); + } + catch (IOException e) + { + // expected + } + } + + @Override + public String getName() + { + return "OnePassSignaturePacketTest"; + } + + @Override + public void performTest() + throws Exception + { + testParseV6OnePassSignaturePacket(); + roundtripV3Packet(); + roundtripV6Packet(); + parsingOfPacketWithUnknownVersionFails(); + parsingOfPacketWithTruncatedFingerprintFails(); + roundtripV6PacketWithZeroLengthSalt(); + } + + public static void main(String[] args) + { + runTest(new OnePassSignaturePacketTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/OpenPgpMessageTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/OpenPgpMessageTest.java new file mode 100644 index 0000000000..8bad1dcb36 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/OpenPgpMessageTest.java @@ -0,0 +1,177 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.*; +import org.bouncycastle.bcpg.sig.IssuerFingerprint; +import org.bouncycastle.bcpg.sig.SignatureCreationTime; +import org.bouncycastle.openpgp.PGPLiteralData; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.util.Arrays; +import org.bouncycastle.util.encoders.Hex; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +public class OpenPgpMessageTest + extends AbstractPacketTest +{ + + /* + Inline-signed message using a version 6 signature + see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#name-sample-inline-signed-messag + */ + public static final String INLINE_SIGNED = "-----BEGIN PGP MESSAGE-----\n" + + "\n" + + "xEYGAQobIHZJX1AhiJD39eLuPBgiUU9wUA9VHYblySHkBONKU/usyxhsTwYJppfk\n" + + "1S36bHIrDB8eJ8GKVnCPZSXsJ7rZrMkBy0p1AAAAAABXaGF0IHdlIG5lZWQgZnJv\n" + + "bSB0aGUgZ3JvY2VyeSBzdG9yZToKCi0gdG9mdQotIHZlZ2V0YWJsZXMKLSBub29k\n" + + "bGVzCsKYBgEbCgAAACkFgmOYo2MiIQbLGGxPBgmml+TVLfpscisMHx4nwYpWcI9l\n" + + "JewnutmsyQAAAABpNiB2SV9QIYiQ9/Xi7jwYIlFPcFAPVR2G5ckh5ATjSlP7rCfQ\n" + + "b7gKqPxbyxbhljGygHQPnqau1eBzrQD5QVplPEDnemrnfmkrpx0GmhCfokxYz9jj\n" + + "FtCgazStmsuOXF9SFQE=\n" + + "-----END PGP MESSAGE-----"; + + /* + Cleartext-signed message using a version 6 signature + see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#name-sample-cleartext-signed-mes + */ + public static final String CLEARTEXT_SIGNED = "-----BEGIN PGP SIGNED MESSAGE-----\n" + + "\n" + + "What we need from the grocery store:\n" + + "\n" + + "- - tofu\n" + + "- - vegetables\n" + + "- - noodles\n" + + "\n" + + "-----BEGIN PGP SIGNATURE-----\n" + + "\n" + + "wpgGARsKAAAAKQWCY5ijYyIhBssYbE8GCaaX5NUt+mxyKwwfHifBilZwj2Ul7Ce6\n" + + "2azJAAAAAGk2IHZJX1AhiJD39eLuPBgiUU9wUA9VHYblySHkBONKU/usJ9BvuAqo\n" + + "/FvLFuGWMbKAdA+epq7V4HOtAPlBWmU8QOd6aud+aSunHQaaEJ+iTFjP2OMW0KBr\n" + + "NK2ay45cX1IVAQ==\n" + + "-----END PGP SIGNATURE-----"; + + // Content of the message's LiteralData packet + public static final String CONTENT = "What we need from the grocery store:\n" + + "\n" + + "- tofu\n" + + "- vegetables\n" + + "- noodles\n"; + // Issuer of the message + public static byte[] ISSUER = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + // Salt used to generate the signature + public static byte[] SALT = Hex.decode("76495F50218890F7F5E2EE3C1822514F70500F551D86E5C921E404E34A53FBAC"); + + + private void testParseV6CleartextSignedMessage() + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(CLEARTEXT_SIGNED.getBytes(StandardCharsets.UTF_8)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + + isNull("The ASCII armored input stream MUST NOT hallucinate headers where there are non", + aIn.getArmorHeaders()); // We do not have any header lines after the armor header + + // Parse and compare literal data + ByteArrayOutputStream litOut = new ByteArrayOutputStream(); + while (aIn.isClearText()) + { + litOut.write(aIn.read()); + } + String c = litOut.toString(); + isEquals("Mismatching content of the cleartext-signed test message", + CONTENT, c.substring(0, c.length() - 2)); // compare ignoring last '\n' + + BCPGInputStream pIn = new BCPGInputStream(aIn); + // parse and compare signature + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + compareSignature(sig); + } + + private void testParseV6InlineSignedMessage() + throws IOException + { + ByteArrayInputStream bIn = new ByteArrayInputStream(INLINE_SIGNED.getBytes(StandardCharsets.UTF_8)); + ArmoredInputStream aIn = new ArmoredInputStream(bIn); + BCPGInputStream pIn = new BCPGInputStream(aIn); + + // Parse and compare the OnePassSignature packet + OnePassSignaturePacket ops = (OnePassSignaturePacket) pIn.readPacket(); + isEquals("OPS packet MUST be of version 6", + OnePassSignaturePacket.VERSION_6, ops.getVersion()); + isEncodingEqual("OPS packet issuer fingerprint mismatch", + ISSUER, ops.getFingerprint()); + isEncodingEqual("OPS packet salt mismatch", + SALT, ops.getSalt()); + isTrue("OPS packet isContaining mismatch", + ops.isContaining()); + + // Parse and compare the LiteralData packet + LiteralDataPacket lit = (LiteralDataPacket) pIn.readPacket(); + compareLiteralData(lit); + + // Parse and compare the Signature packet + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + compareSignature(sig); + } + + + private void compareLiteralData(LiteralDataPacket lit) + throws IOException + { + isEquals("LiteralDataPacket format mismatch", + PGPLiteralData.UTF8, lit.getFormat()); + isEquals("LiteralDataPacket mod data mismatch", + 0, lit.getModificationTime()); + byte[] content = lit.getInputStream().readAll(); + String contentString = new String(content, StandardCharsets.UTF_8); + isEquals("LiteralDataPacket content mismatch", + CONTENT, contentString); + } + + private void compareSignature(SignaturePacket sig) + { + isEquals("SignaturePacket version mismatch", + SignaturePacket.VERSION_6, sig.getVersion()); + isEquals("SignaturePacket signature type mismatch", + PGPSignature.CANONICAL_TEXT_DOCUMENT, sig.getSignatureType()); + isEquals("SignaturePacket key algorithm mismatch", + PublicKeyAlgorithmTags.Ed25519, sig.getKeyAlgorithm()); + isEquals("SignaturePacket hash algorithm mismatch", + HashAlgorithmTags.SHA512, sig.getHashAlgorithm()); + isTrue("SignaturePacket salt mismatch", + Arrays.areEqual(SALT, sig.getSalt())); + // hashed subpackets + isEquals("SignaturePacket number of hashed packets mismatch", + 2, sig.getHashedSubPackets().length); + SignatureCreationTime creationTimeSubpacket = (SignatureCreationTime) sig.getHashedSubPackets()[0]; + isEquals("SignaturePacket signature creation time mismatch", + 1670947683000L, creationTimeSubpacket.getTime().getTime()); + IssuerFingerprint issuerSubpacket = (IssuerFingerprint) sig.getHashedSubPackets()[1]; + isEncodingEqual("SignaturePacket issuer fingerprint mismatch", + ISSUER, issuerSubpacket.getFingerprint()); + // unhashed subpackets + isEquals("SignaturePacket number of unhashed packets mismatch", + 0, sig.getUnhashedSubPackets().length); + } + + @Override + public String getName() + { + return "OpenPgpMessageTest"; + } + + @Override + public void performTest() + throws Exception + { + testParseV6CleartextSignedMessage(); + testParseV6InlineSignedMessage(); + } + + public static void main(String[] args) + { + runTest(new OpenPgpMessageTest()); + } +} diff --git a/pg/src/test/java/org/bouncycastle/bcpg/test/SignaturePacketTest.java b/pg/src/test/java/org/bouncycastle/bcpg/test/SignaturePacketTest.java new file mode 100644 index 0000000000..6d77368bd7 --- /dev/null +++ b/pg/src/test/java/org/bouncycastle/bcpg/test/SignaturePacketTest.java @@ -0,0 +1,159 @@ +package org.bouncycastle.bcpg.test; + +import org.bouncycastle.bcpg.*; +import org.bouncycastle.bcpg.sig.IssuerFingerprint; +import org.bouncycastle.bcpg.sig.IssuerKeyID; +import org.bouncycastle.bcpg.sig.SignatureCreationTime; +import org.bouncycastle.openpgp.PGPSignature; +import org.bouncycastle.util.encoders.Hex; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class SignaturePacketTest + extends AbstractPacketTest +{ + @Override + public String getName() + { + return "SignaturePacketTest"; + } + + @Override + public void performTest() + throws Exception + { + testParseV6Signature(); + testParseV4Ed25519LegacySignature(); + testParseUnknownVersionSignaturePacket(); + } + + private void testParseV6Signature() + throws IOException + { + // Hex-encoded OpenPGP v6 signature packet + // Extracted from https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#name-sample-inline-signed-messag + byte[] encSigPacket = Hex.decode("c29806011b0a0000002905826398a363222106cb186c4f0609a697e4d52dfa6c722b0c1f1e27c18a56708f6525ec27bad9acc90000000069362076495f50218890f7f5e2ee3c1822514f70500f551d86e5c921e404e34a53fbac27d06fb80aa8fc5bcb16e19631b280740f9ea6aed5e073ad00f9415a653c40e77a6ae77e692ba71d069a109fa24c58cfd8e316d0a06b34ad9acb8e5c5f521501"); + // Issuer of the message + byte[] issuerFP = Hex.decode("CB186C4F0609A697E4D52DFA6C722B0C1F1E27C18A56708F6525EC27BAD9ACC9"); + // Salt used to generate the signature + byte[] salt = Hex.decode("76495F50218890F7F5E2EE3C1822514F70500F551D86E5C921E404E34A53FBAC"); + + ByteArrayInputStream bIn = new ByteArrayInputStream(encSigPacket); + BCPGInputStream pIn = new BCPGInputStream(bIn); + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + + isEquals("SignaturePacket version mismatch", + SignaturePacket.VERSION_6, sig.getVersion()); + isEquals("SignaturePacket signature type mismatch", + PGPSignature.CANONICAL_TEXT_DOCUMENT, sig.getSignatureType()); + isEquals("SignaturePacket key algorithm mismatch", + PublicKeyAlgorithmTags.Ed25519, sig.getKeyAlgorithm()); + isEquals("SignaturePacket hash algorithm mismatch", + HashAlgorithmTags.SHA512, sig.getHashAlgorithm()); + isEncodingEqual("SignaturePacket salt mismatch", + salt, sig.getSalt()); + // hashed subpackets + isEquals("SignaturePacket number of hashed packets mismatch", + 2, sig.getHashedSubPackets().length); + SignatureCreationTime creationTimeSubpacket = (SignatureCreationTime) sig.getHashedSubPackets()[0]; + isEquals("SignaturePacket signature creation time mismatch", + 1670947683000L, creationTimeSubpacket.getTime().getTime()); + IssuerFingerprint issuerSubpacket = (IssuerFingerprint) sig.getHashedSubPackets()[1]; + isEncodingEqual("SignaturePacket issuer fingerprint mismatch", + issuerFP, issuerSubpacket.getFingerprint()); + // unhashed subpackets + isEquals("SignaturePacket number of unhashed packets mismatch", + 0, sig.getUnhashedSubPackets().length); + + // v6 Ed25519 signatures (not LEGACY) do not use MPI encoding for the raw signature + // but rather encode into octet strings + isNull("Signature MPI encoding MUST be null", + sig.getSignature()); + isEncodingEqual("Signature octet string encoding mismatch", + Hex.decode("27d06fb80aa8fc5bcb16e19631b280740f9ea6aed5e073ad00f9415a653c40e77a6ae77e692ba71d069a109fa24c58cfd8e316d0a06b34ad9acb8e5c5f521501"), + sig.getSignatureBytes()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, true); + sig.encode(pOut); + pOut.close(); + + isEncodingEqual("SignaturePacket encoding mismatch", encSigPacket, bOut.toByteArray()); + } + + private void testParseV4Ed25519LegacySignature() + throws IOException + { + // Hex-encoded v4 test signature + // see https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#name-sample-v4-ed25519legacy-sig + byte[] encSigPacket = Hex.decode("885e040016080006050255f95f95000a09108cfde12197965a9af62200ff56f90cca98e2102637bd983fdb16c131dfd27ed82bf4dde5606e0d756aed33660100d09c4fa11527f038e0f57f2201d82f2ea2c9033265fa6ceb489e854bae61b404"); + ByteArrayInputStream bIn = new ByteArrayInputStream(encSigPacket); + BCPGInputStream pIn = new BCPGInputStream(bIn); + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + + isEquals("SignaturePacket version mismatch", + SignaturePacket.VERSION_4, sig.getVersion()); + isEquals("SignaturePacket signature type mismatch", + PGPSignature.BINARY_DOCUMENT, sig.getSignatureType()); + isEquals("SignaturePacket public key algorithm mismatch", + PublicKeyAlgorithmTags.EDDSA_LEGACY, sig.getKeyAlgorithm()); + isEquals("SignaturePacket hash algorithm mismatch", + HashAlgorithmTags.SHA256, sig.getHashAlgorithm()); + isEquals("SignaturePacket number of hashed subpackets mismatch", + 1, sig.getHashedSubPackets().length); + SignatureCreationTime creationTimeSubpacket = (SignatureCreationTime) sig.getHashedSubPackets()[0]; + isEquals("SignaturePacket creationTime mismatch", + 1442406293000L, creationTimeSubpacket.getTime().getTime()); + isEquals("SignaturePacket number of unhashed subpackets mismatch", + 1, sig.getUnhashedSubPackets().length); + IssuerKeyID issuerKeyID = (IssuerKeyID) sig.getUnhashedSubPackets()[0]; + isEquals("SignaturePacket issuer key-id mismatch", + -8287220204898461030L, issuerKeyID.getKeyID()); + + // EDDSA_LEGACY uses MPI encoding for the raw signature value + MPInteger[] mpInts = sig.getSignature(); + isEquals("Signature MPI encoding mismatch", + 2, mpInts.length); + isEncodingEqual("Signature MPI encoding in signatureBytes field mismatch", + Hex.decode("00ff56f90cca98e2102637bd983fdb16c131dfd27ed82bf4dde5606e0d756aed33660100d09c4fa11527f038e0f57f2201d82f2ea2c9033265fa6ceb489e854bae61b404"), + sig.getSignatureBytes()); + + // v4 signatures do not have salt + isNull("Salt MUST be null", sig.getSalt()); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + BCPGOutputStream pOut = new BCPGOutputStream(bOut, false); + sig.encode(pOut); + pOut.close(); + + isEncodingEqual("SignaturePacket encoding mismatch", + encSigPacket, bOut.toByteArray()); + } + + private void testParseUnknownVersionSignaturePacket() + { + // Hex-encoded signature with version 0x99 + byte[] encSigPacket = Hex.decode("885e990016080006050255f95f95000a09108cfde12197965a9af62200ff56f90cca98e2102637bd983fdb16c131dfd27ed82bf4dde5606e0d756aed33660100d09c4fa11527f038e0f57f2201d82f2ea2c9033265fa6ceb489e854bae61b404"); + ByteArrayInputStream bIn = new ByteArrayInputStream(encSigPacket); + BCPGInputStream pIn = new BCPGInputStream(bIn); + Exception ex = testException("unsupported version: 153", + "UnsupportedPacketVersionException", + new TestExceptionOperation() + { + @Override + public void operation() + throws Exception + { + SignaturePacket sig = (SignaturePacket) pIn.readPacket(); + } + }); + isNotNull("Parsing SignaturePacket of version 0x99 MUST throw UnsupportedPacketVersionException.", ex); + } + + public static void main(String[] args) + { + runTest(new SignaturePacketTest()); + } +}