List of usage examples for org.bouncycastle.bcpg BCPGOutputStream BCPGOutputStream
public BCPGOutputStream(OutputStream out)
From source file:genkeys.java
License:Open Source License
private static SecretKeyPacket secretKeyPacket(KeyPair key, int cipher, boolean useSHA1, S2K s2k, String pass) throws NoSuchProviderException, PGPException { int algorithm; if (key.getPrivate().getAlgorithm() == "RSA") { algorithm = PGPPublicKey.RSA_GENERAL; } else {/*ww w .ja v a 2 s .c o m*/ algorithm = PGPPublicKey.DSA; } Date time = new Date(); PGPKeyPair keyPair = new PGPKeyPair(algorithm, key.getPublic(), key.getPrivate(), time, "BC"); PublicKeyPacket pubPk = publicKeyPacket(key.getPublic(), algorithm, time); BCPGObject secKey; switch (keyPair.getPublicKey().getAlgorithm()) { case PGPPublicKey.RSA_ENCRYPT: case PGPPublicKey.RSA_SIGN: case PGPPublicKey.RSA_GENERAL: RSAPrivateCrtKey rsK = (RSAPrivateCrtKey) keyPair.getPrivateKey().getKey(); secKey = new RSASecretBCPGKey(rsK.getPrivateExponent(), rsK.getPrimeP(), rsK.getPrimeQ()); break; case PGPPublicKey.DSA: DSAPrivateKey dsK = (DSAPrivateKey) keyPair.getPrivateKey().getKey(); secKey = new DSASecretBCPGKey(dsK.getX()); break; case PGPPublicKey.ELGAMAL_ENCRYPT: case PGPPublicKey.ELGAMAL_GENERAL: ElGamalPrivateKey esK = (ElGamalPrivateKey) keyPair.getPrivateKey().getKey(); secKey = new ElGamalSecretBCPGKey(esK.getX()); break; default: throw new PGPException("unknown key class"); } Cipher c = cipher(cipher); SecretKeyPacket secPk; try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); BCPGOutputStream pOut = new BCPGOutputStream(bOut); pOut.writeObject(secKey); byte[] keyData = bOut.toByteArray(); pOut.write(checksum(useSHA1, keyData, keyData.length)); if (c != null) { SecretKey skey = PGPUtil.makeKeyFromPassPhrase(cipher, s2k, pass.toCharArray(), "BC"); c.init(Cipher.ENCRYPT_MODE, skey, new SecureRandom()); byte[] iv = c.getIV(); byte[] encData = c.doFinal(bOut.toByteArray()); if (useSHA1) { secPk = new SecretKeyPacket(pubPk, cipher, SecretKeyPacket.USAGE_SHA1, s2k, iv, encData); } else { secPk = new SecretKeyPacket(pubPk, cipher, SecretKeyPacket.USAGE_CHECKSUM, s2k, iv, encData); } } else { secPk = new SecretKeyPacket(pubPk, cipher, null, null, bOut.toByteArray()); } } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Exception encrypting key", e); } return secPk; }
From source file:genkeys.java
License:Open Source License
private static void exportSecretKey(OutputStream out, KeyPair key, int cipher, int s2kmode, int hashAlgorithm, boolean useSHA1, String pass, boolean armor) throws IOException, NoSuchProviderException, PGPException { if (armor) {/*w w w . j a va 2s . c o m*/ out = new ArmoredOutputStream(out); } SecureRandom rand = new SecureRandom(); byte[] iv = new byte[8]; rand.nextBytes(iv); S2K s2k = new S2K(hashAlgorithm, iv, 0x60); SecretKeyPacket packet = secretKeyPacket(key, cipher, useSHA1, s2k, pass); BCPGOutputStream bcOut; if (out instanceof BCPGOutputStream) { bcOut = (BCPGOutputStream) out; } else { bcOut = new BCPGOutputStream(out); } bcOut.writePacket(packet); if (armor) { out.close(); } }
From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void sign(final OutputStream outputStream, final InputStream inputStream, final String keyInfo) { try {/*from w w w .j a va 2 s. com*/ final File keyFile = this.secretKeyRing; final char[] pass = this.secretKeyRingPassword; final ArmoredOutputStream out = new ArmoredOutputStream(outputStream); final PGPSecretKey pgpSec = this.getSignKey(keyInfo); // readSecretKey(new // FileInputStream(keyFile)); final PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass)); final PGPSignatureGenerator sGen = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1)); sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); final Iterator it = pgpSec.getPublicKey().getUserIDs(); if (it.hasNext()) { final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, (String) it.next()); sGen.setHashedSubpackets(spGen.generate()); } final PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZLIB); final BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out)); sGen.generateOnePassVersion(false).encode(bOut); final PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); final byte[] buffer = new byte[1 << 16]; final OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, "", new Date(), buffer); int ch = 0; while ((ch = inputStream.read()) >= 0) { lOut.write(ch); sGen.update((byte) ch); } lGen.close(); sGen.generate().encode(bOut); cGen.close(); out.close(); } catch (final FileNotFoundException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final PGPException e) { e.printStackTrace(); } catch (final SignatureException e) { e.printStackTrace(); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * UNUSED IN FRIENDLY BACKUP/*from w ww . j a va 2 s . c om*/ * Sign the passed in message stream (version 3 signature) */ private void signDataV3(File inFile, OutputStream aOut, PGPPublicKey publicKey, PGPPrivateKey privateKey) throws PGPException { try { PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(aOut)); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(true); PGPV3SignatureGenerator s3Gen = new PGPV3SignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC"); s3Gen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey); s3Gen.generateOnePassVersion(false).encode(bOut); OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, inFile); FileInputStream fIn = new FileInputStream(inFile); int ch; while ((ch = fIn.read()) >= 0) { lOut.write(ch); s3Gen.update((byte) ch); } fIn.close(); // close() finishes the writing of the literal data and flushes the stream // It does not close bOut so this is ok here lGen.close(); // Generate the signature s3Gen.generate().encode(bOut); // Must not close bOut here bOut.finish(); bOut.flush(); cGen.close(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in signing", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Sign the passed in message stream//from w w w .ja v a2s . c o m */ private void signData(File inFile, OutputStream aOut, PGPPublicKey publicKey, PGPPrivateKey privateKey) throws PGPException { try { PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(aOut)); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); PGPSignatureGenerator sGen = new PGPSignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC"); sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey); @SuppressWarnings("unchecked") Iterator<String> users = publicKey.getUserIDs(); if (users.hasNext()) { PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, users.next()); sGen.setHashedSubpackets(spGen.generate()); } sGen.generateOnePassVersion(false).encode(bOut); OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, inFile); FileInputStream fIn = new FileInputStream(inFile); int ch; while ((ch = fIn.read()) >= 0) { lOut.write(ch); sGen.update((byte) ch); } fIn.close(); // close() finishes the writing of the literal data and flushes the stream // It does not close bOut so this is ok here lGen.close(); // Generate the signature sGen.generate().encode(bOut); // Must not close bOut here bOut.finish(); bOut.flush(); cGen.close(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in signing", e); } }
From source file:com.github.sannies.nexusaptplugin.sign.PGPSigner.java
License:Apache License
/** * Creates a clear sign signature over the input data. (Not detached) * * @param input the content to be signed * @param output the output destination of the signature *///from w w w . j ava 2 s .c o m public void clearSign(InputStream input, OutputStream output) throws IOException, PGPException, GeneralSecurityException { int digest = PGPUtil.SHA1; PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest)); signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey); ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output); armoredOutput.beginClearText(digest); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String line; while ((line = reader.readLine()) != null) { // trailing spaces must be removed for signature calculation (see http://tools.ietf.org/html/rfc4880#section-7.1) byte[] data = trim(line).getBytes("UTF-8"); armoredOutput.write(data); armoredOutput.write(EOL); signatureGenerator.update(data); signatureGenerator.update(EOL); } armoredOutput.endClearText(); PGPSignature signature = signatureGenerator.generate(); signature.encode(new BCPGOutputStream(armoredOutput)); armoredOutput.close(); }
From source file:com.google.gerrit.gpg.PushCertificateCheckerTest.java
License:Apache License
private PushCertificate newSignedCert(String nonce, TestKey signingKey) throws Exception { PushCertificateIdent ident = new PushCertificateIdent(signingKey.getFirstUserId(), System.currentTimeMillis(), -7 * 60); String payload = "certificate version 0.1\n" + "pusher " + ident.getRaw() + "\n" + "pushee test://localhost/repo.git\n" + "nonce " + nonce + "\n" + "\n" + "0000000000000000000000000000000000000000" + " deadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + " refs/heads/master\n"; PGPSignatureGenerator gen = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(signingKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)); gen.init(PGPSignature.BINARY_DOCUMENT, signingKey.getPrivateKey()); gen.update(payload.getBytes(UTF_8)); PGPSignature sig = gen.generate();/*from w w w. j a va2s . c o m*/ ByteArrayOutputStream bout = new ByteArrayOutputStream(); try (BCPGOutputStream out = new BCPGOutputStream(new ArmoredOutputStream(bout))) { sig.encode(out); } String cert = payload + new String(bout.toByteArray(), UTF_8); Reader reader = new InputStreamReader(new ByteArrayInputStream(cert.getBytes(UTF_8))); PushCertificateParser parser = new PushCertificateParser(tr.getRepository(), signedPushConfig); return parser.parse(reader); }
From source file:com.navnorth.learningregistry.LRSigner.java
License:Apache License
/** * Encodes the provided message with the private key and pass phrase set in configuration * * @param message Message to encode//from w w w . ja v a 2 s.c o m * @return Encoded message * @throws LRException SIGNING_FAILED if the document cannot be signed, NO_KEY if the key cannot be obtained */ private String signEnvelopeData(String message) throws LRException { // Throw an exception if any of the required fields are null if (passPhrase == null || publicKeyLocation == null || privateKey == null) { throw new LRException(LRException.NULL_FIELD); } // Add the provider here so that after signing, we can remove the provider. // This allows using this code from multiple separate class loaders while Bouncy Castle is on a separate class loader BouncyCastleProvider provider = new BouncyCastleProvider(); Security.addProvider(provider); try { // Get an InputStream for the private key InputStream privateKeyStream = getPrivateKeyStream(privateKey); // Get an OutputStream for the result ByteArrayOutputStream result = new ByteArrayOutputStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(result); // Get the pass phrase char[] privateKeyPassword = passPhrase.toCharArray(); try { // Get the private key from the InputStream PGPSecretKey sk = readSecretKey(privateKeyStream); PGPPrivateKey pk = sk.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(privateKeyPassword)); PGPSignatureGenerator sGen = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(sk.getPublicKey().getAlgorithm(), PGPUtil.SHA256) .setProvider("BC")); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); // Clear sign the message java.util.Iterator it = sk.getPublicKey().getUserIDs(); if (it.hasNext()) { spGen.setSignerUserID(false, (String) it.next()); sGen.setHashedSubpackets(spGen.generate()); } aOut.beginClearText(PGPUtil.SHA256); sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, pk); byte[] msg = message.getBytes(); sGen.update(msg, 0, msg.length); aOut.write(msg, 0, msg.length); BCPGOutputStream bOut = new BCPGOutputStream(aOut); aOut.endClearText(); sGen.generate().encode(bOut); aOut.close(); String strResult = result.toString("utf8"); // for whatever reason, bouncycastle is failing to put a linebreak before "-----BEGIN PGP SIGNATURE" strResult = strResult.replaceAll("([a-z0-9])-----BEGIN PGP SIGNATURE-----", "$1\n-----BEGIN PGP SIGNATURE-----"); return strResult; } catch (Exception e) { throw new LRException(LRException.SIGNING_FAILED, e); } finally { try { if (privateKeyStream != null) { privateKeyStream.close(); } result.close(); } catch (IOException e) { //Could not close the streams } } } finally { Security.removeProvider(provider.getName()); } }
From source file:com.verhas.licensor.License.java
License:Open Source License
/** * Encode the currently loaded/created license. * /*ww w . ja v a 2 s . co m*/ * @param keyPassPhraseString * the pass phrase to the signing key that was loaded. * @return the license encoded as ascii string. * @throws java.io.IOException * @throws java.security.NoSuchAlgorithmException * @throws java.security.NoSuchProviderException * @throws org.bouncycastle.openpgp.PGPException * @throws java.security.SignatureException */ public String encodeLicense(final String keyPassPhraseString) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, PGPException, SignatureException { final char[] keyPassPhrase = keyPassPhraseString.toCharArray(); final String licensePlain = getLicenseString(); final ByteArrayOutputStream baOut = new ByteArrayOutputStream(); final OutputStream out = new ArmoredOutputStream(baOut); final PGPPrivateKey pgpPrivKey = key.extractPrivateKey(keyPassPhrase, "BC"); final PGPSignatureGenerator sGen = new PGPSignatureGenerator(key.getPublicKey().getAlgorithm(), hashAlgorithm, "BC"); sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); @SuppressWarnings("unchecked") final Iterator<String> it = key.getPublicKey().getUserIDs(); if (it.hasNext()) { final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, it.next()); sGen.setHashedSubpackets(spGen.generate()); } final PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB); final BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out)); sGen.generateOnePassVersion(false).encode(bOut); final PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); final OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, "licenseFileName-Ignored", new Date(), new byte[1024]); final InputStream fIn = new ByteArrayInputStream(licensePlain.getBytes("utf-8")); int ch = 0; while ((ch = fIn.read()) >= 0) { lOut.write(ch); sGen.update((byte) ch); } lGen.close(); sGen.generate().encode(bOut); cGen.close(); out.close(); return new String(baOut.toByteArray()); }
From source file:com.zwitserloot.ivyplusplus.mavencentral.CreateDetachedSignatures_.java
License:Open Source License
void signFile(InputStream fileData, PGPSecretKey signingKey, String passphrase, OutputStream out) throws IOException, NoSuchProviderException, PGPException, NoSuchAlgorithmException, SignatureException {/*from w ww. ja v a 2 s . c o m*/ PGPPrivateKey privKey = signingKey.extractPrivateKey(passphrase.toCharArray(), "BC"); PGPSignatureGenerator sigGen = new PGPSignatureGenerator(signingKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC"); sigGen.initSign(PGPSignature.BINARY_DOCUMENT, privKey); out = new ArmoredOutputStream(out); BCPGOutputStream bOut = new BCPGOutputStream(out); byte[] b = new byte[4096]; while (true) { int r = fileData.read(b); if (r == -1) break; sigGen.update(b, 0, r); } sigGen.generate().encode(bOut); bOut.close(); out.close(); }