org.bouncycastle.openpgp.PGPKeyPair Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPKeyPair. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ComparatorKeyringTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testRdeSigningKey_same() throws Exception {
  Keyring actualKeyring = mock(Keyring.class);
  Keyring secondKeyring = mock(Keyring.class);
  PGPKeyPair keyPair =
      new PGPKeyPair(
          mockPublicKey(false, false),
          mockPrivateKey(false, false, false, false));
  PGPKeyPair keyPairCopy =
      new PGPKeyPair(
          mockPublicKey(false, false),
          mockPrivateKey(false, false, false, false));
  when(actualKeyring.getRdeSigningKey()).thenReturn(keyPair);
  when(secondKeyring.getRdeSigningKey()).thenReturn(keyPairCopy);
  Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring);

  assertThat(comparatorKeyring.getRdeSigningKey()).isSameInstanceAs(keyPair);

  assertAboutLogs().that(testLogHandler).hasNoLogsAtLevel(Level.SEVERE);
}
 
Example #2
Source File: RydeEncryptionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFail_oneReceiver_decryptWithWrongKey() throws Exception {
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  PGPKeyPair key = keyringModule.get("[email protected]", ENCRYPT);
  PGPKeyPair wrongKey = keyringModule.get("[email protected]", ENCRYPT);
  assertThat(key.getKeyID()).isNotEqualTo(wrongKey.getKeyID());
  byte[] expected = "Testing 1, 2, 3".getBytes(UTF_8);

  ByteArrayOutputStream output = new ByteArrayOutputStream();
  try (OutputStream encryptor =
      RydeEncryption.openEncryptor(output, false, ImmutableList.of(key.getPublicKey()))) {
    encryptor.write(expected);
  }
  byte[] encryptedData = output.toByteArray();

  ByteArrayInputStream input = new ByteArrayInputStream(encryptedData);
  RuntimeException thrown =
      assertThrows(
          RuntimeException.class,
          () -> {
            RydeEncryption.openDecryptor(input, false, wrongKey.getPrivateKey()).read();
          });

  assertThat(thrown).hasCauseThat().isInstanceOf(PGPException.class);
}
 
Example #3
Source File: RydeEncryptionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_twoReceivers() throws Exception {
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  PGPKeyPair key1 = keyringModule.get("[email protected]", ENCRYPT);
  PGPKeyPair key2 = keyringModule.get("[email protected]", ENCRYPT);
  assertThat(key1.getKeyID()).isNotEqualTo(key2.getKeyID());
  byte[] expected = "Testing 1, 2, 3".getBytes(UTF_8);

  ByteArrayOutputStream output = new ByteArrayOutputStream();
  try (OutputStream encryptor =
      RydeEncryption.openEncryptor(
          output, false, ImmutableList.of(key1.getPublicKey(), key2.getPublicKey()))) {
    encryptor.write(expected);
  }
  byte[] encryptedData = output.toByteArray();

  ByteArrayInputStream input = new ByteArrayInputStream(encryptedData);
  try (InputStream decryptor = RydeEncryption.openDecryptor(input, false, key1.getPrivateKey())) {
    assertThat(ByteStreams.toByteArray(decryptor)).isEqualTo(expected);
  }

  input.reset();
  try (InputStream decryptor = RydeEncryption.openDecryptor(input, false, key2.getPrivateKey())) {
    assertThat(ByteStreams.toByteArray(decryptor)).isEqualTo(expected);
  }
}
 
Example #4
Source File: KeySerializer.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize a PGPKeyPair
 *
 * <p>Use this to serialize a PGPPrivateKey as well (pairing it with the corresponding
 * PGPPublicKey), as private keys can't be serialized on their own.
 */
