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 ); } }
private static void produceSign( byte[] data, BCPGOutputStream bcOut, PGPSignatureGenerator signGen ) throws IOException, PGPException { PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator(); OutputStream os = literalGen.open( bcOut, PGPLiteralData.BINARY, "", data.length, new Date() ); InputStream is = new ByteArrayInputStream( data ); int ch; while ( ( ch = is.read() ) >= 0 ) { signGen.update( ( byte ) ch ); os.write( ch ); } literalGen.close(); signGen.generate().encode( bcOut ); }
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); } }
private static byte[] compress(byte[] clearData, String fileName, int algorithm) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm); OutputStream cos = comData.open(bOut); // open it with the final destination PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator(); // we want to generate compressed data. This might be a user option later, // in which case we would pass in bOut. OutputStream pOut = lData.open(cos, // the compressed output stream PGPLiteralData.BINARY, fileName, // "filename" to store clearData.length, // length of clear data new Date() // current time ); pOut.write(clearData); pOut.close(); comData.close(); return bOut.toByteArray(); }
private void readBackTest( PGPLiteralDataGenerator generator) throws IOException { Random rand = new Random(); byte[] buf = new byte[MAX]; rand.nextBytes(buf); for (int i = 1; i <= 200; i++) { bufferTest(generator, buf, i); } bufferTest(generator, buf, 8382); bufferTest(generator, buf, 8383); bufferTest(generator, buf, 8384); bufferTest(generator, buf, 8385); for (int i = 200; i < MAX; i += 100) { bufferTest(generator, buf, i); } }
private static void writeBytesToLiteralData(OutputStream out, char fileType, String name, byte[] bytes) throws IOException { PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator(); OutputStream pOut = lData.open(out, fileType, name, bytes.length, new Date()); pOut.write(bytes); }
/** * Wraps with stream that ouputs literal data packet. */ protected OutputStream packet(OutputStream out, FileMetadata meta) throws IOException, PGPException { char format = meta.getFormat().getCode(); String name = meta.getName(); Date date = meta.getLastModifiedDate(); byte[] buf = getLiteralBuffer(meta); return new PGPLiteralDataGenerator().open(out, format, name, date, buf); }
private static OutputStream createDelegate(int bufferSize, OutputStream os, DateTime modified, String filename) { try { checkArgument(filename.endsWith(".tar"), "Ryde PGP message should contain a tar file."); return new PGPLiteralDataGenerator().open( os, BINARY, filename, modified.toDate(), new byte[bufferSize]); } catch (IOException e) { throw new RuntimeException(e); } }
@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."); }
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()); }
private void bufferTest( PGPLiteralDataGenerator generator, byte[] buf, int i) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); OutputStream out = generator.open( new UncloseableOutputStream(bOut), PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, i, new Date()); out.write(buf, 0, i); generator.close(); PGPObjectFactory fact = new PGPObjectFactory(bOut.toByteArray()); PGPLiteralData data = (PGPLiteralData)fact.nextObject(); InputStream in = data.getInputStream(); for (int count = 0; count != i; count++) { if (in.read() != (buf[count] & 0xff)) { fail("failed readback test - length = " + i); } } }
public void performTest() throws IOException { PGPLiteralDataGenerator oldGenerator = new PGPLiteralDataGenerator(true); readBackTest(oldGenerator); PGPLiteralDataGenerator newGenerator = new PGPLiteralDataGenerator(false); readBackTest(newGenerator); }
private void testSig( int encAlgorithm, int hashAlgorithm, PGPPublicKey pubKey, PGPPrivateKey privKey) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayInputStream testIn = new ByteArrayInputStream(TEST_DATA); PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(encAlgorithm, hashAlgorithm).setProvider("BC")); sGen.init(PGPSignature.BINARY_DOCUMENT, privKey); sGen.generateOnePassVersion(false).encode(bOut); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); OutputStream lOut = lGen.open( new UncloseableOutputStream(bOut), PGPLiteralData.BINARY, "_CONSOLE", TEST_DATA.length * 2, new Date()); int ch; while ((ch = testIn.read()) >= 0) { lOut.write(ch); sGen.update((byte)ch); } lOut.write(TEST_DATA); sGen.update(TEST_DATA); lGen.close(); sGen.generate().encode(bOut); verifySignature(bOut.toByteArray(), hashAlgorithm, pubKey, TEST_DATA); }
private byte[] generateV3BinarySig(PGPPrivateKey privKey, int encAlgorithm, int hashAlgorithm) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayInputStream testIn = new ByteArrayInputStream(TEST_DATA); PGPV3SignatureGenerator sGen = new PGPV3SignatureGenerator(new JcaPGPContentSignerBuilder(encAlgorithm, hashAlgorithm).setProvider("BC")); sGen.init(PGPSignature.BINARY_DOCUMENT, privKey); sGen.generateOnePassVersion(false).encode(bOut); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); OutputStream lOut = lGen.open( new UncloseableOutputStream(bOut), PGPLiteralData.BINARY, "_CONSOLE", TEST_DATA.length * 2, new Date()); int ch; while ((ch = testIn.read()) >= 0) { lOut.write(ch); sGen.update((byte)ch); } lOut.write(TEST_DATA); sGen.update(TEST_DATA); lGen.close(); sGen.generate().encode(bOut); return bOut.toByteArray(); }
/** * Generated signature test * * @param sKey * @param pgpPrivKey */ public void generateTest( PGPSecretKeyRing sKey, PGPPublicKey pgpPubKey, PGPPrivateKey pgpPrivKey) throws Exception { String data = "hello world!"; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayInputStream testIn = new ByteArrayInputStream(data.getBytes()); PGPSignatureGenerator sGen = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1)); sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); Iterator it = sKey.getSecretKey().getPublicKey().getUserIDs(); String primaryUserID = (String)it.next(); spGen.setSignerUserID(true, primaryUserID); sGen.setHashedSubpackets(spGen.generate()); sGen.generateOnePassVersion(false).encode(bOut); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000); OutputStream lOut = lGen.open( new UncloseableOutputStream(bOut), PGPLiteralData.BINARY, "_CONSOLE", data.getBytes().length, testDate); int ch; while ((ch = testIn.read()) >= 0) { lOut.write(ch); sGen.update((byte)ch); } lGen.close(); sGen.generate().encode(bOut); PGPObjectFactory pgpFact = new BcPGPObjectFactory(bOut.toByteArray()); PGPOnePassSignatureList p1 = (PGPOnePassSignatureList)pgpFact.nextObject(); PGPOnePassSignature ops = p1.get(0); PGPLiteralData p2 = (PGPLiteralData)pgpFact.nextObject(); if (!p2.getModificationTime().equals(testDate)) { fail("Modification time not preserved"); } InputStream dIn = p2.getInputStream(); ops.init(new BcPGPContentVerifierBuilderProvider(), pgpPubKey); while ((ch = dIn.read()) >= 0) { ops.update((byte)ch); } PGPSignatureList p3 = (PGPSignatureList)pgpFact.nextObject(); if (!ops.verify(p3.get(0))) { fail("Failed generated signature check"); } }
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 ); } }
public static byte[] sign( byte[] message, PGPSecretKey secretKey, String secretPwd, boolean armor ) throws PGPException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream theOut = armor ? new ArmoredOutputStream( out ) : out; PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ); PGPSignatureGenerator sGen = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1 ) .setProvider( provider ) ); sGen.init( PGPSignature.BINARY_DOCUMENT, pgpPrivKey ); Iterator it = secretKey.getPublicKey().getUserIDs(); if ( it.hasNext() ) { PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID( false, ( String ) it.next() ); sGen.setHashedSubpackets( spGen.generate() ); } PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator( PGPCompressedData.ZLIB ); BCPGOutputStream bOut = new BCPGOutputStream( cGen.open( theOut ) ); sGen.generateOnePassVersion( false ).encode( bOut ); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); OutputStream lOut = lGen.open( bOut, PGPLiteralData.BINARY, "filename", new Date(), new byte[4096] ); // InputStream fIn = new ByteArrayInputStream( message ); int ch; while ( ( ch = fIn.read() ) >= 0 ) { lOut.write( ch ); sGen.update( ( byte ) ch ); } lGen.close(); sGen.generate().encode( bOut ); cGen.close(); theOut.close(); return out.toByteArray(); } catch ( Exception e ) { throw new PGPException( "Error in sign", e ); } }
private static byte[] compress( byte data[] ) throws IOException { PGPCompressedDataGenerator compressGen = new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream compressOut = compressGen.open( bos ); OutputStream os = new PGPLiteralDataGenerator().open( compressOut, PGPLiteralData.BINARY, "", data.length, new Date() ); os.write( data ); os.close(); compressGen.close(); return bos.toByteArray(); }
@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); } }
public static byte[] signFile(byte[] content, String fileName, InputStream keyIn, char[] pass, Provider securityProvider, TimeProvider timeProvider) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, PGPException, SignatureException { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); ArmoredOutputStream armoredOut = new ArmoredOutputStream(byteArrayOut); PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB); try { PGPSecretKey pgpSecretKey = BouncyCastlePGPExampleUtil.readSecretKey(keyIn); PGPPrivateKey pgpPrivateKey = pgpSecretKey.extractPrivateKey(pass, securityProvider); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(pgpSecretKey .getPublicKey().getAlgorithm(), PGPUtil.SHA1, securityProvider); signatureGenerator.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivateKey); Iterator<?> it = pgpSecretKey.getPublicKey().getUserIDs(); if (it.hasNext()) { //get first user ID PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, (String) it.next()); signatureGenerator.setHashedSubpackets(spGen.generate()); } else { throw new PGPException("No user ID found in the public key of the certificate."); } BCPGOutputStream bOut = new BCPGOutputStream(compressedDataGenerator.open(armoredOut)); signatureGenerator.generateOnePassVersion(false).encode(bOut); OutputStream literalOut = literalDataGenerator.open(bOut, PGPLiteralData.BINARY, fileName, timeProvider.nowDate(), content); literalOut.write(content); signatureGenerator.update(content); signatureGenerator.generate().encode(bOut); } finally { literalDataGenerator.close(); compressedDataGenerator.close(); armoredOut.close(); } return byteArrayOut.toByteArray(); }
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); } }
private void testTextSig( int encAlgorithm, int hashAlgorithm, PGPPublicKey pubKey, PGPPrivateKey privKey, byte[] data, byte[] canonicalData) throws Exception { PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(encAlgorithm, HashAlgorithmTags.SHA1).setProvider("BC")); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayInputStream testIn = new ByteArrayInputStream(data); Date creationTime = new Date(); sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey); sGen.generateOnePassVersion(false).encode(bOut); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); OutputStream lOut = lGen.open( new UncloseableOutputStream(bOut), PGPLiteralData.TEXT, "_CONSOLE", data.length * 2, creationTime); int ch; while ((ch = testIn.read()) >= 0) { lOut.write(ch); sGen.update((byte)ch); } lOut.write(data); sGen.update(data); lGen.close(); PGPSignature sig = sGen.generate(); if (sig.getCreationTime().getTime() == 0) { fail("creation time not set in v4 signature"); } sig.encode(bOut); verifySignature(bOut.toByteArray(), hashAlgorithm, pubKey, canonicalData); }
private void testTextSigV3( int encAlgorithm, int hashAlgorithm, PGPPublicKey pubKey, PGPPrivateKey privKey, byte[] data, byte[] canonicalData) throws Exception { PGPV3SignatureGenerator sGen = new PGPV3SignatureGenerator(new JcaPGPContentSignerBuilder(encAlgorithm, HashAlgorithmTags.SHA1).setProvider("BC")); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayInputStream testIn = new ByteArrayInputStream(data); sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey); sGen.generateOnePassVersion(false).encode(bOut); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); OutputStream lOut = lGen.open( new UncloseableOutputStream(bOut), PGPLiteralData.TEXT, "_CONSOLE", data.length * 2, new Date()); int ch; while ((ch = testIn.read()) >= 0) { lOut.write(ch); sGen.update((byte)ch); } lOut.write(data); sGen.update(data); lGen.close(); PGPSignature sig = sGen.generate(); if (sig.getCreationTime().getTime() == 0) { fail("creation time not set in v3 signature"); } sig.encode(bOut); verifySignature(bOut.toByteArray(), hashAlgorithm, pubKey, canonicalData); }
private void doSigGenerateTest(String privateKeyFile, String publicKeyFile, int digest) throws Exception { PGPSecretKeyRing secRing = loadSecretKey(privateKeyFile); PGPPublicKeyRing pubRing = loadPublicKey(publicKeyFile); String data = "hello world!"; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayInputStream testIn = new ByteArrayInputStream(data.getBytes()); PGPSignatureGenerator sGen = new PGPSignatureGenerator(PublicKeyAlgorithmTags.DSA, digest, "BC"); sGen.initSign(PGPSignature.BINARY_DOCUMENT, secRing.getSecretKey().extractPrivateKey("test".toCharArray(), "BC")); BCPGOutputStream bcOut = new BCPGOutputStream(bOut); sGen.generateOnePassVersion(false).encode(bcOut); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000); OutputStream lOut = lGen.open( new UncloseableOutputStream(bcOut), PGPLiteralData.BINARY, "_CONSOLE", data.getBytes().length, testDate); int ch; while ((ch = testIn.read()) >= 0) { lOut.write(ch); sGen.update((byte)ch); } lGen.close(); sGen.generate().encode(bcOut); PGPObjectFactory pgpFact = new PGPObjectFactory(bOut.toByteArray()); PGPOnePassSignatureList p1 = (PGPOnePassSignatureList)pgpFact.nextObject(); PGPOnePassSignature ops = p1.get(0); assertEquals(digest, ops.getHashAlgorithm()); assertEquals(PublicKeyAlgorithmTags.DSA, ops.getKeyAlgorithm()); PGPLiteralData p2 = (PGPLiteralData)pgpFact.nextObject(); if (!p2.getModificationTime().equals(testDate)) { fail("Modification time not preserved"); } InputStream dIn = p2.getInputStream(); ops.initVerify(pubRing.getPublicKey(), "BC"); while ((ch = dIn.read()) >= 0) { ops.update((byte)ch); } PGPSignatureList p3 = (PGPSignatureList)pgpFact.nextObject(); PGPSignature sig = p3.get(0); assertEquals(digest, sig.getHashAlgorithm()); assertEquals(PublicKeyAlgorithmTags.DSA, sig.getKeyAlgorithm()); assertTrue(ops.verify(sig)); }
/** * 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(); }
/** * Generated signature test * * @param sKey * @param pgpPrivKey */ public void generateTest( PGPSecretKeyRing sKey, PGPPublicKey pgpPubKey, PGPPrivateKey pgpPrivKey) throws Exception { String data = "hello world!"; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayInputStream testIn = new ByteArrayInputStream(data.getBytes()); PGPSignatureGenerator sGen = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(PublicKeyAlgorithmTags.DSA, HashAlgorithmTags.SHA1)); sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); Iterator it = sKey.getSecretKey().getPublicKey().getUserIDs(); String primaryUserID = (String)it.next(); spGen.setSignerUserID(true, primaryUserID); sGen.setHashedSubpackets(spGen.generate()); sGen.generateOnePassVersion(false).encode(bOut); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000); OutputStream lOut = lGen.open( new UncloseableOutputStream(bOut), PGPLiteralData.BINARY, "_CONSOLE", data.getBytes().length, testDate); int ch; while ((ch = testIn.read()) >= 0) { lOut.write(ch); sGen.update((byte)ch); } lGen.close(); sGen.generate().encode(bOut); PGPObjectFactory pgpFact = new PGPObjectFactory(bOut.toByteArray()); PGPOnePassSignatureList p1 = (PGPOnePassSignatureList)pgpFact.nextObject(); PGPOnePassSignature ops = p1.get(0); PGPLiteralData p2 = (PGPLiteralData)pgpFact.nextObject(); if (!p2.getModificationTime().equals(testDate)) { fail("Modification time not preserved"); } InputStream dIn = p2.getInputStream(); ops.init(new BcPGPContentVerifierBuilderProvider(), pgpPubKey); while ((ch = dIn.read()) >= 0) { ops.update((byte)ch); } PGPSignatureList p3 = (PGPSignatureList)pgpFact.nextObject(); if (!ops.verify(p3.get(0))) { fail("Failed generated signature check"); } }