org.bouncycastle.openpgp.PGPPrivateKey Java Examples
The following examples show how to use
org.bouncycastle.openpgp.PGPPrivateKey.
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: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 6 votes |
/** * *********************************************** */ public static PGPPrivateKey getPrivateKey( final PGPSecretKey secretKey, final String secretPwd ) { Preconditions.checkNotNull( secretKey ); Preconditions.checkNotNull( secretPwd ); try { return secretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ); } catch ( Exception e ) { LOG.error( "Unable to extract key {}: {}", secretKey.getKeyID(), e.getMessage() ); } return null; }
Example #2
Source File: PgpHelper.java From nomulus with Apache License 2.0 | 6 votes |
/** * 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 #3
Source File: ComparatorKeyringTest.java From nomulus with Apache License 2.0 | 6 votes |
private static PGPPrivateKey mockPrivateKey( boolean altId, boolean altBcpgKeyFormat, boolean altBcpgKeyEncoded, boolean altPublicKeyPacketEncoded) throws IOException { String bcpgKeyFormat = altBcpgKeyFormat ? "alternate" : "bcpgFormat"; String bcpgKeyEncoded = altBcpgKeyEncoded ? "alternate" : "bcpgEncoded"; String publicKeyPacketEncoded = altPublicKeyPacketEncoded ? "alternate" : "packetEncoded"; BCPGKey bcpgKey = mock(BCPGKey.class); PublicKeyPacket publicKeyPacket = mock(PublicKeyPacket.class); when(bcpgKey.getFormat()).thenReturn(bcpgKeyFormat); when(bcpgKey.getEncoded()).thenReturn(bcpgKeyEncoded.getBytes(UTF_8)); when(publicKeyPacket.getEncoded()).thenReturn(publicKeyPacketEncoded.getBytes(UTF_8)); return new PGPPrivateKey(altId ? 2 : 1, publicKeyPacket, bcpgKey); }
Example #4
Source File: Ghostryde.java From nomulus with Apache License 2.0 | 6 votes |
/** * Creates a Ghostryde decoder. * * @param input from where to read the encrypted data * @param decryptionKey the decryption key to use */ public static ImprovedInputStream decoder(InputStream input, PGPPrivateKey decryptionKey) { // We use a Closer to handle the stream .close, to make sure it's done correctly. Closer closer = Closer.create(); InputStream decryptionLayer = closer.register(openDecryptor(input, GHOSTRYDE_USE_INTEGRITY_PACKET, decryptionKey)); InputStream decompressor = closer.register(openDecompressor(decryptionLayer)); InputStream fileLayer = closer.register(openPgpFileReader(decompressor)); return new ImprovedInputStream("GhostryderDecoder", fileLayer) { @Override public void onClose() throws IOException { // Close all the streams we opened closer.close(); } }; }
Example #5
Source File: PGPDecrypt.java From peer-os with Apache License 2.0 | 6 votes |
public static byte[] decrypt( byte encData[], PGPPrivateKey privateKey ) throws PGPException, IOException { PGPPublicKeyEncryptedData pgpEncData = getPGPEncryptedData( encData ); InputStream is = getInputStream( privateKey, pgpEncData ); // IMPORTANT: pipe() should be before verify(). Otherwise we get "java.io.EOFException: Unexpected end of ZIP // input stream". byte data[] = pipe( is ); if ( !pgpEncData.verify() ) { throw new PGPDataValidationException( "Data integrity check failed" ); } return data; }
Example #6
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 6 votes |
private static PGPLiteralData asLiteral( final byte[] message, final InputStream secretKeyRing, final String secretPwd ) throws IOException, PGPException { PGPPrivateKey key = null; PGPPublicKeyEncryptedData encrypted = null; final PGPSecretKeyRingCollection keys = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secretKeyRing ), new JcaKeyFingerprintCalculator() ); for ( final Iterator<PGPPublicKeyEncryptedData> i = getEncryptedObjects( message ); ( key == null ) && i.hasNext(); ) { encrypted = i.next(); key = getPrivateKey( keys, encrypted.getKeyID(), secretPwd ); } if ( key == null ) { throw new IllegalArgumentException( "secret key for message not found." ); } final InputStream stream = encrypted .getDataStream( new JcePublicKeyDataDecryptorFactoryBuilder().setProvider( provider ).build( key ) ); return asLiteral( stream ); }
Example #7
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 6 votes |
/** * *********************************************** */ private static PGPPrivateKey getPrivateKey( final PGPSecretKeyRingCollection keys, final long id, final String secretPwd ) { try { final PGPSecretKey key = keys.getSecretKey( id ); if ( key != null ) { return key.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ) .build( secretPwd.toCharArray() ) ); } } catch ( final Exception e ) { // Don't print the passphrase but do print null if thats what it was final String passphraseMessage = ( secretPwd == null ) ? "null" : "supplied"; LOG.warn( "Unable to extract key " + id + " using " + passphraseMessage + " passphrase: {}", e.getMessage() ); } return null; }
Example #8
Source File: AptSigningFacet.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
public byte[] signExternal(final String input) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC")); sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.update(input.getBytes(Charsets.UTF_8)); sigGenerator.generate().encode(bOut); } } catch (PGPException ex) { throw new RuntimeException(ex); } return buffer.toByteArray(); }
Example #9
Source File: EncryptionServicePgpImpl.java From pgptool with GNU General Public License v3.0 | 6 votes |
private PGPPrivateKey getPrivateKey(String passphrase, PGPSecretKey secretKey) throws InvalidPasswordException { try { PBESecretKeyDecryptor decryptorFactory = new BcPBESecretKeyDecryptorBuilder( new BcPGPDigestCalculatorProvider()).build(passphrase.toCharArray()); PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptorFactory); return privateKey; } catch (Throwable t) { log.warn("Failed to extract private key. Most likely it because of incorrect passphrase provided", t); throw new InvalidPasswordException(); } }
Example #10
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 6 votes |
@Theory public void testStreamingApi(Content content) throws Exception { Keyring keyring = new FakeKeyringModule().get(); byte[] data = content.get().getBytes(UTF_8); PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey(); PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey(); ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); try (OutputStream encoder = Ghostryde.encoder(bsOut, publicKey)) { encoder.write(data); } ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray()); bsOut.reset(); try (InputStream decoder = Ghostryde.decoder(bsIn, privateKey)) { ByteStreams.copy(decoder, bsOut); } assertThat(bsOut.size()).isEqualTo(data.length); assertThat(new String(bsOut.toByteArray(), UTF_8)).isEqualTo(content.get()); }
Example #11
Source File: KeySerializerTest.java From nomulus with Apache License 2.0 | 5 votes |
private static PGPPrivateKey extractPrivateKey(PGPSecretKey secretKey, String password) { try { return secretKey.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(password.toCharArray())); } catch (PGPException e) { throw new Error(e); } }
Example #12
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 5 votes |
@Theory public void testFailure_corruption(Content content) throws Exception { assumeThat(content.get().length(), is(lessThan(100))); Keyring keyring = new FakeKeyringModule().get(); PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey(); PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey(); byte[] data = content.get().getBytes(UTF_8); ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); try (OutputStream encoder = Ghostryde.encoder(bsOut, publicKey)) { encoder.write(data); } byte[] ciphertext = bsOut.toByteArray(); korruption(ciphertext, ciphertext.length / 2); ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext); RuntimeException thrown = assertThrows( RuntimeException.class, () -> { try (InputStream decoder = Ghostryde.decoder(bsIn, privateKey)) { ByteStreams.copy(decoder, ByteStreams.nullOutputStream()); } }); assertThat(thrown).hasCauseThat().isInstanceOf(PGPException.class); }
Example #13
Source File: ComparatorKeyring.java From nomulus with Apache License 2.0 | 5 votes |
/** 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); }
Example #14
Source File: ComparatorKeyring.java From nomulus with Apache License 2.0 | 5 votes |
@VisibleForTesting static boolean compare(@Nullable PGPPrivateKey a, @Nullable PGPPrivateKey b) { if (a == null || b == null) { return a == null && b == null; } return a.getKeyID() == b.getKeyID() && compare(a.getPrivateKeyDataPacket(), b.getPrivateKeyDataPacket()) && compare(a.getPublicKeyPacket(), b.getPublicKeyPacket()); }
Example #15
Source File: ComparatorKeyring.java From nomulus with Apache License 2.0 | 5 votes |
/** 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 #16
Source File: ComparatorKeyring.java From nomulus with Apache License 2.0 | 5 votes |
@VisibleForTesting static String stringify(PGPPrivateKey a) { if (a == null) { return "null"; } // We need to be careful what information we output here. The private key should be private, and // I'm not sure what is safe to put in the logs. return MoreObjects.toStringHelper(PGPPrivateKey.class) .add("keyId", a.getKeyID()) .toString(); }
Example #17
Source File: BouncyCastleTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testEncryptDecrypt_ExplicitStyle() throws Exception { int bufferSize = 64 * 1024; // Alice loads Bob's "publicKey" into memory. PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY); PGPPublicKey publicKey = publicKeyRing.getPublicKey(); // Alice encrypts the secret message for Bob using his "publicKey". PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator( new BcPGPDataEncryptorBuilder(AES_128)); encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey)); byte[] encryptedData; try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) { output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); } encryptedData = output.toByteArray(); } logger.atInfo().log("Encrypted data: %s", dumpHex(encryptedData)); // Bob loads his "privateKey" into memory. PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY); PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey()); // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey". try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject(); assertThat(encDataList.size()).isEqualTo(1); PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0); assertThat(encData.getKeyID()).isEqualTo(publicKey.getKeyID()); assertThat(encData.getKeyID()).isEqualTo(privateKey.getKeyID()); try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) { assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8))) .isEqualTo(FALL_OF_HYPERION_A_DREAM); } } }
Example #18
Source File: KmsKeyringTest.java From nomulus with Apache License 2.0 | 5 votes |
@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 #19
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 5 votes |
@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 #20
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 5 votes |
@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 #21
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 5 votes |
@Theory public void testSimpleApi(Content content) throws Exception { Keyring keyring = new FakeKeyringModule().get(); byte[] data = content.get().getBytes(UTF_8); PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey(); PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey(); byte[] blob = Ghostryde.encode(data, publicKey); byte[] result = Ghostryde.decode(blob, privateKey); assertThat(new String(result, UTF_8)).isEqualTo(content.get()); }
Example #22
Source File: GhostrydeTest.java From nomulus with Apache License 2.0 | 5 votes |
@Theory public void testFailure_tampering(Content content) throws Exception { assumeThat(content.get().length(), is(greaterThan(100))); Keyring keyring = new FakeKeyringModule().get(); PGPPublicKey publicKey = keyring.getRdeStagingEncryptionKey(); PGPPrivateKey privateKey = keyring.getRdeStagingDecryptionKey(); byte[] data = content.get().getBytes(UTF_8); ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); try (OutputStream encoder = Ghostryde.encoder(bsOut, publicKey)) { encoder.write(data); } byte[] ciphertext = bsOut.toByteArray(); korruption(ciphertext, ciphertext.length - 1); ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext); IllegalStateException thrown = assertThrows( IllegalStateException.class, () -> { try (InputStream decoder = Ghostryde.decoder(bsIn, privateKey)) { ByteStreams.copy(decoder, ByteStreams.nullOutputStream()); } }); assertThat(thrown).hasMessageThat().contains("tampering"); }
Example #23
Source File: BouncyCastleTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testSignVerify_Detached() throws Exception { // Load the keys. PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY); PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY); PGPPublicKey publicKey = publicKeyRing.getPublicKey(); PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey()); // Sign the data and write signature data to "signatureFile". // Note: RSA_GENERAL will encrypt AND sign. RSA_SIGN and RSA_ENCRYPT are deprecated. PGPSignatureGenerator signer = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256)); signer.init(PGPSignature.BINARY_DOCUMENT, privateKey); addUserInfoToSignature(publicKey, signer); signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); ByteArrayOutputStream output = new ByteArrayOutputStream(); signer.generate().encode(output); byte[] signatureFileData = output.toByteArray(); logger.atInfo().log(".sig file data: %s", dumpHex(signatureFileData)); // Load algorithm information and signature data from "signatureFileData". PGPSignature sig; try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject(); assertThat(sigList.size()).isEqualTo(1); sig = sigList.get(0); } // Use "onePass" and "sig" to verify "publicKey" signed the text. sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey); sig.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); assertThat(sig.verify()).isTrue(); // Verify that they DIDN'T sign the text "hello monster". sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey); sig.update("hello monster".getBytes(UTF_8)); assertThat(sig.verify()).isFalse(); }
Example #24
Source File: AptSigningFacet.java From nexus-repository-apt with Eclipse Public License 1.0 | 5 votes |
public byte[] signInline(String input) throws IOException, PGPException { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC")); sigGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey); @SuppressWarnings("unchecked") Iterator<String> userIds = signKey.getUserIDs(); if (userIds.hasNext()) { PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator(); sigSubpacketGenerator.setSignerUserID(false, userIds.next()); sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate()); } String[] lines = input.split("\r?\n"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { aOut.beginClearText(PGPUtil.SHA256); boolean firstLine = true; for (String line : lines) { String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", ""); sigGenerator.update(sigLine.getBytes(Charsets.UTF_8)); aOut.write((line + "\n").getBytes(Charsets.UTF_8)); firstLine = false; } aOut.endClearText(); BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.generate().encode(bOut); } return buffer.toByteArray(); }
Example #25
Source File: AptSigningFacet.java From nexus-repository-apt with Eclipse Public License 1.0 | 5 votes |
public byte[] signExternal(String input) throws IOException, PGPException { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC")); sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.update(input.getBytes(Charsets.UTF_8)); sigGenerator.generate().encode(bOut); } return buffer.toByteArray(); }
Example #26
Source File: Ghostryde.java From nomulus with Apache License 2.0 | 5 votes |
/** * Deciphers a ghostryde file from an in-memory byte array. */ public static byte[] decode(byte[] data, PGPPrivateKey key) throws IOException, PGPException { checkNotNull(data, "data"); ByteArrayInputStream dataStream = new ByteArrayInputStream(data); ByteArrayOutputStream output = new ByteArrayOutputStream(); try (InputStream ghostrydeDecoder = decoder(dataStream, key)) { ByteStreams.copy(ghostrydeDecoder, output); } return output.toByteArray(); }
Example #27
Source File: AptSigningFacet.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
public byte[] signInline(final String input) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC")); sigGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey); Iterator<String> userIds = signKey.getUserIDs(); if (userIds.hasNext()) { PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator(); sigSubpacketGenerator.setSignerUserID(false, userIds.next()); sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate()); } String[] lines = input.split("\r?\n"); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { aOut.beginClearText(PGPUtil.SHA256); boolean firstLine = true; for (String line : lines) { String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", ""); sigGenerator.update(sigLine.getBytes(Charsets.UTF_8)); aOut.write((line + "\n").getBytes(Charsets.UTF_8)); firstLine = false; } aOut.endClearText(); BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.generate().encode(bOut); } } catch (PGPException ex) { throw new RuntimeException(ex); } return buffer.toByteArray(); }
Example #28
Source File: RpmMojo.java From rpm-builder with Eclipse Public License 2.0 | 5 votes |
private SignatureProcessor makeRsaSigner ( final Signature signature ) throws MojoExecutionException, MojoFailureException { final PGPPrivateKey privateKey = SigningHelper.loadKey ( signature, this.logger ); if ( privateKey == null ) { return null; } return new RsaHeaderSignatureProcessor ( privateKey, HashAlgorithm.from ( signature.getHashAlgorithm () ) ); }
Example #29
Source File: ConfigManager.java From peer-os with Apache License 2.0 | 5 votes |
public ConfigManager( final SecurityManager securityManager, final PeerManager peerManager, final IdentityManager identityManager ) throws BazaarManagerException { try { this.identityManager = identityManager; this.peerManager = peerManager; final PGPPrivateKey sender = securityManager.getKeyManager().getPrivateKey( null ); this.peerId = peerManager.getLocalPeer().getId(); this.bzrPublicKey = PGPKeyHelper.readPublicKey( Common.BAZAAR_PUB_KEY ); this.ownerPublicKey = securityManager.getKeyManager().getPublicKeyRing( securityManager.getKeyManager().getPeerOwnerId() ) .getPublicKey(); this.peerPublicKey = securityManager.getKeyManager().getPublicKey( null ); this.messenger = new PGPMessenger( sender, bzrPublicKey ); final KeyStoreTool keyStoreTool = new KeyStoreTool(); this.keyStore = keyStoreTool.createPeerCertKeystore( Common.PEER_CERT_ALIAS, PGPKeyUtil.getFingerprint( peerPublicKey.getFingerprint() ) ); } catch ( Exception e ) { throw new BazaarManagerException( e ); } }
Example #30
Source File: KeyManagerImpl.java From peer-os with Apache License 2.0 | 5 votes |
@Override public PGPPrivateKey getPrivateKey( String identityId ) { if ( StringUtils.isBlank( identityId ) ) { identityId = keyData.getManHostId(); } try { PGPSecretKey secretKey = getSecretKey( identityId ); if ( secretKey != null ) { return PGPEncryptionUtil.getPrivateKey( secretKey, keyData.getSecretKeyringPwd() ); } else { return null; } } catch ( Exception ex ) { LOG.error( " ***** Error getting Private key:" + ex.toString(), ex ); return null; } }