public static byte[] serializeKeyPair(PGPKeyPair keyPair) throws IOException, PGPException {
  try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
    // NOTE: We have to close the ArmoredOutputStream before calling the underlying OutputStream's
    // "toByteArray". Failing to do so would result in a truncated serialization as we took the
    // byte array before the ArmoredOutputStream wrote all the data.
    //
    // Even "flushing" the ArmoredOutputStream isn't enough - as there are parts that are only
    // written by the ArmoredOutputStream when it is closed: the "-----END PGP PRIVATE KEY
    // BLOCK-----" (or similar) footer.
    try (ArmoredOutputStream out = new ArmoredOutputStream(byteStream)) {
      new PGPSecretKey(
          keyPair.getPrivateKey(),
          keyPair.getPublicKey(),
          new JcaPGPDigestCalculatorProviderBuilder()
              .setProvider("BC")
              .build()
              .get(HashAlgorithmTags.SHA256),
          true,
          null).encode(out);
    }
    return byteStream.toByteArray();
  }
}
 
Example #5
Source File: PgpHelper.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Same as {@link #lookupPublicKey} but also retrieves the associated private key.
 *
 * @throws VerifyException if either keys couldn't be found.
 * @see #lookupPublicKey
 */
public static PGPKeyPair lookupKeyPair(
    PGPPublicKeyRingCollection publics,
    PGPSecretKeyRingCollection privates,
    String query,
    KeyRequirement want) {
  PGPPublicKey publicKey = lookupPublicKey(publics, query, want);
  PGPPrivateKey privateKey;
  try {
    PGPSecretKey secret = verifyNotNull(privates.getSecretKey(publicKey.getKeyID()),
        "Keyring missing private key associated with public key id: %x (query '%s')",
        publicKey.getKeyID(), query);
    // We do not support putting a password on the private key so we're just going to
    // put char[0] here.
    privateKey = secret.extractPrivateKey(
        new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
            .build(new char[0]));
  } catch (PGPException e) {
    throw new VerifyException(String.format("Could not load PGP private key for: %s", query), e);
  }
  return new PGPKeyPair(publicKey, privateKey);
}
 
Example #6
Source File: RydeEncryptionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_decryptHasntChanged() throws Exception {
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  PGPKeyPair key = keyringModule.get("[email protected]", ENCRYPT);
  byte[] expected = "Testing 1, 2, 3".getBytes(UTF_8);
  byte[] encryptedData =
      Base64.getMimeDecoder()
          .decode(
              "hQEMA6WcEy81iaHVAQf+I14Ewo1Fr6epwqtUoMSuy3qtobayZI54u/ohyMBgnpfts8B15320x4eO"
                  + "ElbaMKLJFZzOI8IsJRlX9mpSMp+qALdhOjXfM4q9wHNPKTRXqkhhblyTt7r4MTRp1w8lTA8R5hGO"
                  + "MCoxYwicK7DYrqL728FCeA2UBaQVXB6FZIIjujwNRzghvyqGDLLF6LxnR8ovB2PqT4Ho0wTmHWNy"
                  + "CZWyR5y9TBgTZWpIoNFuHQGe8egz/rTR+ixp1Ru3lxib7xuJVQyjbiGMO+lk4ffeEg4KpwEFblMx"
                  + "s17nxCrT5E30qktKjRQopvGICSrxyMGrbyUu5HdASZDj4jyqgP152KxJ18khC05Kf6zT4ouLoJHB"
                  + "XENDmLN3Onf6IwR043Lk0KISKi6z");

  ByteArrayInputStream input = new ByteArrayInputStream(encryptedData);
  try (InputStream decryptor = RydeEncryption.openDecryptor(input, false, key.getPrivateKey())) {
    assertThat(ByteStreams.toByteArray(decryptor)).isEqualTo(expected);
  }
}
 
Example #7
Source File: ComparatorKeyringTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testRdeSigningKey_actualThrows() throws Exception {
  Keyring actualKeyring = mock(Keyring.class);
  Keyring secondKeyring = mock(Keyring.class);
  PGPKeyPair keyPair =
      new PGPKeyPair(
          mockPublicKey(false, false),
          mockPrivateKey(false, false, false, false));
  when(actualKeyring.getRdeSigningKey()).thenThrow(new KeyringException("message"));
  when(secondKeyring.getRdeSigningKey()).thenReturn(keyPair);
  Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring);

  assertThrows(KeyringException.class, comparatorKeyring::getRdeSigningKey);

  assertAboutLogs()
      .that(testLogHandler)
      .hasLogAtLevelWithMessage(
          Level.SEVERE, ".getRdeSigningKey: Only actual implementation threw exception");
}
 
