List of usage examples for org.bouncycastle.openpgp PGPSecretKeyRing getSecretKey
public PGPSecretKey getSecretKey()
From source file:de.jtheuer.diki.lib.pgp.PGPHandler.java
License:Open Source License
/** * Creates a new {@link PGPHandler} from already existing PGP keys which are normally loaded from the * file-system using a {@link FileInputStream}. * @param privatekeystream//from www . ja va 2s .c om * @param passphrase * @param identity * @param publickeyring * @throws IOException * @throws PGPException * @throws NoSuchProviderException */ public PGPHandler(InputStream privatekeystream, char[] passphrase, String identity, InputStream publickeyring) throws IOException, PGPException, NoSuchProviderException { this(); PGPSecretKeyRing secretKeyring = new PGPSecretKeyRing(privatekeystream); init(secretKeyring.getSecretKey(), passphrase, identity); if (publickeyring != null) { keyring = new PGPPublicKeyRingCollection(publickeyring); } else { keyring = new PGPPublicKeyRingCollection(new LinkedList<PGPPublicKey>()); } }
From source file:dorkbox.util.crypto.CryptoPGP.java
License:Apache License
/** * Find private gpg key in InputStream, also closes the input stream * * @param inputStream/* w w w. j a v a 2 s . c o m*/ * the inputStream that contains the private (secret) key * @param userId * the user id * * @return the PGP secret key */ public static List<PGPSecretKey> getSecretKeys(InputStream inputStream, String userId) throws PGPException { // iterate over every private key in the key ring PGPSecretKeyRingCollection secretKeyRings; try { secretKeyRings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(inputStream), fingerprintCalculator); } catch (IOException e) { throw new PGPException("No private key found in stream!", e); } finally { IO.close(inputStream); } // look for the key ring that is used to authenticate our reporting facilities Iterator<PGPSecretKeyRing> secretKeys = secretKeyRings.getKeyRings(userId); List<PGPSecretKey> pgpSecretKeys = new ArrayList<PGPSecretKey>(); // iterate over every private key in the ring while (secretKeys.hasNext()) { PGPSecretKeyRing secretKeyRing = secretKeys.next(); PGPSecretKey tmpKey = secretKeyRing.getSecretKey(); if (tmpKey != null) { pgpSecretKeys.add(tmpKey); } } if (!pgpSecretKeys.isEmpty()) { return pgpSecretKeys; } throw new PGPException("No private key found in stream!"); }
From source file:google.registry.keyring.kms.KmsKeyring.java
License:Open Source License
private PGPPrivateKey getPrivateKey(String privateKeyName) { try {// w w w . ja v a 2s . c o m PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(getPgpInputStream(privateKeyName)); // There shouldn't be a passphrase on the key return privateKeyRing.getSecretKey().extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(new char[0])); } catch (IOException | PGPException e) { throw new KeyringException(String.format("Could not parse private key %s", privateKeyName), e); } }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@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);/* w w w. j a v a 2 s . c o m*/ byte[] signatureFileData = output.toByteArray(); logger.info(".sig file data: " + 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(); }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@Test public void testSignVerify_OnePass() 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". PGPSignatureGenerator signer = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256)); signer.init(PGPSignature.BINARY_DOCUMENT, privateKey); addUserInfoToSignature(publicKey, signer); ByteArrayOutputStream output = new ByteArrayOutputStream(); signer.generateOnePassVersion(false).encode(output); signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); signer.generate().encode(output);/*from w ww.j a v a 2s . c o m*/ byte[] signatureFileData = output.toByteArray(); logger.info(".sig file data: " + dumpHex(signatureFileData)); // Load algorithm information and signature data from "signatureFileData". PGPSignature sig; PGPOnePassSignature onePass; try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPOnePassSignatureList onePassList = (PGPOnePassSignatureList) pgpFact.nextObject(); PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject(); assertThat(onePassList.size()).isEqualTo(1); assertThat(sigList.size()).isEqualTo(1); onePass = onePassList.get(0); sig = sigList.get(0); } // Use "onePass" and "sig" to verify "publicKey" signed the text. onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey); onePass.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); assertThat(onePass.verify(sig)).isTrue(); // Verify that they DIDN'T sign the text "hello monster". onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey); onePass.update("hello monster".getBytes(UTF_8)); assertThat(onePass.verify(sig)).isFalse(); }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@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)); }// ww w . java2 s . c om encryptedData = output.toByteArray(); } logger.info("Encrypted data: " + 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); } } }
From source file:org.apache.camel.converter.crypto.PGPDataFormatUtil.java
License:Apache License
@SuppressWarnings("unchecked") private static PGPSecretKey findSecretKey(InputStream keyringInput, String passphrase, String userId, String provider) throws IOException, PGPException, NoSuchProviderException { PGPSecretKey pgpSecKey = null;//ww w . ja va 2s . co m PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyringInput)); for (Iterator<?> i = pgpSec.getKeyRings(); i.hasNext() && pgpSecKey == null;) { Object data = i.next(); if (data instanceof PGPSecretKeyRing) { PGPSecretKeyRing keyring = (PGPSecretKeyRing) data; PGPSecretKey secKey = keyring.getSecretKey(); if (userId != null) { for (Iterator<String> iterator = secKey.getUserIDs(); iterator.hasNext();) { String keyUserId = iterator.next(); // there can be serveral user IDs! if (keyUserId != null && keyUserId.contains(userId)) { PGPPrivateKey privateKey = secKey .extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(provider) .build(passphrase.toCharArray())); if (privateKey != null) { return secKey; } } } } else { PGPPrivateKey privateKey = secKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder() .setProvider(provider).build(passphrase.toCharArray())); if (privateKey != null) { pgpSecKey = secKey; } } } } return pgpSecKey; }
From source file:org.apache.nifi.processors.standard.util.OpenPGPKeyBasedEncryptor.java
License:Apache License
public static boolean validateKeyring(String provider, String secretKeyringFile, char[] passphrase) throws IOException, PGPException, NoSuchProviderException { try (InputStream fin = Files.newInputStream(Paths.get(secretKeyringFile)); InputStream pin = PGPUtil.getDecoderStream(fin)) { PGPSecretKeyRingCollection pgpsec = new PGPSecretKeyRingCollection(pin); Iterator ringit = pgpsec.getKeyRings(); while (ringit.hasNext()) { PGPSecretKeyRing secretkeyring = (PGPSecretKeyRing) ringit.next(); PGPSecretKey secretkey = secretkeyring.getSecretKey(); secretkey.extractPrivateKey(passphrase, provider); return true; }// ww w . jav a 2s .c o m return false; } }
From source file:org.kontalk.certgen.PGP.java
License:Open Source License
@SuppressWarnings("unchecked") public static PrivateKey convertPrivateKey(byte[] privateKeyData, String passphrase) throws PGPException, IOException { PGPDigestCalculatorProvider sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build(); PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(sha1Calc).setProvider(PGP.PROVIDER) .build(passphrase.toCharArray()); // load the secret key ring KeyFingerPrintCalculator fpr = new BcKeyFingerprintCalculator(); PGPSecretKeyRing secRing = new PGPSecretKeyRing(privateKeyData, fpr); // search and decrypt the master (signing key) // secret keys Iterator<PGPSecretKey> skeys = secRing.getSecretKeys(); while (skeys.hasNext()) { PGPSecretKey key = skeys.next(); PGPSecretKey sec = secRing.getSecretKey(); if (key.isMasterKey()) return convertPrivateKey(sec.extractPrivateKey(decryptor)); }//from w ww. j a v a 2 s .c o m throw new PGPException("no suitable private key found."); }
From source file:org.kontalk.certgen.X509Bridge.java
License:Open Source License
public static X509Certificate createCertificate(byte[] privateKeyData, byte[] publicKeyData, String passphrase, String subjectAltName)/*from ww w. j a v a 2s . c o m*/ throws PGPException, IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException, OperatorCreationException { KeyFingerPrintCalculator fpr = new BcKeyFingerprintCalculator(); PGPSecretKeyRing secRing = new PGPSecretKeyRing(privateKeyData, fpr); PGPPublicKeyRing pubRing = new PGPPublicKeyRing(publicKeyData, fpr); PGPDigestCalculatorProvider sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build(); PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(sha1Calc).setProvider(PGP.PROVIDER) .build(passphrase.toCharArray()); // secret key PGPSecretKey secKey = secRing.getSecretKey(); return createCertificate(pubRing, secKey.extractPrivateKey(decryptor), subjectAltName); }