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 PGPLiteralData asLiteral( final byte[] message, final InputStream secretKeyRing, final String secretPwd ) throws IOException, PGPException { PGPPrivateKey key = null; PGPPublicKeyEncryptedData encrypted = null; final PGPSecretKeyRingCollection keys = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secretKeyRing ), new JcaKeyFingerprintCalculator() ); for ( final Iterator<PGPPublicKeyEncryptedData> i = getEncryptedObjects( message ); ( key == null ) && i.hasNext(); ) { encrypted = i.next(); key = getPrivateKey( keys, encrypted.getKeyID(), secretPwd ); } if ( key == null ) { throw new IllegalArgumentException( "secret key for message not found." ); } final InputStream stream = encrypted .getDataStream( new JcePublicKeyDataDecryptorFactoryBuilder().setProvider( provider ).build( key ) ); return asLiteral( stream ); }
private void checkLiteralData(PGPLiteralData ld, byte[] data) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); if (!ld.getFileName().equals(PGPLiteralData.CONSOLE)) { throw new RuntimeException("wrong filename in packet"); } InputStream inLd = ld.getDataStream(); int ch; while ((ch = inLd.read()) >= 0) { bOut.write(ch); } if (!areEqual(bOut.toByteArray(), data)) { fail("wrong plain text in decrypted packet"); } }
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(); }
static byte[] compressFile(String fileName, int algorithm) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm); PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName)); comData.close(); return bOut.toByteArray(); }
/** Constructs a metadata object from Bouncy Castle message data. */ public FileMetadata(PGPLiteralData data) { this(data.getFileName(), Format.byCode((char) data.getFormat())); if (data.getModificationTime() != null) setLastModified(data.getModificationTime().getTime()); }
public static byte[] decrypt( final byte[] encryptedMessage, final InputStream secretKeyRing, final String secretPwd ) throws PGPException { try { final PGPLiteralData msg = asLiteral( encryptedMessage, secretKeyRing, secretPwd ); final ByteArrayOutputStream out = new ByteArrayOutputStream(); Streams.pipeAll( msg.getInputStream(), out ); return out.toByteArray(); } catch ( Exception e ) { throw new PGPException( "Error in decrypt", e ); } }
/** * *********************************************** */ private static PGPLiteralData asLiteral( final InputStream clear ) throws IOException, PGPException { final PGPObjectFactory plainFact = new PGPObjectFactory( clear, new JcaKeyFingerprintCalculator() ); final Object message = plainFact.nextObject(); if ( message instanceof PGPCompressedData ) { final PGPCompressedData cData = ( PGPCompressedData ) message; final PGPObjectFactory pgpFact = new PGPObjectFactory( cData.getDataStream(), new JcaKeyFingerprintCalculator() ); // Find the first PGPLiteralData object Object object = null; for ( int safety = 0; ( safety++ < 1000 ) && !( object instanceof PGPLiteralData ); object = pgpFact.nextObject() ) { //ignore } return ( PGPLiteralData ) object; } else if ( message instanceof PGPLiteralData ) { return ( PGPLiteralData ) message; } else if ( message instanceof PGPOnePassSignatureList ) { throw new PGPException( "encrypted message contains a signed message - not literal data." ); } else { throw new PGPException( "message is not a simple encrypted file - type unknown: " + message.getClass().getName() ); } }
/** * 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"); }
@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); } } }
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(); }
public String encryptText(String text) throws FileIOException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final byte[] bytes = text.getBytes(); _encryptData(output, new ByteArrayInputStream(bytes), bytes.length, PGPLiteralData.CONSOLE, null, ENCRYPT_ALGORITHM, ENCRYPT_ARMOR); text = Base64.encodeBase64String(output.toByteArray()); text = text.replace('/', '_'); return text; }
/** * 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(); }
/** * 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"); } }