Example #8
Source File: ComparatorKeyringTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testRdeSigningKey_secondThrows() throws Exception {
  Keyring actualKeyring = mock(Keyring.class);
  Keyring secondKeyring = mock(Keyring.class);
  PGPKeyPair keyPair =
      new PGPKeyPair(
          mockPublicKey(false, false),
          mockPrivateKey(false, false, false, false));
  when(actualKeyring.getRdeSigningKey()).thenReturn(keyPair);
  when(secondKeyring.getRdeSigningKey()).thenThrow(new KeyringException("message"));
  Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring);

  assertThat(comparatorKeyring.getRdeSigningKey()).isSameInstanceAs(keyPair);

  assertAboutLogs()
      .that(testLogHandler)
      .hasLogAtLevelWithMessage(
          Level.SEVERE, ".getRdeSigningKey: Only second implementation threw exception");
}
 
Example #9
Source File: RydeEncryptionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_oneReceiver_withIntegrityPacket() throws Exception {
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  PGPKeyPair key = keyringModule.get("[email protected]", ENCRYPT);
  byte[] expected = "Testing 1, 2, 3".getBytes(UTF_8);

  ByteArrayOutputStream output = new ByteArrayOutputStream();
  try (OutputStream encryptor =
      RydeEncryption.openEncryptor(output, true, ImmutableList.of(key.getPublicKey()))) {
    encryptor.write(expected);
  }
  byte[] encryptedData = output.toByteArray();

  ByteArrayInputStream input = new ByteArrayInputStream(encryptedData);
  try (InputStream decryptor = RydeEncryption.openDecryptor(input, true, key.getPrivateKey())) {
    assertThat(ByteStreams.toByteArray(decryptor)).isEqualTo(expected);
  }
}
 
Example #10
Source File: RydeEncryptionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_oneReceiver_decryptWithCorrectKey() throws Exception {
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  PGPKeyPair key = keyringModule.get("[email protected]", ENCRYPT);
  byte[] expected = "Testing 1, 2, 3".getBytes(UTF_8);

  ByteArrayOutputStream output = new ByteArrayOutputStream();
  try (OutputStream encryptor =
      RydeEncryption.openEncryptor(output, false, ImmutableList.of(key.getPublicKey()))) {
    encryptor.write(expected);
  }
  byte[] encryptedData = output.toByteArray();

  ByteArrayInputStream input = new ByteArrayInputStream(encryptedData);
  try (InputStream decryptor = RydeEncryption.openDecryptor(input, false, key.getPrivateKey())) {
    assertThat(ByteStreams.toByteArray(decryptor)).isEqualTo(expected);
  }
}
 
Example #11
Source File: EscrowDepositEncryptor.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Creates a {@code .ryde} and {@code .sig} file, provided an XML deposit file. */
void encrypt(String tld, Path xmlFile, Path outdir)
    throws IOException, XmlException {
  try (InputStream xmlFileInput = Files.newInputStream(xmlFile);
      BufferedInputStream xmlInput = new BufferedInputStream(xmlFileInput, PEEK_BUFFER_SIZE)) {
    DateTime watermark = RdeUtil.peekWatermark(xmlInput);
    String name = RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, 0);
    Path rydePath = outdir.resolve(name + ".ryde");
    Path sigPath = outdir.resolve(name + ".sig");
    Path pubPath = outdir.resolve(tld + ".pub");
    PGPKeyPair signingKey = rdeSigningKey.get();
    try (OutputStream rydeOutput = Files.newOutputStream(rydePath);
        OutputStream sigOutput = Files.newOutputStream(sigPath);
        RydeEncoder rydeEncoder = new RydeEncoder.Builder()
            .setRydeOutput(rydeOutput, rdeReceiverKey.get())
            .setSignatureOutput(sigOutput, signingKey)
            .setFileMetadata(name, Files.size(xmlFile), watermark)
            .build()) {
      ByteStreams.copy(xmlInput, rydeEncoder);
    }
    try (OutputStream pubOutput = Files.newOutputStream(pubPath);
        ArmoredOutputStream ascOutput = new ArmoredOutputStream(pubOutput)) {
      signingKey.getPublicKey().encode(ascOutput);
    }
  }
}
 
