本文整理汇总了Java中org.bouncycastle.openpgp.PGPEncryptedDataGenerator.open方法的典型用法代码示例。如果您正苦于以下问题:Java PGPEncryptedDataGenerator.open方法的具体用法?Java PGPEncryptedDataGenerator.open怎么用?Java PGPEncryptedDataGenerator.open使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.bouncycastle.openpgp.PGPEncryptedDataGenerator
的用法示例。
在下文中一共展示了PGPEncryptedDataGenerator.open方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: encrypt
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
public static byte[] encrypt( final byte[] message, final PGPPublicKey publicKey, boolean armored )
throws PGPException
{
try
{
final ByteArrayInputStream in = new ByteArrayInputStream( message );
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
final PGPLiteralDataGenerator literal = new PGPLiteralDataGenerator();
final PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP );
final OutputStream pOut =
literal.open( comData.open( bOut ), PGPLiteralData.BINARY, "filename", in.available(), new Date() );
Streams.pipeAll( in, pOut );
comData.close();
final byte[] bytes = bOut.toByteArray();
final PGPEncryptedDataGenerator generator = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder( SymmetricKeyAlgorithmTags.AES_256 ).setWithIntegrityPacket( true )
.setSecureRandom(
new SecureRandom() )
.setProvider( provider ) );
generator.addMethod( new JcePublicKeyKeyEncryptionMethodGenerator( publicKey ).setProvider( provider ) );
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream theOut = armored ? new ArmoredOutputStream( out ) : out;
OutputStream cOut = generator.open( theOut, bytes.length );
cOut.write( bytes );
cOut.close();
theOut.close();
return out.toByteArray();
}
catch ( Exception e )
{
throw new PGPException( "Error in encrypt", e );
}
}
示例2: encrypt
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
/**
* Wraps with stream that outputs encrypted data packet.
*/
protected OutputStream encrypt(OutputStream out, FileMetadata meta)
throws IOException, PGPException {
if (log.isLoggable(Level.FINEST))
log.finest("using encryption algorithm " + encryptionAlgorithm);
if (encryptionAlgorithm == EncryptionAlgorithm.Unencrypted)
return null;
List<Key> keys = ring.getEncryptionKeys();
if (Util.isEmpty(keys) && Util.isEmpty(symmetricPassphrase))
throw new PGPException("no suitable encryption key found");
PGPEncryptedDataGenerator generator = buildEncryptor();
for (Key key : keys)
generator.addMethod(buildPublicKeyEncryptor(key));
if (!Util.isEmpty(symmetricPassphrase))
generator.addMethod(buildSymmetricKeyEncryptor());
return generator.open(out, getEncryptionBuffer(meta));
}
示例3: createEncryptedNonCompressedData
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
void createEncryptedNonCompressedData(ByteArrayOutputStream bos, String keyringPath) throws Exception, IOException, PGPException,
UnsupportedEncodingException {
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
.setSecureRandom(new SecureRandom()).setProvider(getProvider()));
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(readPublicKey(keyringPath)));
OutputStream encOut = encGen.open(bos, new byte[512]);
PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
OutputStream litOut = litData.open(encOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[512]);
try {
litOut.write("Test Message Without Compression".getBytes("UTF-8"));
litOut.flush();
} finally {
IOHelper.close(litOut);
IOHelper.close(encOut, bos);
}
}
示例4: encryptFile
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
/**
* Encrypt the given file
* @param unencryptedFileName - Name of the unecrypted file
* @param encryptedFileName - Name of the encrypted file, will have .enc as extension
* @throws IOException
* @throws NoSuchProviderException
* @throws PGPException
* @throws CryptDecryptException
*/
public void encryptFile(final String unencryptedFileName, final String encryptedFileName)
throws IOException, NoSuchProviderException, PGPException, CryptDecryptException {
if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.encryptFile", "Entry");
// Initialise PGP provider and read public key
if(!initialized) initialise(false);
FileOutputStream encrytedFile = new FileOutputStream(encryptedFileName);
// Compress the input plain text file in ZIP format.
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(unencryptedFileName) );
comData.close();
// Encrypt the file using Triple-DES algorithm
BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES);
dataEncryptor.setWithIntegrityPacket(false);
dataEncryptor.setSecureRandom(new SecureRandom());
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
byte[] bytes = bOut.toByteArray();
OutputStream cOut = encryptedDataGenerator.open(encrytedFile, bytes.length);
cOut.write(bytes);
cOut.close();
encrytedFile.close();
if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.encryptFile", "Exit");
}
示例5: openEncryptor
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
/**
* Opens a new {@link Encryptor} (Writing Step 1/3)
*
* <p>This is the first step in creating a ghostryde file. After this method, you'll want to
* call {@link #openCompressor(Encryptor)}.
*
* @param os is the upstream {@link OutputStream} to which the result is written.
* @param publicKey is the public encryption key of the recipient.
* @throws IOException
* @throws PGPException
*/
@CheckReturnValue
public Encryptor openEncryptor(@WillNotClose OutputStream os, PGPPublicKey publicKey)
throws IOException, PGPException {
PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(CIPHER)
.setWithIntegrityPacket(USE_INTEGRITY_PACKET)
.setSecureRandom(getRandom())
.setProvider(PROVIDER_NAME));
encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
return new Encryptor(encryptor.open(os, new byte[bufferSize]));
}
示例6: testEncryptDecrypt_ExplicitStyle
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
@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));
}
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);
}
}
}
示例7: testExceptionDecryptorIncorrectInputFormatSymmetricEncryptedData
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
@Test
public void testExceptionDecryptorIncorrectInputFormatSymmetricEncryptedData() throws Exception {
byte[] payload = "Not Correct Format".getBytes("UTF-8");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
.setSecureRandom(new SecureRandom()).setProvider(getProvider()));
encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator("pw".toCharArray()));
OutputStream encOut = encGen.open(bos, new byte[1024]);
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
OutputStream comOut = new BufferedOutputStream(comData.open(encOut));
PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[1024]);
litOut.write(payload);
litOut.flush();
litOut.close();
comOut.close();
encOut.close();
MockEndpoint mock = getMockEndpoint("mock:exception");
mock.expectedMessageCount(1);
template.sendBody("direct:subkeyUnmarshal", bos.toByteArray());
assertMockEndpointsSatisfied();
checkThrownException(mock, IllegalArgumentException.class, null, "The input message body has an invalid format.");
}
示例8: encryptString
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
public String encryptString(PGPPublicKey key, String clearText)
throws IOException, PGPException {
byte[] clearData = clearText.getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
OutputStream out = new ArmoredOutputStream(encOut);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
PGPCompressedDataGenerator.ZIP);
OutputStream cos = comData.open(bOut);
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
OutputStream pOut = lData.open(cos, PGPLiteralData.BINARY,
PGPLiteralData.CONSOLE, clearData.length, new Date());
pOut.write(clearData);
lData.close();
comData.close();
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
.setWithIntegrityPacket(true)
.setSecureRandom(new SecureRandom()).setProvider(BouncyCastleProvider.PROVIDER_NAME));
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key)
.setProvider(BouncyCastleProvider.PROVIDER_NAME));
byte[] bytes = bOut.toByteArray();
OutputStream cOut = encGen.open(out, bytes.length);
cOut.write(bytes);
cOut.close();
out.close();
return new String(encOut.toByteArray());
}
示例9: signAndEncrypt
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
public static byte[] signAndEncrypt( final byte[] message, final PGPSecretKey secretKey, final String secretPwd,
final PGPPublicKey publicKey, final boolean armored ) throws PGPException
{
try
{
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder( SymmetricKeyAlgorithmTags.AES_256 ).setWithIntegrityPacket( true )
.setSecureRandom(
new SecureRandom() )
.setProvider( provider ) );
encryptedDataGenerator.addMethod(
new JcePublicKeyKeyEncryptionMethodGenerator( publicKey ).setSecureRandom( new SecureRandom() )
.setProvider( provider ) );
final OutputStream theOut = armored ? new ArmoredOutputStream( out ) : out;
final OutputStream encryptedOut = encryptedDataGenerator.open( theOut, new byte[4096] );
final PGPCompressedDataGenerator compressedDataGenerator =
new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP );
final OutputStream compressedOut = compressedDataGenerator.open( encryptedOut, new byte[4096] );
final PGPPrivateKey privateKey = secretKey.extractPrivateKey(
new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) );
final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1 )
.setProvider( provider ) );
signatureGenerator.init( PGPSignature.BINARY_DOCUMENT, privateKey );
final Iterator<?> it = secretKey.getPublicKey().getUserIDs();
if ( it.hasNext() )
{
final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
spGen.setSignerUserID( false, ( String ) it.next() );
signatureGenerator.setHashedSubpackets( spGen.generate() );
}
signatureGenerator.generateOnePassVersion( false ).encode( compressedOut );
final PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
final OutputStream literalOut = literalDataGenerator
.open( compressedOut, PGPLiteralData.BINARY, "filename", new Date(), new byte[4096] );
final InputStream in = new ByteArrayInputStream( message );
final byte[] buf = new byte[4096];
for ( int len; ( len = in.read( buf ) ) > 0; )
{
literalOut.write( buf, 0, len );
signatureGenerator.update( buf, 0, len );
}
in.close();
literalDataGenerator.close();
signatureGenerator.generate().encode( compressedOut );
compressedDataGenerator.close();
encryptedDataGenerator.close();
theOut.close();
return out.toByteArray();
}
catch ( Exception e )
{
throw new PGPException( "Error in signAndEncrypt", e );
}
}
示例10: testEncryptDecrypt_KeyRingStyle
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
@Test
public void testEncryptDecrypt_KeyRingStyle() throws Exception {
int bufferSize = 64 * 1024;
// Alice loads Bob's "publicKey" into memory from her public key ring.
PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection(
PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY)));
PGPPublicKeyRing publicKeyRing =
publicKeyRings.getKeyRings("[email protected]", true, true).next();
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));
}
encryptedData = output.toByteArray();
}
logger.info("Encrypted data: " + dumpHex(encryptedData));
// Bob loads his chain of private keys into memory.
PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection(
PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY)));
// 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);
// Bob loads the private key to which the message is addressed.
PGPPrivateKey privateKey =
extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID()));
try (InputStream original =
encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
.isEqualTo(FALL_OF_HYPERION_A_DREAM);
}
}
}
示例11: signAndEncrypt
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
@Override
public String signAndEncrypt(String message) throws IOException {
try {
/* Final < Armored < Crypted < Clear PGP */
ByteArrayOutputStream out = new ByteArrayOutputStream();
ArmoredOutputStream armoredOutput = new ArmoredOutputStream(out);
PGPEncryptedDataGenerator crypter = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.S2K_SHA1, new SecureRandom(), _provider);
crypter.addMethod(getRemotePublicKey());
BCPGOutputStream pgpOut = new BCPGOutputStream(crypter.open(armoredOutput, new byte[512]));
/* Prepare for signing */
PGPSignatureGenerator signer = new PGPSignatureGenerator(getSigningPublicKey().getAlgorithm(),
PGPUtil.SHA1, _provider
);
signer.initSign(PGPSignature.BINARY_DOCUMENT, getSigningPrivateKey());
/* Output the standard header */
signer.generateOnePassVersion(false).encode(pgpOut);
/* Output the literal data */
PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(true);
literalDataGenerator.open(pgpOut, 'b', "bar", message.getBytes().length, new Date()).write(message.getBytes());
/* Calculate signature and output it */
signer.update(message.getBytes());
signer.generate().encode(pgpOut);
pgpOut.close();
armoredOutput.close();
out.close();
byte[] result = out.toByteArray();
// brain dead UMAPI adds an extra base64 encoding on top of the ASCII armored string. Go figure.
return new String(Base64.encode(result));
} catch (PGPException pgpException) {
throw new IOException("PGP subsystem problem.", pgpException);
} catch (NoSuchAlgorithmException noSuchAlgorithmException) {
throw new IOException("Missing algorithm. Are you running a compatible JVM/Bouncycastle version?", noSuchAlgorithmException);
} catch (SignatureException signatureException) {
throw new IOException("PGP subsystem problem.", signatureException);
} catch (NoSuchProviderException noSuchProviderException) {
throw new IOException("Missing provider. Are you running a compatible JVM/Bouncycastle version?", noSuchProviderException);
}
}
示例12: encryptAndDecrypt
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
@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
}
}
示例13: run
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
public void run(final char[] passphrase, final InputStream inputStream, final OutputStream outputStream) throws IOException, CryptoException {
try {
final OutputStream armor = new ArmoredOutputStream(outputStream);
final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(
SymmetricKeyAlgorithmTags.AES_128).setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(new BouncyCastleProvider()));
encryptedDataGenerator.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setSecureRandom(new SecureRandom()).setProvider(
new BouncyCastleProvider()));
final OutputStream encryptedOut = encryptedDataGenerator.open(armor, new byte[4096]);
final PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
final OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[4096]);
final PGPPrivateKey privateKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(new BouncyCastleProvider())
.build(passphrase));
final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(secretKey.getPublicKey()
.getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(new BouncyCastleProvider()));
signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
final Iterator<?> it = secretKey.getPublicKey().getUserIDs();
if (it.hasNext()) {
final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
spGen.setSignerUserID(false, (String) it.next());
signatureGenerator.setHashedSubpackets(spGen.generate());
}
signatureGenerator.generateOnePassVersion(false).encode(compressedOut);
final PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
final OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, "", new Date(), new byte[4096]);
final byte[] buf = new byte[4096];
for (int len = 0; (len = inputStream.read(buf)) > 0;) {
literalOut.write(buf, 0, len);
signatureGenerator.update(buf, 0, len);
}
literalDataGenerator.close();
signatureGenerator.generate().encode(compressedOut);
compressedDataGenerator.close();
encryptedDataGenerator.close();
armor.close();
}
catch (final Exception e) {
throw new CryptoException(e);
}
}
示例14: encryptAndSign
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; //导入方法依赖的package包/类
/**
* 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();
}