org.bouncycastle.openpgp.PGPEncryptedData Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPEncryptedData. 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: GPGFileEncryptor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a string cipher name to the integer tag used by GPG
 * @param cipherName the cipher name
 * @return integer tag for the cipher
 */
private static int symmetricKeyAlgorithmNameToTag(String cipherName) {
  // Use CAST5 if no cipher specified
  if (StringUtils.isEmpty(cipherName)) {
    return PGPEncryptedData.CAST5;
  }

  Set<Field> fields = ReflectionUtils.getAllFields(PGPEncryptedData.class, ReflectionUtils.withName(cipherName));

  if (fields.isEmpty()) {
    throw new RuntimeException("Could not find tag for cipher name " + cipherName);
  }

  try {
    return fields.iterator().next().getInt(null);
  } catch (IllegalAccessException e) {
    throw new RuntimeException("Could not access field " + cipherName, e);
  }
}
 
Example #2
Source File: PGPUtils.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
public static PGPSecretKeyRing copySecretKeyRingWithNewPassword(byte[] privateKeyData,
        char[] oldPassphrase, char[] newPassphrase) throws PGPException, IOException, KonException {

    // load the secret key ring
    PGPSecretKeyRing secRing = new PGPSecretKeyRing(privateKeyData, FP_CALC);

    PGPDigestCalculatorProvider calcProv = new JcaPGPDigestCalculatorProviderBuilder().build();
    PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(calcProv)
        .setProvider(PGPUtils.PROVIDER)
        .build(oldPassphrase);

    PGPDigestCalculator calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA256);
    PBESecretKeyEncryptor encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calc)
        .setProvider(PROVIDER).build(newPassphrase);

    try {
        return PGPSecretKeyRing.copyWithNewPassword(secRing, decryptor, encryptor);
    } catch (PGPException ex) {
        // treat this special, cause most like the decryption password was wrong
        throw new KonException(KonException.Error.CHANGE_PASS_COPY, ex);
    }
}
 
Example #3
Source File: OpenPGPPasswordBasedEncryptor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void process(InputStream in, OutputStream out) throws IOException {
    try {
        PGPKeyEncryptionMethodGenerator encryptionMethodGenerator = new JcePBEKeyEncryptionMethodGenerator(password).setProvider(provider);
        org.apache.nifi.processors.standard.util.PGPUtil.encrypt(in, out, algorithm, provider, PGPEncryptedData.AES_128, filename, encryptionMethodGenerator);
    } catch (Exception e) {
        throw new ProcessException(e.getMessage());
    }
}
 
Example #4
Source File: EncryptionServicePgpImpl.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
private static PGPEncryptedDataGenerator buildEncryptedDataGenerator(Collection<PGPPublicKey> encKeys) {
	BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
			.setSecureRandom(new SecureRandom()).setWithIntegrityPacket(true);
	PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(builder);

	for (PGPPublicKey encKey : encKeys) {
		encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));
	}
	return encryptedDataGenerator;
}
 
Example #5
Source File: PGPEncrypt.java    From peer-os with Apache License 2.0 5 votes vote down vote up
private static PGPEncryptedDataGenerator getEncryptedGenerator( PGPPublicKey publicKey )
{
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder( PGPEncryptedData.CAST5 ).setWithIntegrityPacket( true )
                                                                    .setSecureRandom( new SecureRandom() )
                                                                    .setProvider( "BC" ) );

    encGen.addMethod( new JcePublicKeyKeyEncryptionMethodGenerator( publicKey ).setProvider( "BC" ) );

    return encGen;
}
 
Example #6
Source File: OpenPGPKeyBasedEncryptorTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldDecryptExternalFile() throws Exception {
    for (int i = 1; i<14; i++) {
        if (PGPEncryptedData.SAFER != i) { // SAFER cipher is not supported and therefore its test is skipped
            Integer cipher = i;
            // Arrange
            byte[] plainBytes = Files.readAllBytes(Paths.get(plainFile.getPath()));
            final String PLAINTEXT = new String(plainBytes, "UTF-8");

            InputStream cipherStream = new FileInputStream(unsignedFile);
            OutputStream recoveredStream = new ByteArrayOutputStream();

            // No file, just streams
            String filename = unsignedFile.getName();

            OpenPGPKeyBasedEncryptor encryptor = new OpenPGPKeyBasedEncryptor(
                    EncryptionMethod.PGP.getAlgorithm(), cipher, EncryptionMethod.PGP.getProvider(), SECRET_KEYRING_PATH, USER_ID, PASSWORD.toCharArray(), filename);

            StreamCallback decryptionCallback = encryptor.getDecryptionCallback();

            // Act
            decryptionCallback.process(cipherStream, recoveredStream);

            // Assert
            byte[] recoveredBytes = ((ByteArrayOutputStream) recoveredStream).toByteArray();
            String recovered = new String(recoveredBytes, "UTF-8");
            logger.info("Recovered: {}", recovered);
            Assert.assertEquals("Recovered text", PLAINTEXT, recovered);
        }
    }
}
 