Example #12
Source File: GhostrydeTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("Intentionally corrupting a PGP key is easier said than done >_>")
public void testFailure_keyCorruption() throws Exception {
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  byte[] data = "Fanatics have their dreams, wherewith they weave.".getBytes(UTF_8);
  PGPKeyPair rsa = keyringModule.get("[email protected]", ENCRYPT);
  PGPPublicKey publicKey = rsa.getPublicKey();

  // Make the last byte of the private key off by one. muahahaha
  byte[] keyData = rsa.getPrivateKey().getPrivateKeyDataPacket().getEncoded();
  keyData[keyData.length - 1]++;
  PGPPrivateKey privateKey = new PGPPrivateKey(
      rsa.getKeyID(),
      rsa.getPrivateKey().getPublicKeyPacket(),
      rsa.getPrivateKey().getPrivateKeyDataPacket());

  ByteArrayOutputStream bsOut = new ByteArrayOutputStream();
  try (OutputStream encoder = Ghostryde.encoder(bsOut, publicKey)) {
    encoder.write(data);
  }

  ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray());
  try (InputStream decoder = Ghostryde.decoder(bsIn, privateKey)) {
    ByteStreams.copy(decoder, ByteStreams.nullOutputStream());
  }
}
 
Example #13
Source File: RydeEncoder.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private RydeEncoder(
    OutputStream rydeOutput,
    OutputStream sigOutput,
    long dataLength,
    String filenamePrefix,
    DateTime modified,
    PGPKeyPair signingKey,
    Collection<PGPPublicKey> receiverKeys) {
  super(null);
  this.sigOutput = sigOutput;
  signer = closer.register(new RydePgpSigningOutputStream(checkNotNull(rydeOutput), signingKey));
  OutputStream encryptLayer =
      closer.register(openEncryptor(signer, RYDE_USE_INTEGRITY_PACKET, receiverKeys));
  OutputStream kompressor = closer.register(openCompressor(encryptLayer));
  OutputStream fileLayer =
      closer.register(openPgpFileWriter(kompressor, filenamePrefix + ".tar", modified));
  OutputStream tarLayer =
      closer.register(openTarWriter(fileLayer, dataLength, filenamePrefix + ".xml", modified));
  this.out = tarLayer;
}
 
Example #14
Source File: ComparatorKeyringTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeyPairToString() throws Exception {
  assertThat(
          ComparatorKeyring.stringify(
              new PGPKeyPair(
                  mockPublicKey(false, false),
                  mockPrivateKey(false, false, false, false))))
      .isEqualTo(KEY_PAIR_TO_STRING);
}
 
Example #15
Source File: KmsTestHelper.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static PGPKeyPair getKeyPair() throws Exception {
  PGPSecretKey secretKey = getPrivateKeyring().getSecretKey();
  return new PGPKeyPair(
      secretKey.getPublicKey(),
      secretKey.extractPrivateKey(
          new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
          .build(new char[0])));
}
 
Example #16
Source File: KeySerializerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test public void serializeKeyPair() throws Exception {
  PGPKeyPair keyPairResult =
      KeySerializer.deserializeKeyPair(
          KeySerializer.serializeKeyPair(new PGPKeyPair(PUBLIC_KEY, PRIVATE_KEY)));

  assertThat(keyPairResult.getPublicKey().getEncoded()).isEqualTo(PUBLIC_KEY.getEncoded());
  assertThat(keyPairResult.getPrivateKey().getKeyID()).isEqualTo(PRIVATE_KEY.getKeyID());
  assertThat(keyPairResult.getPrivateKey().getPrivateKeyDataPacket().getEncoded())
      .isEqualTo(PRIVATE_KEY.getPrivateKeyDataPacket().getEncoded());
  assertThat(keyPairResult.getPrivateKey().getPublicKeyPacket().getEncoded())
      .isEqualTo(PRIVATE_KEY.getPublicKeyPacket().getEncoded());
}
 
