List of usage examples for org.bouncycastle.openpgp PGPSignatureGenerator generate
public PGPSignature generate() throws PGPException
From source file:net.staticsnow.nexus.repository.apt.internal.gpg.AptSigningFacet.java
License:Open Source License
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()); }//w w w . j a v a2 s.c om 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(); }
From source file:net.staticsnow.nexus.repository.apt.internal.gpg.AptSigningFacet.java
License:Open Source License
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); }/*w ww . j a v a 2 s . co m*/ return buffer.toByteArray(); }
From source file:org.apache.camel.converter.crypto.PGPDataFormat.java
License:Apache License
public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception { List<String> userids = determineEncryptionUserIds(exchange); List<PGPPublicKey> keys = PGPDataFormatUtil.findPublicKeys(exchange.getContext(), findKeyFileName(exchange), findEncryptionKeyRing(exchange), userids, true); if (keys.isEmpty()) { throw new IllegalArgumentException( "Cannot PGP encrypt message. No public encryption key found for the User Ids " + userids + " in the public keyring. Either specify other User IDs or add correct public keys to the keyring."); }//from w w w .j a v a2 s. com InputStream input = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph); if (armored) { outputStream = new ArmoredOutputStream(outputStream); } PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(findAlgorithm(exchange)).setWithIntegrityPacket(integrity) .setSecureRandom(new SecureRandom()).setProvider(getProvider())); // several keys can be added for (PGPPublicKey key : keys) { encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key)); } OutputStream encOut = encGen.open(outputStream, new byte[BUFFER_SIZE]); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange)); OutputStream comOut = new BufferedOutputStream(comData.open(encOut)); PGPSignatureGenerator sigGen = createSignatureGenerator(exchange, comOut); PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator(); String fileName = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class); if (ObjectHelper.isEmpty(fileName)) { // This marks the file as For Your Eyes Only... may cause problems for the receiver if they use // an automated process to decrypt as the filename is appended with _CONSOLE fileName = PGPLiteralData.CONSOLE; } OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, fileName, new Date(), new byte[BUFFER_SIZE]); try { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { litOut.write(buffer, 0, bytesRead); if (sigGen != null) { sigGen.update(buffer, 0, bytesRead); } litOut.flush(); } } finally { IOHelper.close(litOut); if (sigGen != null) { sigGen.generate().encode(comOut); } IOHelper.close(comOut, encOut, outputStream, input); } }
From source file:org.apache.camel.converter.crypto.PGPKeyAccessDataFormat.java
License:Apache License
public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception { List<String> userids = determineEncryptionUserIds(exchange); List<PGPPublicKey> keys = publicKeyAccessor.getEncryptionKeys(exchange, userids); if (keys.isEmpty()) { throw new IllegalArgumentException( "Cannot PGP encrypt message. No public encryption key found for the User Ids " + userids + " in the public keyring. Either specify other User IDs or add correct public keys to the keyring."); }// w w w . j av a2 s . com exchange.getOut().setHeader(NUMBER_OF_ENCRYPTION_KEYS, Integer.valueOf(keys.size())); InputStream input = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph); if (armored) { outputStream = new ArmoredOutputStream(outputStream); } PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(findAlgorithm(exchange)).setWithIntegrityPacket(integrity) .setSecureRandom(new SecureRandom()).setProvider(getProvider())); // several keys can be added for (PGPPublicKey key : keys) { encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key)); } OutputStream encOut = encGen.open(outputStream, new byte[BUFFER_SIZE]); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange)); OutputStream comOut = new BufferedOutputStream(comData.open(encOut)); List<PGPSignatureGenerator> sigGens = createSignatureGenerator(exchange, comOut); PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator(); String fileName = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class); if (ObjectHelper.isEmpty(fileName)) { // This marks the file as For Your Eyes Only... may cause problems for the receiver if they use // an automated process to decrypt as the filename is appended with _CONSOLE fileName = PGPLiteralData.CONSOLE; } OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, fileName, new Date(), new byte[BUFFER_SIZE]); try { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { litOut.write(buffer, 0, bytesRead); if (sigGens != null && !sigGens.isEmpty()) { for (PGPSignatureGenerator sigGen : sigGens) { // not nested therefore it is the same for all // can this be improved that we only do it for one sigGen and set the result on the others? sigGen.update(buffer, 0, bytesRead); } } litOut.flush(); } } finally { IOHelper.close(litOut); if (sigGens != null && !sigGens.isEmpty()) { // reverse order for (int i = sigGens.size() - 1; i > -1; i--) { PGPSignatureGenerator sigGen = sigGens.get(i); sigGen.generate().encode(comOut); } } IOHelper.close(comOut, encOut, outputStream, input); } }
From source file:org.apache.ivy.plugins.signer.bouncycastle.OpenPGPSignatureGenerator.java
License:Apache License
public void sign(File src, File dest) throws IOException { OutputStream out = null;/*from w w w. j a v a 2 s. c o m*/ InputStream in = null; InputStream keyIn = null; try { if (secring == null) { secring = System.getProperty("user.home") + "/.gnupg/secring.gpg"; } if (pgpSec == null) { keyIn = new FileInputStream(secring); pgpSec = readSecretKey(keyIn); } PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(password.toCharArray(), BouncyCastleProvider.PROVIDER_NAME); PGPSignatureGenerator sGen = new PGPSignatureGenerator(pgpSec.getPublicKey().getAlgorithm(), PGPUtil.SHA1, BouncyCastleProvider.PROVIDER_NAME); sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); in = new FileInputStream(src); out = new BCPGOutputStream(new ArmoredOutputStream(new FileOutputStream(dest))); int ch = 0; while ((ch = in.read()) >= 0) { sGen.update((byte) ch); } sGen.generate().encode(out); } catch (SignatureException e) { IOException ioexc = new IOException(); ioexc.initCause(e); throw ioexc; } catch (PGPException e) { IOException ioexc = new IOException(); ioexc.initCause(e); throw ioexc; } catch (NoSuchAlgorithmException e) { IOException ioexc = new IOException(); ioexc.initCause(e); throw ioexc; } catch (NoSuchProviderException e) { IOException ioexc = new IOException(); ioexc.initCause(e); throw ioexc; } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (keyIn != null) { try { keyIn.close(); } catch (IOException e) { } } } }
From source file:org.brownsocks.payments.gateways.enets.pgp.BCPGPProvider.java
@Override public String signAndEncrypt(String message) throws IOException { try {/* w ww .ja v a 2s . co m*/ /* 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); } }
From source file:org.eclipse.packagedrone.repo.signing.pgp.internal.AbstractSecretKeySigningService.java
License:Open Source License
@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 {/*ww w.j av a2 s. c o m*/ 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(); }
From source file:org.eclipse.packagedrone.utils.rpm.signature.RsaHeaderSignatureProcessor.java
License:Open Source License
@Override public void feedHeader(final ByteBuffer header) { try {// w w w . java2 s. c om 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); } }
From source file:org.elasticsearch.plugins.InstallPluginCommandTests.java
License:Apache License
private String signature(final byte[] bytes, final PGPSecretKey secretKey) { try {// w w w .j a v a 2 s.c o m final PGPPrivateKey privateKey = secretKey.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().build()) .build("passphrase".toCharArray())); final PGPSignatureGenerator generator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder( privateKey.getPublicKeyPacket().getAlgorithm(), HashAlgorithmTags.SHA512)); generator.init(PGPSignature.BINARY_DOCUMENT, privateKey); final ByteArrayOutputStream output = new ByteArrayOutputStream(); try (BCPGOutputStream pout = new BCPGOutputStream(new ArmoredOutputStream(output)); InputStream is = new ByteArrayInputStream(bytes)) { final byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer)) != -1) { generator.update(buffer, 0, read); } generator.generate().encode(pout); } return new String(output.toByteArray(), "UTF-8"); } catch (IOException | PGPException e) { throw new RuntimeException(e); } }
From source file:org.gradle.plugins.signing.signatory.pgp.PgpSignatory.java
License:Apache License
/** * Exhausts {@code toSign}, and writes the signature to {@code signatureDestination}. * * The caller is responsible for closing the streams, though the output WILL be flushed. *//* ww w. j a va2s . com*/ @Override public void sign(InputStream toSign, OutputStream signatureDestination) { PGPSignatureGenerator generator = createSignatureGenerator(); try { feedGeneratorWith(toSign, generator); PGPSignature signature = generator.generate(); writeSignatureTo(signatureDestination, signature); } catch (IOException e) { throw new UncheckedIOException(e); } catch (PGPException e) { throw new UncheckedException(e); } }