Example #7
Source File: OpenPGPPasswordBasedEncryptorTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldDecryptExternalFile() throws Exception {
    for (int i = 1; i<14; i++) {
        if (PGPEncryptedData.SAFER != i) {  // SAFER cipher is not supported and therefore its test is skipped
            Integer cipher = i;
            // Arrange
            byte[] plainBytes = Files.readAllBytes(Paths.get(plainFile.getPath()));
            final String PLAINTEXT = new String(plainBytes, "UTF-8");

            InputStream cipherStream = new FileInputStream(encryptedFile);
            OutputStream recoveredStream = new ByteArrayOutputStream();

            // No file, just streams
            String filename = encryptedFile.getName();

            OpenPGPPasswordBasedEncryptor encryptor = new OpenPGPPasswordBasedEncryptor(EncryptionMethod.PGP.getAlgorithm(), cipher,
                    EncryptionMethod.PGP.getProvider(), LEGACY_PASSWORD.toCharArray(), filename);

            StreamCallback decryptionCallback = encryptor.getDecryptionCallback();

            // Act
            decryptionCallback.process(cipherStream, recoveredStream);

            // Assert
            byte[] recoveredBytes = ((ByteArrayOutputStream) recoveredStream).toByteArray();
            String recovered = new String(recoveredBytes, "UTF-8");
            logger.info("Recovered: {}", recovered);
            Assert.assertEquals("Recovered text", PLAINTEXT, recovered);
        }
    }
}
 
Example #8
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example #9
Source File: Encryptor.java    From desktopclient-java with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Encrypt, sign and write input stream data to output stream.
 * Input and output stream are closed.
 */
private static void encryptAndSign(
        InputStream plainInput, OutputStream encryptedOutput,
        PersonalKey myKey, List<PGPUtils.PGPCoderKey> receiverKeys)
        throws IOException, PGPException {

    // setup data encryptor & generator
    BcPGPDataEncryptorBuilder encryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_192);
    encryptor.setWithIntegrityPacket(true);
    encryptor.setSecureRandom(new SecureRandom());

    // add public key recipients
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptor);
    receiverKeys.forEach(key ->
        encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key.encryptKey)));

    OutputStream encryptedOut = encGen.open(encryptedOutput, new byte[BUFFER_SIZE]);

    // setup compressed data generator
    PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
    OutputStream compressedOut = compGen.open(encryptedOut, new byte[BUFFER_SIZE]);

    // setup signature generator
    int algo = myKey.getSigningAlgorithm();
    PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA256));
    sigGen.init(PGPSignature.BINARY_DOCUMENT, myKey.getPrivateSigningKey());

    PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
    spGen.setSignerUserID(false, myKey.getUserId());
    sigGen.setUnhashedSubpackets(spGen.generate());

    sigGen.generateOnePassVersion(false).encode(compressedOut);

    // Initialize literal data generator
    PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
    OutputStream literalOut = literalGen.open(
        compressedOut,
        PGPLiteralData.BINARY,
        "",
        new Date(),
        new byte[BUFFER_SIZE]);

    // read the "in" stream, compress, encrypt and write to the "out" stream
    // this must be done if clear data is bigger than the buffer size
    // but there are other ways to optimize...
    byte[] buf = new byte[BUFFER_SIZE];
    int len;
    while ((len = plainInput.read(buf)) > 0) {
        literalOut.write(buf, 0, len);
        sigGen.update(buf, 0, len);
    }

    literalGen.close();

    // generate the signature, compress, encrypt and write to the "out" stream
    sigGen.generate().encode(compressedOut);
    compGen.close();
    encGen.close();
}