Example #17
Source File: DummyKeyringModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Always returns a {@link InMemoryKeyring} instance. */
@Provides
@Named("DummyKeyring")
static InMemoryKeyring provideDummyKeyring() {
  PGPKeyPair dummyKey;
  try (InputStream publicInput = PGP_PUBLIC_KEYRING.openStream();
      InputStream privateInput = PGP_PRIVATE_KEYRING.openStream()) {
    PGPPublicKeyRingCollection publicKeys =
        new BcPGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicInput));
    PGPSecretKeyRingCollection privateKeys =
        new BcPGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateInput));
    dummyKey = lookupKeyPair(publicKeys, privateKeys, EMAIL_ADDRESS, ENCRYPT_SIGN);
  } catch (PGPException | IOException e) {
    throw new VerifyException("Failed to load PGP keys from jar", e);
  }
  // Use the same dummy PGP keypair for all required PGP keys -- a real production system would
  // have different values for these keys.  Pass dummy values for all Strings.
  return new InMemoryKeyring(
      dummyKey,
      dummyKey,
      dummyKey.getPublicKey(),
      dummyKey,
      dummyKey.getPublicKey(),
      "not a real key",
      "not a real key",
      "not a real password",
      "not a real API key",
      "not a real login",
      "not a real password",
      "not a real login",
      "not a real credential",
      "not a real password",
      "not a real password");
}
 
Example #18
Source File: ComparatorKeyring.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Implements toString for the PGP classes. */
@Override
protected String stringifyResult(Method method, @Nullable Object a) {
  Class<?> clazz = method.getReturnType();
  if (PGPPublicKey.class.equals(clazz)) {
    return stringify((PGPPublicKey) a);
  }
  if (PGPPrivateKey.class.equals(clazz)) {
    return stringify((PGPPrivateKey) a);
  }
  if (PGPKeyPair.class.equals(clazz)) {
    return stringify((PGPKeyPair) a);
  }
  return super.stringifyResult(method, a);
}
 
Example #19
Source File: GhostrydeTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testFullEncryption() throws Exception {
  // Check that the full encryption hasn't changed. All the other tests check that encrypting and
  // decrypting results in the original data, but not whether the encryption method has changed.
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  PGPKeyPair dsa = keyringModule.get("[email protected]", ENCRYPT);
  PGPPrivateKey privateKey = dsa.getPrivateKey();

  // Encryption is inconsistent because it uses a random state. But decryption is consistent!
  //
  // If the encryption has legitimately changed - uncomment the following code, and copy the new
  // encryptedInputBase64 from the test error:
  //
  // assertThat(
  //         Base64.getMimeEncoder()
  //             .encodeToString(
  //                 Ghostryde.encode("Some data!!!111!!!".getBytes(UTF_8), dsa.getPublicKey())))
  //     .isEqualTo("expect error");

  String encryptedInputBase64 =
      "    hQEMA6WcEy81iaHVAQgAnn9bS6IOCTW2uZnITPWH8zIYr6K7YJslv38c4YU5eQqVhHC5PN0NhM2l\n"
          + "    i89U3lUE6gp3DdEEbTbugwXCHWyRL4fYTlpiHZjBn2vZdSS21EAG+q1XuTaD8DTjkC2G060/sW6i\n"
          + "    0gSIkksqgubbSVZTxHEqh92tv35KCqiYc52hjKZIIGI8FHhpJOtDa3bhMMad8nrMy3vbv5LiYNh5\n"
          + "    j3DUCFhskU8Ldi1vBfXIonqUNLBrD/R471VVJyQ3NoGQTVUF9uXLoy+2dL0oBLc1Avj1XNP5PQ08\n"
          + "    MWlqmezkLdY0oHnQqTHYhYDxRo/Sw7xO1GLwWR11rcx/IAJloJbKSHTFeNJUAcKFnKvPDwBk3nnr\n"
          + "    uR505HtOj/tZDT5weVjhrlnmWXzaBRmYASy6PXZu6KzTbPUQTf4JeeJWdyw7glLMr2WPdMVPGZ8e\n"
          + "    gcFAjSJZjZlqohZyBUpP\n";

  byte[] result =
      Ghostryde.decode(Base64.getMimeDecoder().decode(encryptedInputBase64), privateKey);

  assertThat(new String(result, UTF_8)).isEqualTo("Some data!!!111!!!");
}
 
