@ReactMethod public void signData(final String privKeyData, final String password, final String data, Promise promise) { try { // region Decode Private Key PGPSecretKey secKey = PGPUtils.getSecretKey(privKeyData); PGPPrivateKey privKey = PGPUtils.decryptArmoredPrivateKey(secKey, password); // endregion // region Sign Data String signature = PGPUtils.signArmoredAscii(privKey, data, signatureAlgo); WritableMap resultMap = Arguments.createMap(); resultMap.putString("asciiArmoredSignature", signature); resultMap.putString("hashingAlgo", PGPUtils.hashAlgoToString(signatureAlgo)); resultMap.putString("fingerPrint", Utils.bytesToHex(secKey.getPublicKey().getFingerprint())); promise.resolve(resultMap); // endregion } catch (Exception e) { promise.reject(e); } }
@ReactMethod public void signB64Data(final String privKeyData, final String password, final String b64Data, Promise promise) { try { // region Decode Base64 byte[] data = Base64.decode(b64Data, Base64.DEFAULT); // endregion // region Decode Private Key PGPSecretKey secKey = PGPUtils.getSecretKey(privKeyData); PGPPrivateKey privKey = PGPUtils.decryptArmoredPrivateKey(secKey, password); // endregion // region Sign Data String signature = PGPUtils.signArmoredAscii(privKey, data, signatureAlgo); WritableMap resultMap = Arguments.createMap(); resultMap.putString("asciiArmoredSignature", signature); resultMap.putString("hashingAlgo", PGPUtils.hashAlgoToString(signatureAlgo)); resultMap.putString("fingerPrint", Utils.bytesToHex(secKey.getPublicKey().getFingerprint())); promise.resolve(resultMap); // endregion } catch (Exception e) { promise.reject(e); } }
static PGPSecretKey getSecretKey(String privateKeyData) throws IOException, PGPException { PGPPrivateKey privKey = null; try (InputStream privStream = new ArmoredInputStream(new ByteArrayInputStream(privateKeyData.getBytes("UTF-8")))) { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privStream), new JcaKeyFingerprintCalculator()); Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing)keyRingIter.next(); Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey)keyIter.next(); if (key.isSigningKey()) { return key; } } } } throw new IllegalArgumentException("Can't find signing key in key ring."); }
public static PGPSecretKey readSecretKey( PGPSecretKeyRing keyRing ) throws PGPException { try { Iterator keyIter = keyRing.getSecretKeys(); while ( keyIter.hasNext() ) { PGPSecretKey key = ( PGPSecretKey ) keyIter.next(); if ( key.isSigningKey() ) { return key; } } } catch ( Exception e ) { LOG.error( e.getMessage() ); } return null; }
/** * *********************************************** */ 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; }
public static X509Certificate getX509CertificateFromPgpKeyPair( PGPPublicKey pgpPublicKey, PGPSecretKey pgpSecretKey, String secretPwd, String issuer, String subject, Date dateOfIssue, Date dateOfExpiry, BigInteger serial ) throws PGPException, CertificateException, IOException { JcaPGPKeyConverter c = new JcaPGPKeyConverter(); PublicKey publicKey = c.getPublicKey( pgpPublicKey ); PrivateKey privateKey = c.getPrivateKey( pgpSecretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ) ); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( new X500Name( issuer ), serial, dateOfIssue, dateOfExpiry, new X500Name( subject ), SubjectPublicKeyInfo.getInstance( publicKey.getEncoded() ) ); byte[] certBytes = certBuilder.build( new JCESigner( privateKey, "SHA256withRSA" ) ).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance( "X.509" ); return ( X509Certificate ) certificateFactory.generateCertificate( new ByteArrayInputStream( certBytes ) ); }
/** * *********************************************** */ 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; }
@Test public void testSignEncryptAndDecryptVerify() throws Exception { PGPSecretKey signingKey = PGPEncryptionUtil.findSecretKeyByFingerprint( findFile( SECRET_KEYRING ), SECRET_KEY_FINGERPRINT ); PGPPublicKey encryptingKey = PGPEncryptionUtil.findPublicKeyByFingerprint( findFile( PUBLIC_KEYRING ), PUBLIC_KEY_FINGERPRINT ); byte[] signedAndEncryptedMessage = PGPEncryptionUtil.signAndEncrypt( MESSAGE.getBytes(), signingKey, SECRET_PWD, encryptingKey, true ); PGPSecretKey decryptingSecretKey = PGPEncryptionUtil.findSecretKeyByFingerprint( findFile( SECRET_KEYRING ), PGPEncryptionUtil.BytesToHex( encryptingKey.getFingerprint() ) ); byte[] decryptedAndVerifiedMessage = PGPEncryptionUtil .decryptAndVerify( signedAndEncryptedMessage, decryptingSecretKey, SECRET_PWD, signingKey.getPublicKey() ); assertTrue( Arrays.equals( MESSAGE.getBytes(), decryptedAndVerifiedMessage ) ); }
private static PGPSecretKey readSecretKey( InputStream is ) throws IOException, PGPException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( is ), new JcaKeyFingerprintCalculator() ); Iterator keyRingIter = pgpSec.getKeyRings(); while ( keyRingIter.hasNext() ) { PGPSecretKeyRing keyRing = ( PGPSecretKeyRing ) keyRingIter.next(); Iterator keyIter = keyRing.getSecretKeys(); while ( keyIter.hasNext() ) { PGPSecretKey key = ( PGPSecretKey ) keyIter.next(); if ( key.isSigningKey() ) { return key; } } } throw new IllegalArgumentException( "Can't find signing key in key ring." ); }
@Override public PGPSecretKey getSecretKeyByFingerprint( String fingerprint ) { PGPSecretKey secretKey = null; try { ByteArrayInputStream barIn = new ByteArrayInputStream( securityDataService.getSecretKeyData( fingerprint ).getData() ); secretKey = PGPEncryptionUtil.findSecretKeyByFingerprint( barIn, fingerprint ); } catch ( Exception ex ) { LOG.error( " ***** Error getting Secret key:" + ex.toString(), ex ); } return secretKey; }
/** * Signs a public key * * @param publicKeyRing a public key ring containing the single public key to sign * @param id the id we are certifying against the public key * @param secretKey the signing key * @param secretKeyPassword the signing key password * * @return a public key ring with the signed public key */ @Override public PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey, String secretKeyPassword ) { try { if ( Strings.isNullOrEmpty( secretKeyPassword ) ) { secretKeyPassword = keyManager.getSecurityKeyData().getSecretKeyringPwd(); } return PGPEncryptionUtil.signPublicKey( publicKeyRing, id, secretKey, secretKeyPassword ); } catch ( Exception e ) { //throw custom exception throw new ActionFailedException( e ); } }
/** * 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(); } }
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(); }
private PGPSecretKey readSecretKey() throws IOException, PGPException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new ByteArrayInputStream(config.keypair.getBytes())), new JcaKeyFingerprintCalculator()); Iterator<PGPSecretKeyRing> keyRings = pgpSec.getKeyRings(); while (keyRings.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRings.next(); Iterator<PGPSecretKey> keys = keyRing.getSecretKeys(); while (keys.hasNext()) { PGPSecretKey key = (PGPSecretKey) keys.next(); if (key.isSigningKey()) { return key; } } } throw new IllegalStateException("Can't find signing key in key ring."); }
private static boolean isSigningKey(PGPSecretKey secKey) { if (!secKey.isSigningKey()) { return false; } Boolean hasSigningKeyFlag = hasOneOfExpectedKeyFlags(secKey.getPublicKey(), new int[] {KeyFlags.SIGN_DATA }); if (hasSigningKeyFlag != null && !hasSigningKeyFlag) { // not a signing key --> ignore LOG.debug( "Secret key with key ID {} found for specified user ID part. But this key will not be used for signing because of its key flags.", Long.toString(secKey.getKeyID())); return false; } else { // also if there are not any keyflags (hasSigningKeyFlag=null), true is returned! return true; } }
private void createSignature(OutputStream out) throws Exception { PGPSecretKey pgpSec = readSecretKey(); PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(getProvider()).build( "sdude".toCharArray())); PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(getProvider())); sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); BCPGOutputStream bOut = new BCPGOutputStream(out); InputStream fIn = new ByteArrayInputStream("Test Signature".getBytes("UTF-8")); int ch; while ((ch = fIn.read()) >= 0) { sGen.update((byte) ch); } fIn.close(); sGen.generate().encode(bOut); }
static PGPSecretKey readSecretKey() throws Exception { InputStream input = new ByteArrayInputStream(getSecKeyRing()); PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey) keyIter.next(); if (key.isSigningKey()) { return key; } } } throw new IllegalArgumentException("Can't find signing key in key ring."); }
protected void registerKey ( final PGPSecretKey key, final List<String> users ) throws Exception { final String keyId = String.format ( "%016X", key.getKeyID () ); final SigningService service = new ManagedSigningService ( key, this.cfg.getPassphrase () ); final Dictionary<String, Object> properties = new Hashtable<> ( 1 ); properties.put ( Constants.SERVICE_PID, "pgp." + keyId ); final String usersString = users.stream ().collect ( Collectors.joining ( "; " ) ); if ( !users.isEmpty () ) { properties.put ( Constants.SERVICE_DESCRIPTION, String.format ( "Managed PGP key (%s) %s: %s", keyId, !key.isMasterKey () ? "(sub)" : "", usersString ) ); } else { properties.put ( Constants.SERVICE_DESCRIPTION, String.format ( "Managed PGP key (%s) %s", keyId, !key.isMasterKey () ? "(sub)" : "" ) ); } this.regs.add ( this.context.registerService ( SigningService.class, service, properties ) ); }
public static Predicate<PGPSecretKey> keyShortId ( final String keyId ) { final long keyIdNum = Long.parseUnsignedLong ( keyId, 16 ); return new Predicate<PGPSecretKey> () { @Override public boolean test ( final PGPSecretKey key ) { final long shortId = key.getKeyID () & 0xFFFFFFFFL; if ( key.getKeyID () != keyIdNum && shortId != keyIdNum ) { return false; } return true; } }; }
@Override public boolean testPassphrase(final PgpKey pgpKey, final char[] passphrase) throws IllegalArgumentException { assertNotNull(pgpKey, "pgpKey"); assertNotNull(passphrase, "passphrase"); // empty for no passphrase! never null! final BcPgpKey bcPgpKey = getBcPgpKeyOrFail(pgpKey); final PGPSecretKey secretKey = bcPgpKey.getSecretKey(); if (secretKey == null) throw new IllegalArgumentException("pgpKey has no secret key!"); try { // secretKey.extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(passphrase)); extractPrivateKey(secretKey, passphrase); return true; } catch (PGPException e) { logger.debug("testPassphrase: " + e, e); return false; } }
@Override public PgpKey createPgpKey(final CreatePgpKeyParam createPgpKeyParam) { assertNotNull(createPgpKeyParam, "createPgpKeyParam"); try { final Pair<PGPPublicKeyRing, PGPSecretKeyRing> pair = createPGPSecretKeyRing(createPgpKeyParam); final PGPPublicKeyRing pgpPublicKeyRing = pair.a; final PGPSecretKeyRing pgpSecretKeyRing = pair.b; final ImportKeysResult importKeysResult = new ImportKeysResult(); synchronized (this) { importPublicKeyRing(importKeysResult, pgpPublicKeyRing); importSecretKeyRing(importKeysResult, pgpSecretKeyRing); } final PGPSecretKey secretKey = pgpSecretKeyRing.getSecretKey(); final PgpKey pgpKey = getPgpKey(new PgpKeyId(secretKey.getKeyID())); assertNotNull(pgpKey, "pgpKey"); return pgpKey; } catch (IOException | NoSuchAlgorithmException | PGPException e) { throw new RuntimeException(e); } }
public OpenPGPSecretKey(String keyId, InputStream secretKeyRing, char[] password) throws IOException { PGPObjectFactory pgpObjectFactory = new BcPGPObjectFactory(PGPUtil.getDecoderStream(secretKeyRing)); for (Object it = pgpObjectFactory.nextObject(); it != null; it = pgpObjectFactory.nextObject()) { PGPSecretKeyRing pgpSecretKeyRing = (PGPSecretKeyRing) it; PGPSecretKey pgpSecretKey = pgpSecretKeyRing.getSecretKey(); if (keyId == null || keyId.isEmpty() || Long.valueOf(keyId, 16) == (pgpSecretKey.getKeyID() & MASK)) { this.secretKey = pgpSecretKey; break; } } // sanity check if (secretKey == null) { throw new IllegalArgumentException("Secret key " + keyId + " not found"); } this.password = password; }
private static PGPSecretKey readSecretKey(InputStream input, String keyId) throws IOException, PGPException { for (@SuppressWarnings("unchecked") Iterator<PGPSecretKeyRing> keyRingIter = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(input)).getKeyRings(); keyRingIter .hasNext();) { for (@SuppressWarnings("unchecked") Iterator<PGPSecretKey> keyIter = keyRingIter.next().getSecretKeys(); keyIter .hasNext();) { PGPSecretKey key = keyIter.next(); String id = bytArrayToHex(key.getPublicKey().getFingerprint()); if ((keyId == null || keyId.equalsIgnoreCase(id.substring(id .length() - 8))) && key.isSigningKey()) { return key; } } } throw new IllegalArgumentException("No signing key in keyring"); }
private static PGPPrivateKey extractPrivateKey(PGPSecretKey pgpSecKey, char[] passPhrase) throws PGPException { PGPPrivateKey privateKey = null; BcPGPDigestCalculatorProvider calculatorProvider = new BcPGPDigestCalculatorProvider(); BcPBESecretKeyDecryptorBuilder secretKeyDecryptorBuilder = new BcPBESecretKeyDecryptorBuilder( calculatorProvider); PBESecretKeyDecryptor pBESecretKeyDecryptor = secretKeyDecryptorBuilder.build(passPhrase); try { privateKey = pgpSecKey.extractPrivateKey(pBESecretKeyDecryptor); } catch (PGPException e) { throw new PGPException("invalid privateKey passPhrase: " + String.valueOf(passPhrase), e); } return privateKey; }
private PGPPrivateKey createPrivateKey(PGPSecretKey secretKey, String password) { try { PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray()); return secretKey.extractPrivateKey(decryptor); } catch (PGPException e) { throw new UncheckedException(e); } }
public PGPSecretKey readSecretKey(final String keyId, final File file) { InputStream inputStream = openSecretKeyFile(file); try { return readSecretKey(inputStream, keyId, "file: " + file.getAbsolutePath()); } finally { uncheckedClose(inputStream); } }
protected PGPSecretKey readSecretKey(PGPSecretKeyRingCollection keyRings, final PgpKeyId keyId, String sourceDescription) { PGPSecretKey key = findSecretKey(keyRings, keyId); if (key == null) { throw new InvalidUserDataException("did not find secret key for id \'" + String.valueOf(keyId) + "\' in key source \'" + sourceDescription + "\'"); } return key; }
@Nullable private PGPSecretKey findSecretKey(PGPSecretKeyRingCollection keyRings, PgpKeyId keyId) { Iterator<PGPSecretKeyRing> keyRingIterator = uncheckedCast(keyRings.getKeyRings()); while (keyRingIterator.hasNext()) { PGPSecretKeyRing keyRing = keyRingIterator.next(); Iterator<PGPSecretKey> secretKeyIterator = uncheckedCast(keyRing.getSecretKeys()); while (secretKeyIterator.hasNext()) { PGPSecretKey secretKey = secretKeyIterator.next(); if (hasId(keyId, secretKey)) { return secretKey; } } } return null; }
public static PGPSecretKey readSecretKey(InputStream in) throws IOException, PGPException { in = PGPUtil.getDecoderStream(in); PGPSecretKeyRingCollection keyRingCollection = new PGPSecretKeyRingCollection(in, new JcaKeyFingerprintCalculator()); // // We just loop through the collection till we find a key suitable for signing. // In the real world you would probably want to be a bit smarter about this. // PGPSecretKey secretKey = null; Iterator<PGPSecretKeyRing> rIt = keyRingCollection.getKeyRings(); while (secretKey == null && rIt.hasNext()) { PGPSecretKeyRing keyRing = rIt.next(); Iterator<PGPSecretKey> kIt = keyRing.getSecretKeys(); while (secretKey == null && kIt.hasNext()) { PGPSecretKey key = kIt.next(); if (key.isSigningKey()) { secretKey = key; } } } // Validate secret key if (secretKey == null) { throw new IllegalArgumentException("Can't find private key in the key ring."); } if (!secretKey.isSigningKey()) { throw new IllegalArgumentException("Private key does not allow signing."); } if (secretKey.getPublicKey().isRevoked()) { throw new IllegalArgumentException("Private key has been revoked."); } return secretKey; }
static PGPSecretKey readSecretKey(String fileName) throws IOException, PGPException { InputStream keyIn = new BufferedInputStream(new FileInputStream(fileName)); PGPSecretKey secKey = readSecretKey(keyIn); keyIn.close(); return secKey; }
/** * A simple routine that opens a key ring file and loads the first available * key suitable for signature generation. * * @param input * stream to read the secret key ring collection from. * @return a secret key. * @throws IOException * on a problem with using the input stream. * @throws PGPException * if there is an issue parsing the input stream. */ static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for // encryption, in the real // world you would probably want to be a bit smarter about this. // Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey) keyIter.next(); if (key.isSigningKey()) { return key; } } } throw new IllegalArgumentException("Can't find signing key in key ring."); }
public static PGPSecretKey readSecretKey(InputStream in) throws IOException, PGPException, NoSuchProviderException { // Get the decoder stream (auto-disarming) in = PGPUtil.getDecoderStream(in); // Open the key ring PGPSecretKeyRingCollection coll = new PGPSecretKeyRingCollection(in); // Find key return readSecretKey(coll); }
public static PGPPrivateKey readPrivateKey(PGPSecretKey secret, char[] pass) throws PGPException, NoSuchProviderException { PGPPrivateKey key = null; try { key = secret.extractPrivateKey(pass, PGPInit.PROVIDER.getName()); } catch (PGPException pgpe) { if (pgpe.getMessage().indexOf("checksum mismatch") >= 0) { throw new PGPException("Private key password invalid"); } else { throw pgpe; } } return key; }
public static String getKeyInfo(PGPSecretKeyRingCollection coll) { StringBuffer info = new StringBuffer(); // Iterate through key rings Iterator<?> rings = coll.getKeyRings(); while (rings.hasNext()) { PGPSecretKeyRing ring = (PGPSecretKeyRing)rings.next(); Iterator<?> keys = ring.getSecretKeys(); while (keys.hasNext()) { info.append(getKeyInfo((PGPSecretKey)keys.next())).append("\n"); } } return info.toString(); }
/** * Returns information on a secret key * @param secret A PGP secret key * @return Key information */ public static String getKeyInfo(PGPSecretKey secret) { StringBuffer info = new StringBuffer(PGPInit.getKeyExchangeAlgorithm(secret.getPublicKey().getAlgorithm())) .append(" (").append(secret.getPublicKey().getBitStrength()).append(")") .append(" id:").append(secret.getKeyID()); if (secret.isMasterKey()) { info.append(" [").append("master").append("]"); } if (secret.isSigningKey()) { info.append(" [").append("signer").append("]"); } return info.toString(); }
static public void addPrivateKeyToKeyring(final String gpgHomeDirectory, final String keyringFile) throws FileNotFoundException, IOException, PGPException { Security.addProvider(new BouncyCastleProvider()); // Read user secret keyring FileInputStream inPriv = new FileInputStream(gpgHomeDirectory + "/secring.gpg"); PGPSecretKeyRingCollection privRings = new PGPSecretKeyRingCollection(inPriv, new JcaKeyFingerprintCalculator()); // Read keys (public and private) from armored file PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(keyringFile)), new JcaKeyFingerprintCalculator()); // Iterate over the keys Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); privRings = PGPSecretKeyRingCollection.addSecretKeyRing(privRings, keyRing); Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey) keyIter.next(); if (key.isSigningKey()) { System.out.println("Private key imported " + Long.toHexString(key.getKeyID()).toUpperCase()); } } } try (FileOutputStream out = new FileOutputStream(new File(gpgHomeDirectory + "/secring.gpg"))) { privRings.encode(out); } }
protected Key newKey(PGPSecretKeyRing ring) throws PGPException { ArrayList<Subkey> subkeys = new ArrayList<Subkey>(); Iterator<PGPSecretKey> i = ring.iterator(); while (i.hasNext()) subkeys.add(newSubkey(i.next())); return newKey(subkeys); }
private void rewrapTest() throws Exception { SecureRandom rand = new SecureRandom(); // Read the secret key rings PGPSecretKeyRingCollection privRings = new PGPSecretKeyRingCollection( new ByteArrayInputStream(rewrapKey), new BcKeyFingerprintCalculator()); Iterator rIt = privRings.getKeyRings(); if (rIt.hasNext()) { PGPSecretKeyRing pgpPriv = (PGPSecretKeyRing)rIt.next(); Iterator it = pgpPriv.getSecretKeys(); while (it.hasNext()) { PGPSecretKey pgpKey = (PGPSecretKey)it.next(); // re-encrypt the key with an empty password pgpPriv = PGPSecretKeyRing.removeSecretKey(pgpPriv, pgpKey); pgpKey = PGPSecretKey.copyWithNewPassword( pgpKey, new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(rewrapPass), null); pgpPriv = PGPSecretKeyRing.insertSecretKey(pgpPriv, pgpKey); // this should succeed PGPPrivateKey privTmp = pgpKey.extractPrivateKey(null); } } }