/** * 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); }
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); } }
/** * Builds a secret key decryptor for the specified passphrase. */ protected PBESecretKeyDecryptor buildDecryptor(String passphrase) { char[] chars = !Util.isEmpty(passphrase) ? passphrase.toCharArray() : new char[0]; return new BcPBESecretKeyDecryptorBuilder( new BcPGPDigestCalculatorProvider()).build(chars); }
/** * Builds a PublicKeyKeyEncryptionMethodGenerator * for the specified key. */ protected PBEKeyEncryptionMethodGenerator buildSymmetricKeyEncryptor() throws PGPException { if (log.isLoggable(Level.INFO)) log.info("using symmetric encryption with " + keyDerivationAlgorithm + " hash, work factor " + keyDerivationWorkFactor); int algo = keyDerivationAlgorithm.ordinal(); return new BcPBEKeyEncryptionMethodGenerator( symmetricPassphrase.toCharArray(), new BcPGPDigestCalculatorProvider().get(algo), keyDerivationWorkFactor); }
/** * Builds a symmetric-key decryptor for the specified passphrase. */ protected PBEDataDecryptorFactory buildSymmetricKeyDecryptor( String passphrase) { char[] chars = !Util.isEmpty(passphrase) ? passphrase.toCharArray() : new char[0]; return new BcPBEDataDecryptorFactory(chars, new BcPGPDigestCalculatorProvider()); }
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); } } }
BcPrivateKey(String armoredKeyString, char[] passphrase) throws PGPKeyInitialisationException { try { PGPSecretKeyRing secKeyRing = new PGPSecretKeyRing( new ArmoredInputStream(new ByteArrayInputStream(armoredKeyString.getBytes(StandardCharsets.US_ASCII))), new BcKeyFingerprintCalculator()); PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(passphrase); ImmutableMap.Builder<Long, PGPPrivateKey> builder = ImmutableMap.builder(); List<PGPPublicKey> pubKeys = new ArrayList<>(2); for (Iterator iterator = secKeyRing.getSecretKeys(); iterator.hasNext(); ) { PGPSecretKey secretKey = (PGPSecretKey) iterator.next(); PGPPrivateKey privateKey = secretKey.extractPrivateKey(decryptor); builder.put(privateKey.getKeyID(), privateKey); pubKeys.add(secretKey.getPublicKey()); } this.secretKey = secKeyRing.getSecretKey(); this.privateKeys = builder.build(); this.privateKey = this.secretKey.extractPrivateKey(decryptor); if (pubKeys.size() >= 2) { this.publicKey = new BcPublicKey(pubKeys.get(0), pubKeys.get(1)); } else { this.publicKey = new BcPublicKey(pubKeys.get(0), pubKeys.get(0)); } } catch (PGPException | RuntimeException | IOException e) { throw new PGPKeyInitialisationException("Error instantiating a private key", e); } checkNotNull(this.secretKey); checkNotNull(this.privateKey); this.fingerprint = BcPublicKey.hexFingerprint(secretKey.getPublicKey()); }
/** * Get private key using the given passphrase * @param pgpSecKey The secret key * @param pass passphrase to decrypt secret key with * @return Private key * @throws PGPException */ private PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecKey, char[] pass) throws PGPException { if (pgpSecKey == null) return null; PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass); return pgpSecKey.extractPrivateKey(decryptor); }
static PGPKeyPair getKeyPair() throws Exception { PGPSecretKey secretKey = getPrivateKeyring().getSecretKey(); return new PGPKeyPair( secretKey.getPublicKey(), secretKey.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(new char[0]))); }
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); } }
public static PGPPrivateKey loadPrivateKey ( final InputStream input, final String keyId, final char[] passPhrase ) throws IOException, PGPException { final PGPSecretKey secretKey = loadSecretKey ( input, keyId ); if ( secretKey == null ) { return null; } return secretKey.extractPrivateKey ( new BcPBESecretKeyDecryptorBuilder ( new BcPGPDigestCalculatorProvider () ).build ( passPhrase ) ); }
/** * creates and initializes a PGP Key Ring Generator * * @param userId * the user id to use * @param password * the password used for the private key * @param keySize * the key size used for the keys * @return the initialized key ring generator or null if something goes wrong */ private PGPKeyRingGenerator createKeyRingGenerator(String userId, String password, int keySize) { LOGGER.trace("createKeyRingGenerator(String, String, int)"); LOGGER.trace("User ID: {}, Password: {}, Key Size: {}", userId, password == null ? "not set" : "********", keySize); PGPKeyRingGenerator generator = null; try { LOGGER.debug("Creating RSA key pair generator"); RSAKeyPairGenerator generator1 = new RSAKeyPairGenerator(); generator1.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), getSecureRandom(), keySize, 12)); LOGGER.debug("Generating Signing Key Pair"); BcPGPKeyPair signingKeyPair = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, generator1.generateKeyPair(), new Date()); LOGGER.debug("Generating Encyption Key Pair"); BcPGPKeyPair encryptionKeyPair = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, generator1.generateKeyPair(), new Date()); LOGGER.debug("Generating Signature Key Properties"); PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator(); signatureSubpacketGenerator.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER); signatureSubpacketGenerator.setPreferredSymmetricAlgorithms(false, getPreferredEncryptionAlgorithms()); signatureSubpacketGenerator.setPreferredHashAlgorithms(false, getPreferredHashingAlgorithms()); signatureSubpacketGenerator.setPreferredCompressionAlgorithms(false, getPreferredCompressionAlgorithms()); LOGGER.debug("Generating Encyption Key Properties"); PGPSignatureSubpacketGenerator encryptionSubpacketGenerator = new PGPSignatureSubpacketGenerator(); encryptionSubpacketGenerator.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); LOGGER.info("Creating PGP Key Ring Generator"); generator = new PGPKeyRingGenerator(PGPPublicKey.RSA_SIGN, signingKeyPair, userId, new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), signatureSubpacketGenerator.generate(), null, new BcPGPContentSignerBuilder(PGPPublicKey.RSA_SIGN, HashAlgorithmTags.SHA256), new BcPBESecretKeyEncryptorBuilder(getEncryptionAlgorithm()).build(password.toCharArray())); generator.addSubKey(encryptionKeyPair, encryptionSubpacketGenerator.generate(), null); } catch (PGPException e) { LOGGER.error("{}", e.getMessage()); generator = null; } return generator; }
/** * read the private key from the given secret key * * @param pgpSecretKey * the secret key * @param password * the password to unlock the private key * @return the unlocked private key * @throws PGPException */ protected PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecretKey, String password) throws PGPException { LOGGER.trace("findPrivateKey(PGPSecretKey, String)"); LOGGER.trace("Secret Key: {}, Password: {}", pgpSecretKey == null ? "not set" : "set", password == null ? "not set" : "********"); PGPPrivateKey result = null; PBESecretKeyDecryptor pbeSecretKeyDecryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray()); LOGGER.info("Extracting private key"); result = pgpSecretKey.extractPrivateKey(pbeSecretKeyDecryptor); if( result == null && LOGGER.isErrorEnabled() ) { LOGGER.error("No private key could be extracted"); } return result; }
public PGPPrivateKey getPrivateKey() throws PGPException { return getSecretKey() .extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) // All test keys have no passphrase. .build(new char[0])); }
private static PGPPrivateKey findSecretKey( PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass) throws PGPException, NoSuchProviderException { PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID); if (pgpSecKey == null) { return null; } final PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder( new BcPGPDigestCalculatorProvider()).build(pass); return pgpSecKey.extractPrivateKey(decryptor); }
public static PGPPrivateKey findSecretKey(final InputStream keyIn, final long keyID, final char[] pass) throws IOException, PGPException { final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator()); final PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID); if (pgpSecKey == null) return null; final PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass); return pgpSecKey.extractPrivateKey(decryptor); }
private static PGPPrivateKey getPgpPrivateKeyOrFail(final long keyId, final char[] passphrase) throws IOException, PGPException { final PGPSecretKey secretKey = getPgpSecretKeyOrFail(keyId); final PGPDigestCalculatorProvider calculatorProvider = new BcPGPDigestCalculatorProvider(); final BcPBESecretKeyDecryptorBuilder secretKeyDecryptorBuilder = new BcPBESecretKeyDecryptorBuilder(calculatorProvider); final PBESecretKeyDecryptor secretKeyDecryptor = secretKeyDecryptorBuilder.build(passphrase); final PGPPrivateKey privateKey = secretKey.extractPrivateKey(secretKeyDecryptor); return privateKey; }
public PgpSigningService ( final InputStream keyring, final String keyId, final String passphrase ) throws IOException, PGPException { this.secretKey = PgpHelper.loadSecretKey ( keyring, keyId ); if ( this.secretKey == null ) { throw new IllegalStateException ( String.format ( "Signing key '%08X' could not be found", keyId ) ); } this.privateKey = this.secretKey.extractPrivateKey ( new BcPBESecretKeyDecryptorBuilder ( new BcPGPDigestCalculatorProvider () ).build ( passphrase.toCharArray () ) ); }
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 void rewrapTest() throws Exception { SecureRandom rand = new SecureRandom(); // Read the secret key rings PGPSecretKeyRingCollection privRings = new PGPSecretKeyRingCollection( new ByteArrayInputStream(rewrapKey)); 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); } } }
public PGPSigner(InputStream keyring, String keyId, String passphrase, int digest) throws IOException, PGPException { secretKey = getSecretKey(keyring, keyId); if(secretKey == null) { throw new PGPException(String.format("Specified key %s does not exist in key ring %s", keyId, keyring)); } privateKey = secretKey.extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(passphrase.toCharArray())); this.digest = digest; }
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; }
private void embeddedJpegTest() throws Exception { PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(testPubKey, new BcKeyFingerprintCalculator()); PGPSecretKeyRing pgpSec = new PGPSecretKeyRing(testPrivKey, new BcKeyFingerprintCalculator()); PGPPublicKey pubKey = pgpPub.getPublicKey(); PGPUserAttributeSubpacketVectorGenerator vGen = new PGPUserAttributeSubpacketVectorGenerator(); vGen.setImageAttribute(ImageAttribute.JPEG, jpegImage); PGPUserAttributeSubpacketVector uVec = vGen.generate(); PGPSignatureGenerator sGen = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1)); sGen.init(PGPSignature.POSITIVE_CERTIFICATION, pgpSec.getSecretKey().extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass))); PGPSignature sig = sGen.generateCertification(uVec, pubKey); PGPPublicKey nKey = PGPPublicKey.addCertification(pubKey, uVec, sig); Iterator it = nKey.getUserAttributes(); int count = 0; while (it.hasNext()) { PGPUserAttributeSubpacketVector attributes = (PGPUserAttributeSubpacketVector)it.next(); Iterator sigs = nKey.getSignaturesForUserAttribute(attributes); int sigCount = 0; while (sigs.hasNext()) { PGPSignature s = (PGPSignature)sigs.next(); s.init(new BcPGPContentVerifierBuilderProvider(), pubKey); if (!s.verifyCertification(attributes, pubKey)) { fail("added signature failed verification"); } sigCount++; } if (sigCount != 1) { fail("Failed added user attributes signature check"); } count++; } if (count != 1) { fail("didn't find added user attributes"); } nKey = PGPPublicKey.removeCertification(nKey, uVec); count = 0; for (it = nKey.getUserAttributes(); it.hasNext();) { count++; } if (count != 0) { fail("found attributes where none expected"); } }
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."); } } } }
/** * decrypt the passed in message stream */ private byte[] decryptMessage( byte[] message, Date date) throws Exception { PGPObjectFactory pgpF = new BcPGPObjectFactory(message); PGPEncryptedDataList enc = (PGPEncryptedDataList)pgpF.nextObject(); PGPPBEEncryptedData pbe = (PGPPBEEncryptedData)enc.get(0); InputStream clear = pbe.getDataStream(new BcPBEDataDecryptorFactory(pass, new BcPGPDigestCalculatorProvider())); PGPObjectFactory pgpFact = new BcPGPObjectFactory(clear); PGPLiteralData ld = (PGPLiteralData)pgpFact.nextObject(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); if (!ld.getFileName().equals("test.txt") && !ld.getFileName().equals("_CONSOLE")) { fail("wrong filename in packet"); } if (!ld.getModificationTime().equals(date)) { fail("wrong modification time in packet: " + ld.getModificationTime().getTime() + " " + date.getTime()); } InputStream unc = ld.getInputStream(); int ch; while ((ch = unc.read()) >= 0) { bOut.write(ch); } if (pbe.isIntegrityProtected() && !pbe.verify()) { fail("integrity check failed"); } return bOut.toByteArray(); }
private byte[] decryptMessageBuffered( byte[] message, Date date) throws Exception { PGPObjectFactory pgpF = new PGPObjectFactory(message, new BcKeyFingerprintCalculator()); PGPEncryptedDataList enc = (PGPEncryptedDataList)pgpF.nextObject(); PGPPBEEncryptedData pbe = (PGPPBEEncryptedData)enc.get(0); InputStream clear = pbe.getDataStream(new BcPBEDataDecryptorFactory(pass, new BcPGPDigestCalculatorProvider())); PGPObjectFactory pgpFact = new PGPObjectFactory(clear, new BcKeyFingerprintCalculator()); PGPLiteralData ld = (PGPLiteralData)pgpFact.nextObject(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); if (!ld.getFileName().equals("test.txt") && !ld.getFileName().equals("_CONSOLE")) { fail("wrong filename in packet"); } if (!ld.getModificationTime().equals(date)) { fail("wrong modification time in packet: " + ld.getModificationTime().getTime() + " " + date.getTime()); } InputStream unc = ld.getInputStream(); byte[] buf = new byte[1024]; int len; while ((len = unc.read(buf)) >= 0) { bOut.write(buf, 0, len); } if (pbe.isIntegrityProtected() && !pbe.verify()) { fail("integrity check failed"); } return bOut.toByteArray(); }
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; }
private static PBESecretKeyDecryptor createSecretKeyDecryptor() { // There shouldn't be a passphrase on the key return new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(new char[0]); }
private static PGPPrivateKey extractPrivateKey(PGPSecretKey secretKey) throws PGPException { return secretKey.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(PASSWORD)); }
public AbstractSecretKeySigningService ( final PGPSecretKey secretKey, final String passphrase ) throws PGPException { this.secretKey = secretKey; this.privateKey = this.secretKey.extractPrivateKey ( new BcPBESecretKeyDecryptorBuilder ( new BcPGPDigestCalculatorProvider () ).build ( passphrase.toCharArray () ) ); }
private static PGPPrivateKey extractPrivateKey(final PGPSecretKey secretKey, final char[] passphrase) throws PGPException { final PGPPrivateKey privateKey = secretKey.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(passphrase)); return privateKey; }