/** * * @param dsaKeyPair - the generated DSA key pair * @param elGamalKeyPair - the generated El Gamal key pair * @param identity - the given identity of the key pair ring * @param passphrase - the secret pass phrase to protect the key pair * @return a PGP Key Ring Generate with the El Gamal key pair added as sub key * @throws Exception */ public static final PGPKeyRingGenerator createPGPKeyRingGenerator(KeyPair dsaKeyPair, KeyPair elGamalKeyPair, String identity, char[] passphrase) throws Exception { PGPKeyPair dsaPgpKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKeyPair, new Date()); PGPKeyPair elGamalPgpKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elGamalKeyPair, new Date()); PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1); PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator( PGPSignature.POSITIVE_CERTIFICATION, dsaPgpKeyPair, identity, sha1Calc, null, null, new JcaPGPContentSignerBuilder(dsaPgpKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha1Calc).setProvider("BC").build(passphrase) ); keyRingGen.addSubKey(elGamalPgpKeyPair); return keyRingGen; }
/** * Same as {@link #lookupPublicKey} but also retrieves the associated private key. * * @throws VerifyException if either keys couldn't be found. * @see #lookupPublicKey */ @SuppressWarnings("deprecation") 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(e.getMessage()); } return new PGPKeyPair(publicKey, privateKey); }
/** * 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(); } }
@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"); }
@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()).isSameAs(keyPair); assertAboutLogs() .that(testLogHandler) .hasLogAtLevelWithMessage( Level.SEVERE, ".getRdeSigningKey: Only second implementation threw exception"); }
@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()).isSameAs(keyPair); assertAboutLogs().that(testLogHandler).hasNoLogsAtLevel(Level.SEVERE); }
/** * 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(os, false, -1); 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); }
/** Creates a {@code .ryde} and {@code .sig} file, provided an XML deposit file. */ void encrypt(String tld, Path xmlFile, Path outdir) throws IOException, PGPException, 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); RydePgpSigningOutputStream signLayer = pgpSigningFactory.create(rydeOutput, signingKey)) { try (RydePgpEncryptionOutputStream encryptLayer = pgpEncryptionFactory.create(signLayer, rdeReceiverKey.get()); RydePgpCompressionOutputStream compressLayer = pgpCompressionFactory.create(encryptLayer); RydePgpFileOutputStream fileLayer = pgpFileFactory.create(compressLayer, watermark, name + ".tar"); RydeTarOutputStream tarLayer = tarFactory.create(fileLayer, Files.size(xmlFile), watermark, name + ".xml")) { ByteStreams.copy(xmlInput, tarLayer); } Files.write(sigPath, signLayer.getSignature()); try (OutputStream pubOutput = Files.newOutputStream(pubPath); ArmoredOutputStream ascOutput = new ArmoredOutputStream(pubOutput)) { signingKey.getPublicKey().encode(ascOutput); } } } }
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; }
private PGPKeyPair getKeyPair(PrivateKeyLabel keyLabel) { try { return KeySerializer.deserializeKeyPair(getDecryptedData(keyLabel.getLabel())); } catch (IOException | PGPException e) { throw new KeyringException( String.format("Could not parse private keyLabel %s", keyLabel), e); } }
/** 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())); }
/** Implements equals for the PGP classes. */ @Override protected boolean compareResults(Method method, @Nullable Object a, @Nullable Object b) { Class<?> clazz = method.getReturnType(); if (PGPPublicKey.class.equals(clazz)) { return compare((PGPPublicKey) a, (PGPPublicKey) b); } if (PGPPrivateKey.class.equals(clazz)) { return compare((PGPPrivateKey) a, (PGPPrivateKey) b); } if (PGPKeyPair.class.equals(clazz)) { return compare((PGPKeyPair) a, (PGPKeyPair) b); } return super.compareResults(method, a, b); }
/** 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); }
@VisibleForTesting static boolean compare(@Nullable PGPKeyPair a, @Nullable PGPKeyPair b) { if (a == null || b == null) { return a == null && b == null; } return compare(a.getPublicKey(), b.getPublicKey()) && compare(a.getPrivateKey(), b.getPrivateKey()); }
@VisibleForTesting static String stringify(PGPKeyPair a) { if (a == null) { return "null"; } return MoreObjects.toStringHelper(PGPKeyPair.class) .addValue(stringify(a.getPublicKey())) .addValue(stringify(a.getPrivateKey())) .toString(); }
/** Always returns a {@link InMemoryKeyring} instance. */ @Provides static Keyring provideKeyring() { 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 login", "not a real password", "not a real login", "not a real credential", "not a real key"); }
public InMemoryKeyring( PGPKeyPair rdeStagingKey, PGPKeyPair rdeSigningKey, PGPPublicKey rdeReceiverKey, PGPKeyPair brdaSigningKey, PGPPublicKey brdaEncryptionKey, String rdeSshClientPublicKey, String rdeSshClientPrivateKey, String icannReportingPassword, String marksdbDnlLogin, String marksdbLordnPassword, String marksdbSmdrlLogin, String jsonCredential, String braintreePrivateKey) { checkArgument(PgpHelper.isSigningKey(rdeSigningKey.getPublicKey()), "RDE signing key must support signing: %s", rdeSigningKey.getKeyID()); checkArgument(rdeStagingKey.getPublicKey().isEncryptionKey(), "staging key must support encryption: %s", rdeStagingKey.getKeyID()); checkArgument(rdeReceiverKey.isEncryptionKey(), "receiver key must support encryption: %s", rdeReceiverKey.getKeyID()); checkArgument(PgpHelper.isSigningKey(brdaSigningKey.getPublicKey()), "BRDA signing key must support signing: %s", brdaSigningKey.getKeyID()); checkArgument(brdaEncryptionKey.isEncryptionKey(), "encryption key must support encryption: %s", brdaEncryptionKey.getKeyID()); this.rdeStagingKey = rdeStagingKey; this.rdeSigningKey = rdeSigningKey; this.rdeReceiverKey = rdeReceiverKey; this.brdaSigningKey = brdaSigningKey; this.brdaEncryptionKey = brdaEncryptionKey; this.rdeSshClientPublicKey = checkNotNull(rdeSshClientPublicKey, "rdeSshClientPublicKey"); this.rdeSshClientPrivateKey = checkNotNull(rdeSshClientPrivateKey, "rdeSshClientPrivateKey"); this.icannReportingPassword = checkNotNull(icannReportingPassword, "icannReportingPassword"); this.marksdbDnlLogin = checkNotNull(marksdbDnlLogin, "marksdbDnlLogin"); this.marksdbLordnPassword = checkNotNull(marksdbLordnPassword, "marksdbLordnPassword"); this.marksdbSmdrlLogin = checkNotNull(marksdbSmdrlLogin, "marksdbSmdrlLogin"); this.jsonCredential = checkNotNull(jsonCredential, "jsonCredential"); this.braintreePrivateKey = checkNotNull(braintreePrivateKey, "braintreePrivateKey"); }
@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())); }
@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())); }
@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())); }
static PGPKeyPair getKeyPair() throws Exception { PGPSecretKey secretKey = getPrivateKeyring().getSecretKey(); return new PGPKeyPair( secretKey.getPublicKey(), secretKey.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(new char[0]))); }
@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()); }
@Test public void testKeyPairToString() throws Exception { assertThat( ComparatorKeyring.stringify( new PGPKeyPair( mockPublicKey(false, false), mockPrivateKey(false, false, false, false)))) .isEqualTo(KEY_PAIR_TO_STRING); }
@Test public void testKeyPairEquals() throws Exception { assertThat( ComparatorKeyring.compare( new PGPKeyPair( mockPublicKey(false, false), mockPrivateKey(false, false, false, false)), new PGPKeyPair( mockPublicKey(false, false), mockPrivateKey(false, false, false, false)))) .isTrue(); }
@Test public void testKeyPairDifferPublicKey_notEqual() throws Exception { assertThat( ComparatorKeyring.compare( new PGPKeyPair( mockPublicKey(false, false), mockPrivateKey(false, false, false, false)), new PGPKeyPair( mockPublicKey(true, false), mockPrivateKey(false, false, false, false)))) .isFalse(); }
@Test public void testKeyPairDifferPrivateKey_notEqual() throws Exception { assertThat( ComparatorKeyring.compare( new PGPKeyPair( mockPublicKey(false, false), mockPrivateKey(false, false, false, false)), new PGPKeyPair( mockPublicKey(false, false), mockPrivateKey(true, false, false, false)))) .isFalse(); }
@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()).isSameAs(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)); }
public SecretKey generateKeyPair(final String id, final char[] pass) throws CryptoException { try { // This object generates individual key-pairs. final RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 2048, 12)); // First create the master (signing) key with the generator. final PGPKeyPair keyPair = new BcPGPKeyPair(PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date()); // Add a self-signature on the id final PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator(); signhashgen.setKeyFlags(true, KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA | KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); signhashgen.setPreferredCompressionAlgorithms(false, new int[] { CompressionAlgorithmTags.ZIP }); signhashgen.setPreferredHashAlgorithms(false, new int[] { HashAlgorithmTags.SHA1 }); signhashgen.setPreferredSymmetricAlgorithms(false, new int[] { SymmetricKeyAlgorithmTags.AES_256 }); signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION); // Create a signature on the encryption subkey. final PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator(); enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); // Objects used to encrypt the secret key. // Finally, create the keyring itself. The constructor // takes parameters that allow it to generate the self // signature. final PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); final PBESecretKeyEncryptor secretKeyEncryptor = new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_128, sha1Calc).build(pass); final BcPGPContentSignerBuilder contentSigner = new BcPGPContentSignerBuilder(keyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1); final PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, keyPair, id, sha1Calc, signhashgen.generate(), null, contentSigner, secretKeyEncryptor); // return new SimpleKeyPair(new BcPGPPublicKey(publicKeyRing.getPublicKey()), return new BcPGPSecretKey(keyRingGen.generateSecretKeyRing().getSecretKey()); } catch (final Exception e) { throw new CryptoException(e); } }
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; }
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); } }
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); } }
public final static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass, int s2kcount, KeyGenPane.BackgroundTask bgt) throws Exception { // This object generates individual key-pairs. RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); // Boilerplate RSA parameters, no need to change anything // except for the RSA key-size (2048). You can use whatever key-size // makes sense for you -- 4096, etc. kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 2048, 12)); bgt.setProgressPub(10); // First create the master (signing) key with the generator. PGPKeyPair rsakp_sign = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, kpg.generateKeyPair(), new Date()); // Then an encryption subkey. PGPKeyPair rsakp_enc = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, kpg.generateKeyPair(), new Date()); bgt.setProgressPub(50); // Add a self-signature on the id PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator(); bgt.setProgressPub(55); // Add signed metadata on the signature. // 1) Declare its purpose signhashgen.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER); bgt.setProgressPub(60); // 2) Set preferences for secondary crypto algorithms to use when // sending messages to this key. signhashgen.setPreferredSymmetricAlgorithms(false, new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 }); signhashgen.setPreferredHashAlgorithms(false, new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224, }); // 3) Request senders add additional checksums to the message (useful // when verifying unsigned messages.) signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION); // Create a signature on the encryption subkey. PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator(); // Add metadata to declare its purpose enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); // Objects used to encrypt the secret key. PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); PGPDigestCalculator sha256Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA256); bgt.setProgressPub(70); // bcpg 1.48 exposes this API that includes s2kcount. Earlier versions // use a default of 0x60. PBESecretKeyEncryptor pske = (new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha256Calc, s2kcount)).build(pass); // Finally, create the keyring itself. The constructor takes parameters // that allow it to generate the self signature. PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign, id, sha1Calc, signhashgen.generate(), null, new BcPGPContentSignerBuilder(rsakp_sign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1), pske); bgt.setProgressPub(80); // Add our encryption subkey, together with its signature. keyRingGen.addSubKey(rsakp_enc, enchashgen.generate(), null); bgt.setProgressPub(90); return keyRingGen; }
static PGPKeyRingGenerator generateKeyRingGenerator(String userId, int numBits, char[] passphrase) throws Exception { RSAKeyPairGenerator keyPairGenerator = new RSAKeyPairGenerator(); keyPairGenerator.init( new RSAKeyGenerationParameters( BigInteger.valueOf(0x10001), new SecureRandom(), numBits, 12 ) ); PGPKeyPair rsaKeyPairSign = new BcPGPKeyPair( PGPPublicKey.RSA_SIGN, keyPairGenerator.generateKeyPair(), new Date() ); PGPKeyPair rsaKeyPairEncrypt = new BcPGPKeyPair( PGPPublicKey.RSA_ENCRYPT, keyPairGenerator.generateKeyPair(), new Date() ); PGPSignatureSubpacketGenerator signHashGenerator = new PGPSignatureSubpacketGenerator(); signHashGenerator.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER); signHashGenerator.setPreferredSymmetricAlgorithms( false, new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 } ); signHashGenerator.setPreferredHashAlgorithms( false, new int[] { HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, // Not recommended HashAlgorithmTags.SHA224, // Not recommended } ); signHashGenerator.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION); PGPSignatureSubpacketGenerator encryptHashGenerator = new PGPSignatureSubpacketGenerator(); encryptHashGenerator.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); PGPDigestCalculator sha1DigestCalculator = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); PGPDigestCalculator sha512DigestCalculator = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA512); PBESecretKeyEncryptor secretKeyEncryptor = ( new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha512DigestCalculator) ) .build(passphrase); PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator( PGPSignature.NO_CERTIFICATION, rsaKeyPairSign, userId, sha1DigestCalculator, signHashGenerator.generate(), null, new BcPGPContentSignerBuilder(rsaKeyPairSign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA512), secretKeyEncryptor ); keyRingGen.addSubKey(rsaKeyPairEncrypt, encryptHashGenerator.generate(), null); return keyRingGen; }
public void generateTest() throws Exception { char[] passPhrase = "hello".toCharArray(); DSAParametersGenerator dsaPGen = new DSAParametersGenerator(); dsaPGen.init(512, 10, new SecureRandom()); DSAKeyPairGenerator dsaKpg = new DSAKeyPairGenerator(); dsaKpg.init(new DSAKeyGenerationParameters(new SecureRandom(), dsaPGen.generateParameters())); // // this takes a while as the key generator has to generate some DSA params // before it generates the key. // AsymmetricCipherKeyPair dsaKp = dsaKpg.generateKeyPair(); ElGamalKeyPairGenerator elgKpg = new ElGamalKeyPairGenerator(); BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); elgKpg.init(new ElGamalKeyGenerationParameters(new SecureRandom(), elParams)); // // this is quicker because we are using pregenerated parameters. // AsymmetricCipherKeyPair elgKp = elgKpg.generateKeyPair(); PGPKeyPair dsaKeyPair = new BcPGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date()); PGPKeyPair elgKeyPair = new BcPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date()); PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair, "test", null, null, null, new BcPGPContentSignerBuilder(PGPPublicKey.DSA, HashAlgorithmTags.SHA1), new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256).build(passPhrase)); keyRingGen.addSubKey(elgKeyPair); PGPSecretKeyRing keyRing = keyRingGen.generateSecretKeyRing(); keyRing.getSecretKey().extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(passPhrase)); PGPPublicKeyRing pubRing = keyRingGen.generatePublicKeyRing(); PGPPublicKey vKey = null; PGPPublicKey sKey = null; Iterator it = pubRing.getPublicKeys(); while (it.hasNext()) { PGPPublicKey pk = (PGPPublicKey)it.next(); if (pk.isMasterKey()) { vKey = pk; } else { sKey = pk; } } Iterator sIt = sKey.getSignatures(); while (sIt.hasNext()) { PGPSignature sig = (PGPSignature)sIt.next(); if (sig.getKeyID() == vKey.getKeyID() && sig.getSignatureType() == PGPSignature.SUBKEY_BINDING) { sig.init(new BcPGPContentVerifierBuilderProvider(), vKey); if (!sig.verifyCertification(vKey, sKey)) { fail("failed to verify sub-key signature."); } } } }
public void generateSha1Test() throws Exception { char[] passPhrase = "hello".toCharArray(); DSAParametersGenerator dsaPGen = new DSAParametersGenerator(); dsaPGen.init(512, 10, new SecureRandom()); DSAKeyPairGenerator dsaKpg = new DSAKeyPairGenerator(); dsaKpg.init(new DSAKeyGenerationParameters(new SecureRandom(), dsaPGen.generateParameters())); // // this takes a while as the key generator has to generate some DSA params // before it generates the key. // AsymmetricCipherKeyPair dsaKp = dsaKpg.generateKeyPair(); ElGamalKeyPairGenerator elgKpg = new ElGamalKeyPairGenerator(); BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); elgKpg.init(new ElGamalKeyGenerationParameters(new SecureRandom(), elParams)); // // this is quicker because we are using pregenerated parameters. // AsymmetricCipherKeyPair elgKp = elgKpg.generateKeyPair(); PGPKeyPair dsaKeyPair = new BcPGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date()); PGPKeyPair elgKeyPair = new BcPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date()); PGPDigestCalculator chkSumCalc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair, "test", chkSumCalc, null, null, new BcPGPContentSignerBuilder(PGPPublicKey.DSA, HashAlgorithmTags.SHA1), new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256).build(passPhrase)); keyRingGen.addSubKey(elgKeyPair); PGPSecretKeyRing keyRing = keyRingGen.generateSecretKeyRing(); keyRing.getSecretKey().extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(passPhrase)); PGPPublicKeyRing pubRing = keyRingGen.generatePublicKeyRing(); PGPPublicKey vKey = null; PGPPublicKey sKey = null; Iterator it = pubRing.getPublicKeys(); while (it.hasNext()) { PGPPublicKey pk = (PGPPublicKey)it.next(); if (pk.isMasterKey()) { vKey = pk; } else { sKey = pk; } } Iterator sIt = sKey.getSignatures(); while (sIt.hasNext()) { PGPSignature sig = (PGPSignature)sIt.next(); if (sig.getKeyID() == vKey.getKeyID() && sig.getSignatureType() == PGPSignature.SUBKEY_BINDING) { sig.init(new BcPGPContentVerifierBuilderProvider(), vKey); if (!sig.verifyCertification(vKey, sKey)) { fail("failed to verify sub-key signature."); } } } }
private static PGPKeyRingGenerator generateKeyRingGenerator( String id, char[] pass, int s2kcount, int keySize, KeyPair keyPair ) throws PGPException { // This object generates individual key-pairs. RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); // Boilerplate RSA parameters, no need to change anything // except for the RSA key-size (2048). You can use whatever // key-size makes sense for you -- 4096, etc. kpg.init( new RSAKeyGenerationParameters( BigInteger.valueOf( 0x10001 ), new SecureRandom(), keySize, 12 ) ); // First create the master (signing) key with the generator. PGPKeyPair rsakp_sign = new BcPGPKeyPair( PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date() ); // Then an encryption subkey. PGPKeyPair rsakp_enc = new BcPGPKeyPair( PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date() ); keyPair.setPrimaryKeyId( Long.toHexString( rsakp_sign.getKeyID() ) ); keyPair.setPrimaryKeyFingerprint( BytesToHex( rsakp_sign.getPublicKey().getFingerprint() ) ); keyPair.setSubKeyId( Long.toHexString( rsakp_enc.getKeyID() ) ); keyPair.setSubKeyFingerprint( BytesToHex( rsakp_enc.getPublicKey().getFingerprint() ) ); // Add a self-signature on the id PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator(); // Add signed metadata on the signature. // 1) Declare its purpose signhashgen.setKeyFlags( false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER ); // 2) Set preferences for secondary crypto algorithms to use // when sending messages to this key. signhashgen.setPreferredSymmetricAlgorithms( false, new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128, SymmetricKeyAlgorithmTags.CAST5, SymmetricKeyAlgorithmTags.TRIPLE_DES } ); signhashgen.setPreferredHashAlgorithms( false, new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224, } ); signhashgen.setPreferredCompressionAlgorithms( false, new int[] { CompressionAlgorithmTags.ZLIB, CompressionAlgorithmTags.BZIP2, CompressionAlgorithmTags.ZIP } ); // 3) Request senders add additional checksums to the // message (useful when verifying unsigned messages.) signhashgen.setFeature( false, Features.FEATURE_MODIFICATION_DETECTION ); // Create a signature on the encryption subkey. PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator(); // Add metadata to declare its purpose enchashgen.setKeyFlags( false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE ); // Objects used to encrypt the secret key. PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get( HashAlgorithmTags.SHA1 ); // bcpg 1.48 exposes this API that includes s2kcount. Earlier // versions use a default of 0x60. PBESecretKeyEncryptor pske = ( new BcPBESecretKeyEncryptorBuilder( PGPEncryptedData.CAST5, sha1Calc, s2kcount ) ).build( pass ); // Finally, create the keyring itself. The constructor // takes parameters that allow it to generate the self // signature. PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator( PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign, id, sha1Calc, signhashgen.generate(), null, new BcPGPContentSignerBuilder( rsakp_sign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1 ), pske ); // Add our encryption subkey, together with its signature. keyRingGen.addSubKey( rsakp_enc, enchashgen.generate(), null ); return keyRingGen; }
@Override public void run() throws Exception { OutputStream out = outputPath != null ? new FileOutputStream(outputPath.toFile()) : System.out; Security.addProvider(new BouncyCastleProvider()); switch (keyringKeyName) { case BRAINTREE_PRIVATE_KEY: out.write(KeySerializer.serializeString(keyring.getBraintreePrivateKey())); break; case BRDA_RECEIVER_PUBLIC_KEY: out.write(KeySerializer.serializePublicKey(keyring.getBrdaReceiverKey())); break; case BRDA_SIGNING_KEY_PAIR: out.write(KeySerializer.serializeKeyPair(keyring.getBrdaSigningKey())); break; case BRDA_SIGNING_PUBLIC_KEY: out.write(KeySerializer.serializePublicKey(keyring.getBrdaSigningKey().getPublicKey())); break; case ICANN_REPORTING_PASSWORD: out.write(KeySerializer.serializeString(keyring.getIcannReportingPassword())); break; case JSON_CREDENTIAL: out.write(KeySerializer.serializeString(keyring.getJsonCredential())); break; case MARKSDB_DNL_LOGIN: out.write(KeySerializer.serializeString(keyring.getMarksdbDnlLogin())); break; case MARKSDB_LORDN_PASSWORD: out.write(KeySerializer.serializeString(keyring.getMarksdbLordnPassword())); break; case MARKSDB_SMDRL_LOGIN: out.write(KeySerializer.serializeString(keyring.getMarksdbSmdrlLogin())); break; case RDE_RECEIVER_PUBLIC_KEY: out.write(KeySerializer.serializePublicKey(keyring.getRdeReceiverKey())); break; case RDE_SIGNING_KEY_PAIR: out.write(KeySerializer.serializeKeyPair(keyring.getRdeSigningKey())); break; case RDE_SIGNING_PUBLIC_KEY: out.write(KeySerializer.serializePublicKey(keyring.getRdeSigningKey().getPublicKey())); break; case RDE_SSH_CLIENT_PRIVATE_KEY: out.write(KeySerializer.serializeString(keyring.getRdeSshClientPrivateKey())); break; case RDE_SSH_CLIENT_PUBLIC_KEY: out.write(KeySerializer.serializeString(keyring.getRdeSshClientPublicKey())); break; case RDE_STAGING_KEY_PAIR: // Note that we're saving a key pair rather than just the private key because we can't // serialize a private key on its own. See {@link KeySerializer}. out.write(KeySerializer.serializeKeyPair( new PGPKeyPair( keyring.getRdeStagingEncryptionKey(), keyring.getRdeStagingDecryptionKey()))); break; case RDE_STAGING_PUBLIC_KEY: out.write(KeySerializer.serializePublicKey(keyring.getRdeStagingEncryptionKey())); break; } }
public KmsUpdater setRdeSigningKey(PGPKeyPair keyPair) throws IOException, PGPException { return setKeyPair(keyPair, RDE_SIGNING_PRIVATE, RDE_SIGNING_PUBLIC); }