/** * Base constructor with the option to turn on formatting for PGP 2.6.x compatibility. * * @param encryptorBuilder builder to create actual data encryptor. * @param oldFormat PGP 2.6.x compatibility required. */ public PGPEncryptedDataGenerator(PGPDataEncryptorBuilder encryptorBuilder, boolean oldFormat) { this.dataEncryptorBuilder = encryptorBuilder; this.oldFormat = oldFormat; this.defAlgorithm = dataEncryptorBuilder.getAlgorithm(); this.rand = dataEncryptorBuilder.getSecureRandom(); }
@Test public void encryptAndDecrypt() throws Exception { // both keys have property encryptionKey==true final String[] keyIds = { "d7a92a24aa97ddbd", // master-key "a58da7d810b74edf" // sub-key }; for (final String keyId : keyIds) { final PGPDataEncryptorBuilder encryptorBuilder = new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.TWOFISH); final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(encryptorBuilder); final PGPKeyEncryptionMethodGenerator keyEncryptionMethodGenerator = new BcPublicKeyKeyEncryptionMethodGenerator( getPgpPublicKeyOrFail(bytesToLong(decodeHexStr(keyId)))); encryptedDataGenerator.addMethod(keyEncryptionMethodGenerator); final byte[] plain = new byte[1 + random.nextInt(1024 * 1024)]; random.nextBytes(plain); final File encryptedFile = File.createTempFile("encrypted_", ".tmp"); try (final OutputStream encryptedOut = new FileOutputStream(encryptedFile);) { try (final OutputStream plainOut = encryptedDataGenerator.open(encryptedOut, new byte[1024 * 16]);) { plainOut.write(plain); } } final byte[] decrypted; try (InputStream in = new FileInputStream(encryptedFile)) { final PGPEncryptedDataList encryptedDataList = new PGPEncryptedDataList(new BCPGInputStream(in)); final Iterator<?> encryptedDataObjects = encryptedDataList.getEncryptedDataObjects(); assertThat(encryptedDataObjects.hasNext()).isTrue(); final PGPPublicKeyEncryptedData encryptedData = (PGPPublicKeyEncryptedData) encryptedDataObjects.next(); assertThat(encryptedDataObjects.hasNext()).isFalse(); final PublicKeyDataDecryptorFactory dataDecryptorFactory = new BcPublicKeyDataDecryptorFactory( getPgpPrivateKeyOrFail(encryptedData.getKeyID(), "test12345".toCharArray())); try (InputStream plainIn = encryptedData.getDataStream(dataDecryptorFactory);) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); transferStreamData(plainIn, out); decrypted = out.toByteArray(); } } assertThat(decrypted).isEqualTo(plain); encryptedFile.delete(); // delete it, if this test did not fail } }
/** * Base constructor. * * @param encryptorBuilder builder to create actual data encryptor. */ public PGPEncryptedDataGenerator(PGPDataEncryptorBuilder encryptorBuilder) { this(encryptorBuilder, false); }