Skip to content

Commit

Permalink
Fix unpacking time (unsigned int) from octets for large values
Browse files Browse the repository at this point in the history
  • Loading branch information
vanitasvitae committed Sep 14, 2024
1 parent 7352222 commit 95ca87a
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pg/src/main/java/org/bouncycastle/bcpg/sig/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ static long timeFromBytes(byte[] bytes)
throw new IllegalStateException("Byte array has unexpected length. Expected length 4, got " + bytes.length);
}

return Pack.bigEndianToInt(bytes, 0);
return Pack.bigEndianToInt(bytes, 0) & 0xFFFFFFFFL; // time is unsigned
}

static byte[] timeToBytes(long t)
Expand Down
3 changes: 2 additions & 1 deletion pg/src/test/java/org/bouncycastle/bcpg/test/AllTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ public void testPacketParsing()
new OnePassSignaturePacketTest(),
new OpenPgpMessageTest(),
new FingerprintUtilTest(),
new EncryptedMessagePacketTest()
new EncryptedMessagePacketTest(),
new UtilsTest()
};

for (int i = 0; i != tests.length; i++)
Expand Down
40 changes: 40 additions & 0 deletions pg/src/test/java/org/bouncycastle/bcpg/test/UtilsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.bouncycastle.bcpg.test;

import org.bouncycastle.bcpg.sig.KeyExpirationTime;
import org.bouncycastle.util.test.SimpleTest;

public class UtilsTest
extends SimpleTest
{
@Override
public String getName()
{
return "UtilsTest";
}

@Override
public void performTest()
throws Exception
{
testRoundtrippingLargeUnsignedInt();
}

private void testRoundtrippingLargeUnsignedInt()
{
// Integer.MAX_VALUE < large < 0xffffffff
long large = 2523592696L; // fits a 32-bit *unsigned* int, but overflows signed int
// KeyExpirationTime packs the time into 4 octets
KeyExpirationTime kexp = new KeyExpirationTime(false, large);
// getTime() parses the time from 4 octets
isEquals("Roundtripped unsigned int mismatches before packet parser pass", large, kexp.getTime());

// To be safe, do an additional packet encode/decode roundtrip
KeyExpirationTime pKexp = new KeyExpirationTime(kexp.isCritical(), kexp.isLongLength(), kexp.getData());
isEquals("Roundtripped unsigned int mismatches after packet parser pass", large, pKexp.getTime());
}

public static void main(String[] args)
{
runTest(new UtilsTest());
}
}

0 comments on commit 95ca87a

Please sign in to comment.