1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2024-11-23 04:42:06 +01:00

OpenPgpV4Fingerprint: Support pretty print format

This commit is contained in:
Paul Schaub 2021-05-08 14:01:42 +02:00
parent 1a82e015f7
commit ec611d7c5f
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311
2 changed files with 27 additions and 1 deletions

View file

@ -22,6 +22,7 @@ import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import javax.annotation.Nonnull;
import org.bouncycastle.openpgp.PGPKeyRing;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKey;
@ -45,7 +46,7 @@ public class OpenPgpV4Fingerprint implements CharSequence, Comparable<OpenPgpV4F
* @param fingerprint hexadecimal representation of the fingerprint.
*/
public OpenPgpV4Fingerprint(@Nonnull String fingerprint) {
String fp = fingerprint.trim().toUpperCase();
String fp = fingerprint.replace(" ", "").trim().toUpperCase();
if (!isValid(fp)) {
throw new IllegalArgumentException("Fingerprint " + fingerprint +
" does not appear to be a valid OpenPGP v4 fingerprint.");
@ -76,6 +77,10 @@ public class OpenPgpV4Fingerprint implements CharSequence, Comparable<OpenPgpV4F
this(ring.getPublicKey());
}
public OpenPgpV4Fingerprint(@Nonnull PGPKeyRing ring) {
this(ring.getPublicKey());
}
/**
* Check, whether the fingerprint consists of 40 valid hexadecimal characters.
* @param fp fingerprint to check.
@ -142,6 +147,20 @@ public class OpenPgpV4Fingerprint implements CharSequence, Comparable<OpenPgpV4F
return fingerprint;
}
public String prettyPrint() {
String fp = toString();
StringBuilder pretty = new StringBuilder();
for (int i = 0; i < 5; i++) {
pretty.append(fp, i * 4, (i + 1) * 4).append(' ');
}
pretty.append(' ');
for (int i = 5; i < 9; i++) {
pretty.append(fp, i * 4, (i + 1) * 4).append(' ');
}
pretty.append(fp, 36, 40);
return pretty.toString();
}
/**
* Return the fingerprint as an openpgp4fpr {@link URI}.
* An example would be 'openpgp4fpr:7F9116FEA90A5983936C7CFAA027DB2F3E1E118A'.

View file

@ -95,4 +95,11 @@ public class OpenPgpV4FingerprintTest {
URI uri = new URI(null, "5448452043414B452049532041204C4945212121", null);
assertThrows(IllegalArgumentException.class, () -> OpenPgpV4Fingerprint.fromUri(uri));
}
@Test
public void testFromPrettyPrinted() {
String prettyPrint = "C94B 884B 9A56 7B1C FB23 6999 7DC5 BDAC BBDF BF87";
OpenPgpV4Fingerprint fingerprint = new OpenPgpV4Fingerprint(prettyPrint);
assertEquals(prettyPrint, fingerprint.prettyPrint());
}
}