Example #20
Source File: GhostrydeTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_keyMismatch() throws Exception {
  FakeKeyringModule keyringModule = new FakeKeyringModule();
  byte[] data = "Fanatics have their dreams, wherewith they weave.".getBytes(UTF_8);
  PGPKeyPair dsa1 = keyringModule.get("[email protected]", ENCRYPT);
  PGPKeyPair dsa2 = keyringModule.get("[email protected]", ENCRYPT);
  PGPPublicKey publicKey = dsa1.getPublicKey();
  PGPPrivateKey privateKey = dsa2.getPrivateKey();

  ByteArrayOutputStream bsOut = new ByteArrayOutputStream();
  try (OutputStream encoder = Ghostryde.encoder(bsOut, publicKey)) {
    encoder.write(data);
  }

  ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray());
  RuntimeException thrown =
      assertThrows(
          RuntimeException.class,
          () -> {
            try (InputStream decoder = Ghostryde.decoder(bsIn, privateKey)) {
              ByteStreams.copy(decoder, ByteStreams.nullOutputStream());
            }
          });
  assertThat(thrown).hasCauseThat().isInstanceOf(PGPException.class);
  assertThat(thrown)
      .hasCauseThat()
      .hasMessageThat()
      .contains(
          "Message was encrypted for keyids [a59c132f3589a1d5] but ours is c9598c84ec70b9fd");
}
 
Example #21
Source File: KmsKeyringTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void test_getRdeSigningKey() throws Exception {
  saveKeyPairSecret("rde-signing-public", "rde-signing-private");

  PGPKeyPair rdeSigningKey = keyring.getRdeSigningKey();

  assertThat(KeySerializer.serializeKeyPair(rdeSigningKey))
      .isEqualTo(KeySerializer.serializeKeyPair(KmsTestHelper.getKeyPair()));
}
 
Example #22
Source File: KmsKeyringTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void test_getRdeStagingDecryptionKey() throws Exception {
  savePrivateKeySecret("rde-staging-private");
  savePublicKeySecret("rde-staging-public");

  PGPPrivateKey rdeStagingDecryptionKey = keyring.getRdeStagingDecryptionKey();
  PGPPublicKey rdeStagingEncryptionKey = keyring.getRdeStagingEncryptionKey();
  PGPKeyPair keyPair = new PGPKeyPair(rdeStagingEncryptionKey, rdeStagingDecryptionKey);

  assertThat(KeySerializer.serializeKeyPair(keyPair))
      .isEqualTo(KeySerializer.serializeKeyPair(KmsTestHelper.getKeyPair()));
}
 
Example #23
Source File: KmsKeyringTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void test_getBrdaSigningKey() throws Exception {
  saveKeyPairSecret("brda-signing-public", "brda-signing-private");

  PGPKeyPair brdaSigningKey = keyring.getBrdaSigningKey();

  assertThat(KeySerializer.serializeKeyPair(brdaSigningKey))
      .isEqualTo(KeySerializer.serializeKeyPair(KmsTestHelper.getKeyPair()));
}
 
Example #24
Source File: KeySerializer.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Deserialize a PGPKeyPair */
public static PGPKeyPair deserializeKeyPair(byte[] serialized)
    throws IOException, PGPException {
  PGPSecretKey secretKey =
      new BcPGPSecretKeyRing(
          PGPUtil.getDecoderStream(
              new ByteArrayInputStream(serialized))).getSecretKey();
  return new PGPKeyPair(
      secretKey.getPublicKey(),
      secretKey.extractPrivateKey(createSecretKeyDecryptor()));
}
 
