static String signArmoredAscii(PGPPrivateKey privateKey, String data, int signatureAlgo) throws IOException, PGPException { String signature = null; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), signatureAlgo)); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); ByteArrayOutputStream signatureOutput = new ByteArrayOutputStream(); try( BCPGOutputStream outputStream = new BCPGOutputStream( new ArmoredOutputStream(signatureOutput)) ) { Utils.processStringAsStream(data, new StreamHandler() { @Override public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException { signatureGenerator.update(buffer, offset, length); } }); signatureGenerator.generate().encode(outputStream); } signature = new String(signatureOutput.toByteArray(), "UTF-8"); return signature; }
static String signArmoredAscii(PGPPrivateKey privateKey, byte[] data, int signatureAlgo) throws IOException, PGPException { String signature = null; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), signatureAlgo)); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); ByteArrayOutputStream signatureOutput = new ByteArrayOutputStream(); try( BCPGOutputStream outputStream = new BCPGOutputStream( new ArmoredOutputStream(signatureOutput)) ) { Utils.processByteArrayAsStream(data, new StreamHandler() { @Override public void handleStreamBuffer(byte[] buffer, int offset, int length) throws IOException { signatureGenerator.update(buffer, offset, length); } }); signatureGenerator.generate().encode(outputStream); } signature = new String(signatureOutput.toByteArray(), "UTF-8"); return signature; }
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 ); }
public byte[] signExternal(String input) throws IOException, PGPException { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC")); sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.update(input.getBytes(Charsets.UTF_8)); sigGenerator.generate().encode(bOut); } return buffer.toByteArray(); }
private void createSignature(OutputStream out) throws Exception { PGPSecretKey pgpSec = readSecretKey(); PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(getProvider()).build( "sdude".toCharArray())); PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(getProvider())); sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); BCPGOutputStream bOut = new BCPGOutputStream(out); InputStream fIn = new ByteArrayInputStream("Test Signature".getBytes("UTF-8")); int ch; while ((ch = fIn.read()) >= 0) { sGen.update((byte) ch); } fIn.close(); sGen.generate().encode(bOut); }
private void feedGeneratorWith(InputStream toSign, PGPSignatureGenerator generator) throws IOException { byte[] buffer = new byte[1024]; int read = toSign.read(buffer); while (read > 0) { generator.update(buffer, 0, read); read = toSign.read(buffer); } }
public PGPSignatureGenerator createSignatureGenerator() { try { PGPSignatureGenerator generator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)); generator.init(PGPSignature.BINARY_DOCUMENT, privateKey); return generator; } catch (PGPException e) { throw new UncheckedException(e); } }
/** * Builds a PGPSignatureGenerator for the specified key and content. */ protected PGPSignatureGenerator buildSigner(Key key, FileMetadata meta) throws PGPException { Subkey subkey = key.getSigning(); if (log.isLoggable(Level.INFO)) log.info("using signing key " + subkey); PGPContentSignerBuilder builder = buildSignerBuilder( subkey.getPublicKey().getAlgorithm(), signingAlgorithm.ordinal() ); PGPSignatureGenerator generator = new PGPSignatureGenerator(builder); generator.init(meta.getSignatureType(), subkey.getPrivateKey()); String uid = key.getSigningUid(); if (!Util.isEmpty(uid)) { if (log.isLoggable(Level.FINE)) log.fine("using signing uid " + uid); PGPSignatureSubpacketGenerator signer = new PGPSignatureSubpacketGenerator(); signer.setSignerUserID(false, uid); generator.setHashedSubpackets(signer.generate()); } return generator; }
protected void init(List<Key> keys) throws IOException, PGPException { // initialize signature generators sigs = new ArrayList<PGPSignatureGenerator>(keys.size()); for (Key key : keys) sigs.add(buildSigner(key, meta)); // write one-pass signature packets // with multiple signatures, all but last must be flagged "nested" for (int i = 0; i < sigs.size(); i++) { boolean nested = i != sigs.size() - 1; sigs.get(i).generateOnePassVersion(nested).encode(out); } }
private static void processLine( OutputStream aOut, PGPSignatureGenerator sGen, byte[] line ) throws SignatureException, IOException { // note: trailing white space needs to be removed from the end of // each line for signature calculation RFC 4880 Section 7.1 int length = getLengthWithoutWhiteSpace( line ); if ( length > 0 ) { sGen.update( line, 0, length ); } aOut.write( line, 0, line.length ); }
/** * Signs a public key * * @param publicKeyRing a public key ring containing the single public key to sign * @param id the id we are certifying against the public key * @param secretKey the signing key * @param secretKeyPassword the signing key password * * @return a public key ring with the signed public key */ public static PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey, String secretKeyPassword ) throws PGPException { try { PGPPublicKey oldKey = publicKeyRing.getPublicKey(); PGPPrivateKey pgpPrivKey = secretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ) .build( secretKeyPassword.toCharArray() ) ); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder( secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1 ) ); signatureGenerator.init( PGPSignature.DEFAULT_CERTIFICATION, pgpPrivKey ); PGPSignature signature = signatureGenerator.generateCertification( id, oldKey ); PGPPublicKey newKey = PGPPublicKey.addCertification( oldKey, signature ); PGPPublicKeyRing newPublicKeyRing = PGPPublicKeyRing.removePublicKey( publicKeyRing, oldKey ); return PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, newKey ); } catch ( Exception e ) { //throw custom exception throw new PGPException( "Error signing public key", e ); } }
private static PGPSignatureGenerator getSignatureGenerator( PGPPrivateKey privateKey, BCPGOutputStream bcOut ) throws PGPException, IOException { PGPSignatureGenerator signGen = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder( privateKey.getPublicKeyPacket().getAlgorithm(), PGPUtil.SHA1 ) .setProvider( "BC" ) ); signGen.init( PGPSignature.BINARY_DOCUMENT, privateKey ); signGen.generateOnePassVersion( false ).encode( bcOut ); return signGen; }
/** * Create a signer that wraps {@code os} and generates a detached signature using * {@code signingKey}. After closing, you should call {@link #getSignature()} to get the detached * signature. * * @param os is the upstream {@link OutputStream} which is not closed by this object * @throws RuntimeException to rethrow {@link PGPException} */ public RydePgpSigningOutputStream( @WillNotClose OutputStream os, PGPKeyPair signingKey) { super(os, false, -1); try { signer = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256)); signer.init(BINARY_DOCUMENT, signingKey.getPrivateKey()); } catch (PGPException e) { throw new RuntimeException(e); } addUserInfoToSignature(signingKey.getPublicKey(), signer); }
@Test public void testSignVerify_Detached() throws Exception { // Load the keys. PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY); PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY); PGPPublicKey publicKey = publicKeyRing.getPublicKey(); PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey()); // Sign the data and write signature data to "signatureFile". // Note: RSA_GENERAL will encrypt AND sign. RSA_SIGN and RSA_ENCRYPT are deprecated. PGPSignatureGenerator signer = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256)); signer.init(PGPSignature.BINARY_DOCUMENT, privateKey); addUserInfoToSignature(publicKey, signer); signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); ByteArrayOutputStream output = new ByteArrayOutputStream(); signer.generate().encode(output); byte[] signatureFileData = output.toByteArray(); logger.info(".sig file data: " + dumpHex(signatureFileData)); // Load algorithm information and signature data from "signatureFileData". PGPSignature sig; try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject(); assertThat(sigList.size()).isEqualTo(1); sig = sigList.get(0); } // Use "onePass" and "sig" to verify "publicKey" signed the text. sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey); sig.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); assertThat(sig.verify()).isTrue(); // Verify that they DIDN'T sign the text "hello monster". sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey); sig.update("hello monster".getBytes(UTF_8)); assertThat(sig.verify()).isFalse(); }
public byte[] signInline(String input) throws IOException, PGPException { PGPSecretKey signKey = readSecretKey(); PGPPrivateKey privKey = signKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray())); PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC")); sigGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey); @SuppressWarnings("unchecked") Iterator<String> userIds = signKey.getUserIDs(); if (userIds.hasNext()) { PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator(); sigSubpacketGenerator.setSignerUserID(false, userIds.next()); sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate()); } String[] lines = input.split("\r?\n"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) { aOut.beginClearText(PGPUtil.SHA256); boolean firstLine = true; for (String line : lines) { String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", ""); sigGenerator.update(sigLine.getBytes(Charsets.UTF_8)); aOut.write((line + "\n").getBytes(Charsets.UTF_8)); firstLine = false; } aOut.endClearText(); BCPGOutputStream bOut = new BCPGOutputStream(aOut); sigGenerator.generate().encode(bOut); } return buffer.toByteArray(); }
protected List<PGPSignatureGenerator> createSignatureGenerator(Exchange exchange, OutputStream out) throws Exception { //NOPMD if (secretKeyAccessor == null) { return null; } List<String> sigKeyUserids = determineSignaturenUserIds(exchange); List<PGPSecretKeyAndPrivateKeyAndUserId> sigSecretKeysWithPrivateKeyAndUserId = secretKeyAccessor.getSignerKeys(exchange, sigKeyUserids); if (sigSecretKeysWithPrivateKeyAndUserId.isEmpty()) { return null; } exchange.getOut().setHeader(NUMBER_OF_SIGNING_KEYS, Integer.valueOf(sigSecretKeysWithPrivateKeyAndUserId.size())); List<PGPSignatureGenerator> sigGens = new ArrayList<PGPSignatureGenerator>(); for (PGPSecretKeyAndPrivateKeyAndUserId sigSecretKeyWithPrivateKeyAndUserId : sigSecretKeysWithPrivateKeyAndUserId) { PGPPrivateKey sigPrivateKey = sigSecretKeyWithPrivateKeyAndUserId.getPrivateKey(); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, sigSecretKeyWithPrivateKeyAndUserId.getUserId()); int algorithm = sigSecretKeyWithPrivateKeyAndUserId.getSecretKey().getPublicKey().getAlgorithm(); PGPSignatureGenerator sigGen = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(algorithm, findHashAlgorithm(exchange)).setProvider(getProvider())); sigGen.init(PGPSignature.BINARY_DOCUMENT, sigPrivateKey); sigGen.setHashedSubpackets(spGen.generate()); sigGen.generateOnePassVersion(false).encode(out); sigGens.add(sigGen); } return sigGens; }
protected void testInit () throws IOException { if ( this.initialized ) { return; } this.initialized = true; try { this.signatureGenerator = new PGPSignatureGenerator ( new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), this.digestAlgorithm ) ); this.signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey ); this.armoredOutput = new ArmoredOutputStream ( this.stream ); if ( this.version != null ) { this.armoredOutput.setHeader ( "Version", this.version ); } if ( this.inline ) { this.armoredOutput.beginClearText ( this.digestAlgorithm ); } } catch ( final PGPException e ) { throw new IOException ( e ); } }
@Override public void feedHeader ( final ByteBuffer header ) { try { final BcPGPContentSignerBuilder contentSignerBuilder = new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), this.hashAlgorithm ); final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( contentSignerBuilder ); signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey ); if ( header.hasArray () ) { signatureGenerator.update ( header.array (), header.position (), header.remaining () ); } else { final byte[] buffer = new byte[header.remaining ()]; header.get ( buffer ); signatureGenerator.update ( buffer ); } this.value = signatureGenerator.generate ().getEncoded (); logger.info ( "RSA HEADER: {}", this.value ); } catch ( final Exception e ) { throw new RuntimeException ( e ); } }
private static PGPPublicKeyRing addUserId( final PGPPublicKeyRing publicKeyRing, final String userId, final PGPSecretKeyRing secretKeyRing, final char[] passphrase, PGPContentSignerBuilder signerBuilder, final PGPSignatureSubpacketVector hashedSubpackets, final PGPSignatureSubpacketVector unhashedSubpackets) throws PGPException { assertNotNull(publicKeyRing, "publicKeyRing"); assertNotNull(userId, "userId"); final PGPPublicKey masterPublicKey = getMasterKeyOrFail(publicKeyRing); final PGPSecretKey masterSecretKey = secretKeyRing.getSecretKey(masterPublicKey.getKeyID()); assertNotNull(masterSecretKey, "masterSecretKey"); final PGPPrivateKey privateKey = extractPrivateKey(masterSecretKey, passphrase); final PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder); sGen.init(PGPSignature.POSITIVE_CERTIFICATION, privateKey); sGen.setHashedSubpackets(hashedSubpackets); sGen.setUnhashedSubpackets(unhashedSubpackets); final PGPSignature certification = sGen.generateCertification(userId, masterPublicKey); final PGPPublicKey newMasterPublicKey = PGPPublicKey.addCertification(masterPublicKey, userId, certification); PGPPublicKeyRing result = PGPPublicKeyRing.removePublicKey(publicKeyRing, masterPublicKey); result = PGPPublicKeyRing.insertPublicKey(result, newMasterPublicKey); return result; }
public OpenPGPSignature(OpenPGPSecretKey key) throws PGPException { PGPDigestCalculatorProvider pgpDigestCalculator = new JcaPGPDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(); PBESecretKeyDecryptor pbeSecretKeyDecryptor = new JcePBESecretKeyDecryptorBuilder(pgpDigestCalculator).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(key.getPassword()); JcaPGPContentSignerBuilder pgpContentSigner = new JcaPGPContentSignerBuilder(key.getSecretKey().getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(BouncyCastleProvider.PROVIDER_NAME).setDigestProvider(BouncyCastleProvider.PROVIDER_NAME); signature = new PGPSignatureGenerator(pgpContentSigner); PGPPrivateKey privateKey = key.getSecretKey().extractPrivateKey(pbeSecretKeyDecryptor); signature.init(PGPSignature.BINARY_DOCUMENT, privateKey); }
@Override public void sign ( final InputStream in, final OutputStream out, final boolean inline ) throws Exception { final int digest = HashAlgorithmTags.SHA1; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), digest ) ); signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey ); final ArmoredOutputStream armoredOutput = new ArmoredOutputStream ( out ); if ( inline ) { armoredOutput.beginClearText ( digest ); } final byte[] buffer = new byte[4096]; int rc; while ( ( rc = in.read ( buffer ) ) >= 0 ) { if ( inline ) { armoredOutput.write ( buffer, 0, rc ); } signatureGenerator.update ( buffer, 0, rc ); } armoredOutput.endClearText (); final PGPSignature signature = signatureGenerator.generate (); signature.encode ( new BCPGOutputStream ( armoredOutput ) ); armoredOutput.close (); }
private static void processLine(OutputStream aOut, PGPSignatureGenerator sGen, byte[] line) throws SignatureException, IOException { // note: trailing white space needs to be removed from the end of // each line for signature calculation RFC 4880 Section 7.1 int length = getLengthWithoutWhiteSpace(line); if (length > 0) { sGen.update(line, 0, length); } aOut.write(line, 0, line.length); }
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 static void processLine(OutputStream aOut, PGPSignatureGenerator sGen, byte[] line) throws SignatureException, IOException { int length = getLengthWithoutWhiteSpace(line); if (length > 0) { sGen.update(line, 0, length); } aOut.write(line, 0, line.length); }
public void update(byte[] b, int off, int len) { for (PGPSignatureGenerator sig : sigs) sig.update(b, off, len); }
private void embeddedJpegTest() throws Exception { PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(testPubKey, new BcKeyFingerprintCalculator()); PGPSecretKeyRing pgpSec = new PGPSecretKeyRing(testPrivKey, new BcKeyFingerprintCalculator()); PGPPublicKey pubKey = pgpPub.getPublicKey(); PGPUserAttributeSubpacketVectorGenerator vGen = new PGPUserAttributeSubpacketVectorGenerator(); vGen.setImageAttribute(ImageAttribute.JPEG, jpegImage); PGPUserAttributeSubpacketVector uVec = vGen.generate(); PGPSignatureGenerator sGen = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1)); sGen.init(PGPSignature.POSITIVE_CERTIFICATION, pgpSec.getSecretKey().extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass))); PGPSignature sig = sGen.generateCertification(uVec, pubKey); PGPPublicKey nKey = PGPPublicKey.addCertification(pubKey, uVec, sig); Iterator it = nKey.getUserAttributes(); int count = 0; while (it.hasNext()) { PGPUserAttributeSubpacketVector attributes = (PGPUserAttributeSubpacketVector)it.next(); Iterator sigs = nKey.getSignaturesForUserAttribute(attributes); int sigCount = 0; while (sigs.hasNext()) { PGPSignature s = (PGPSignature)sigs.next(); s.init(new BcPGPContentVerifierBuilderProvider(), pubKey); if (!s.verifyCertification(attributes, pubKey)) { fail("added signature failed verification"); } sigCount++; } if (sigCount != 1) { fail("Failed added user attributes signature check"); } count++; } if (count != 1) { fail("didn't find added user attributes"); } nKey = PGPPublicKey.removeCertification(nKey, uVec); count = 0; for (it = nKey.getUserAttributes(); it.hasNext();) { count++; } if (count != 0) { fail("found attributes where none expected"); } }
/** * 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 ); } }
public static byte[] sign( byte data[], PGPPrivateKey privateKey ) throws IOException, PGPException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ArmoredOutputStream aos = new ArmoredOutputStream( bos ); PGPCompressedDataGenerator compressGen = new PGPCompressedDataGenerator( PGPCompressedData.ZLIB ); BCPGOutputStream bcOut = new BCPGOutputStream( compressGen.open( aos ) ); PGPSignatureGenerator signGen = getSignatureGenerator( privateKey, bcOut ); produceSign( data, bcOut, signGen ); compressGen.close(); aos.close(); return bos.toByteArray(); }
@Test public void testSignVerify_OnePass() throws Exception { // Load the keys. PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY); PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY); PGPPublicKey publicKey = publicKeyRing.getPublicKey(); PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey()); // Sign the data and write signature data to "signatureFile". PGPSignatureGenerator signer = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256)); signer.init(PGPSignature.BINARY_DOCUMENT, privateKey); addUserInfoToSignature(publicKey, signer); ByteArrayOutputStream output = new ByteArrayOutputStream(); signer.generateOnePassVersion(false).encode(output); signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); signer.generate().encode(output); byte[] signatureFileData = output.toByteArray(); logger.info(".sig file data: " + dumpHex(signatureFileData)); // Load algorithm information and signature data from "signatureFileData". PGPSignature sig; PGPOnePassSignature onePass; try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPOnePassSignatureList onePassList = (PGPOnePassSignatureList) pgpFact.nextObject(); PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject(); assertThat(onePassList.size()).isEqualTo(1); assertThat(sigList.size()).isEqualTo(1); onePass = onePassList.get(0); sig = sigList.get(0); } // Use "onePass" and "sig" to verify "publicKey" signed the text. onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey); onePass.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); assertThat(onePass.verify(sig)).isTrue(); // Verify that they DIDN'T sign the text "hello monster". onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey); onePass.update("hello monster".getBytes(UTF_8)); assertThat(onePass.verify(sig)).isFalse(); }
@Override public void sign ( final InputStream in, final OutputStream out, final boolean inline ) throws Exception { final int digest = HashAlgorithmTags.SHA1; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), digest ) ); if ( inline ) { signatureGenerator.init ( PGPSignature.CANONICAL_TEXT_DOCUMENT, this.privateKey ); } else { signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey ); } final ArmoredOutputStream armoredOutput = new ArmoredOutputStream ( out ); armoredOutput.setHeader ( "Version", VersionInformation.VERSIONED_PRODUCT ); if ( inline ) { armoredOutput.beginClearText ( digest ); final LineNumberReader lnr = new LineNumberReader ( new InputStreamReader ( in, StandardCharsets.UTF_8 ) ); String line; while ( ( line = lnr.readLine () ) != null ) { if ( lnr.getLineNumber () > 1 ) { signatureGenerator.update ( NL_DATA ); } final byte[] data = trimTrailing ( line ).getBytes ( StandardCharsets.UTF_8 ); if ( inline ) { armoredOutput.write ( data ); armoredOutput.write ( NL_DATA ); } signatureGenerator.update ( data ); } armoredOutput.endClearText (); } else { final byte[] buffer = new byte[4096]; int rc; while ( ( rc = in.read ( buffer ) ) >= 0 ) { signatureGenerator.update ( buffer, 0, rc ); } } final PGPSignature signature = signatureGenerator.generate (); signature.encode ( new BCPGOutputStream ( armoredOutput ) ); armoredOutput.close (); }
@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(); }