Example #25
Source File: PGPUtils.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
static PGPKeyPair decrypt(PGPSecretKey secretKey, PBESecretKeyDecryptor dec) throws KonException {
    try {
        return new PGPKeyPair(secretKey.getPublicKey(), secretKey.extractPrivateKey(dec));
    } catch (PGPException ex) {
        LOGGER.log(Level.WARNING, "failed", ex);
        throw new KonException(KonException.Error.LOAD_KEY_DECRYPT, ex);
    }
}
 
Example #26
Source File: RydePgpSigningOutputStream.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Create a signer that wraps {@code os} and generates a detached signature using
 * {@code signingKey}. After closing, you should call {@link #getSignature()} to get the detached
 * signature.
 *
 * @param os is the upstream {@link OutputStream} which is not closed by this object
 * @throws RuntimeException to rethrow {@link PGPException}
 */
public RydePgpSigningOutputStream(
    @WillNotClose OutputStream os,
    PGPKeyPair signingKey) {
  super("RydePgpSigningOutputStream", os, false);
  try {
    signer = new PGPSignatureGenerator(
        new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256));
    signer.init(BINARY_DOCUMENT, signingKey.getPrivateKey());
  } catch (PGPException e) {
    throw new RuntimeException(e);
  }
  addUserInfoToSignature(signingKey.getPublicKey(), signer);
}
 
Example #27
Source File: PersonalKey.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private static X509Certificate createX509Certificate(PGPKeyPair keyPair,
        PGPPublicKeyRing keyRing)
        throws KonException {
    try {
        return X509Bridge.createCertificate(keyPair, keyRing.getEncoded());
    } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException |
            SignatureException | CertificateException | NoSuchProviderException |
            PGPException | IOException | OperatorCreationException ex) {
        LOGGER.log(Level.WARNING, "can't create X.509 certificate");
        throw new KonException(KonException.Error.LOAD_KEY, ex);
    }
}
 
Example #28
Source File: PersonalKey.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private PersonalKey(PGPKeyPair authKP,
        PGPKeyPair signKP,
        PGPKeyPair encryptKP,
        X509Certificate bridgeCert,
        String uid) throws PGPException {
    mAuthKey = authKP.getPublicKey();
    mLoginKey = PGPUtils.convertPrivateKey(authKP.getPrivateKey());
    mSignKey = signKP;
    mEncryptKey = encryptKP;
    mBridgeCert = bridgeCert;
    mUID = uid;
}
 
Example #29
Source File: ComparatorKeyringTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRdeSigningKey_different() throws Exception {
  Keyring actualKeyring = mock(Keyring.class);
  Keyring secondKeyring = mock(Keyring.class);
  PGPKeyPair keyPair =
      new PGPKeyPair(
          mockPublicKey(false, false),
          mockPrivateKey(false, false, false, false));
  PGPKeyPair keyPairDifferent =
      new PGPKeyPair(
          mockPublicKey(false, false),
          mockPrivateKey(true, false, false, false));
  when(actualKeyring.getRdeSigningKey()).thenReturn(keyPair);
  when(secondKeyring.getRdeSigningKey()).thenReturn(keyPairDifferent);
  Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring);

  assertThat(comparatorKeyring.getRdeSigningKey()).isSameInstanceAs(keyPair);

  String alternateKeyPairString = String.format(
      "PGPKeyPair{%s, %s}", PUBLIC_KEY_TO_STRING, "PGPPrivateKey{keyId=2}");

  assertAboutLogs()
      .that(testLogHandler)
      .hasLogAtLevelWithMessage(
          Level.SEVERE,
          String.format(
              ".getRdeSigningKey: Got different results! '%s' vs '%s'",
              KEY_PAIR_TO_STRING,
              alternateKeyPairString));
}
 
Example #30
Source File: KmsUpdater.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private KmsUpdater setKeyPair(
    PGPKeyPair keyPair, PrivateKeyLabel privateKeyLabel, PublicKeyLabel publicKeyLabel)
    throws IOException, PGPException {
  checkArgumentNotNull(keyPair);

  setSecret(privateKeyLabel.getLabel(), KeySerializer.serializeKeyPair(keyPair));
  setSecret(publicKeyLabel.getLabel(), KeySerializer.serializePublicKey(keyPair.getPublicKey()));
  return this;
}