List of usage examples for org.bouncycastle.openpgp PGPSignatureGenerator generateOnePassVersion
public PGPOnePassSignature generateOnePassVersion(boolean isNested) throws PGPException
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 . ja v a 2s. c om*/ 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.arcusx.simplepgp.PgpDataEncryptor.java
public void encryptAndSign(InputStream dataIn, InputStream recipientPublicKeyFileIn, String dataFileName, InputStream senderPrivateKeyFileIn, OutputStream dataOut, boolean isArmoredOutput) throws IOException, PGPException { PGPCompressedDataGenerator comData = null; try {/*from w ww . j a va 2 s . com*/ OutputStream out = dataOut; PGPPublicKey recipientPublicKey = PgpKeyUtils.readPublicKey(recipientPublicKeyFileIn); if (isArmoredOutput) { out = new ArmoredOutputStream(out); } BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES); dataEncryptor.setWithIntegrityPacket(true); dataEncryptor.setSecureRandom(new SecureRandom()); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor); encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(recipientPublicKey)); OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]); // Initialize compressed data generator PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator( PGPCompressedData.ZIP); OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BUFFER_SIZE]); // Initialize signature generator final PGPSecretKey senderSecretKey = PgpKeyUtils.findSecretKey(senderPrivateKeyFileIn); PGPPrivateKey privateKey = PgpKeyUtils.getPrivateKeyFrom(senderSecretKey); PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder( senderSecretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(signerBuilder); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator(); signatureSubpacketGenerator.setSignerUserID(false, PgpKeyUtils.getUserIdFrom(senderSecretKey)); signatureGenerator.setHashedSubpackets(signatureSubpacketGenerator.generate()); signatureGenerator.generateOnePassVersion(false).encode(compressedOut); // Initialize literal data generator PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, dataFileName, new Date(), new byte[BUFFER_SIZE]); byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = dataIn.read(buf)) > 0) { literalOut.write(buf, 0, len); signatureGenerator.update(buf, 0, len); } dataIn.close(); literalDataGenerator.close(); // generate the signature, compress, encrypt and write to the "out" stream signatureGenerator.generate().encode(compressedOut); compressedDataGenerator.close(); encryptedDataGenerator.close(); if (isArmoredOutput) { out.close(); } } finally { if (comData != null) { comData.close(); } IOUtils.closeQuietly(dataOut); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Sign the passed in message stream/*from ww w. j a v a2s. co 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.goodvikings.cryptim.api.KeyRing.java
License:BEER-WARE LICENSE
public void signEncryptMessage(InputStream in, OutputStream out, String jid) throws IOException, PGPException, SignatureException { out = new ArmoredOutputStream(out); PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SYMM_ALG) .setWithIntegrityPacket(true).setSecureRandom(rand).setProvider(PROVIDER)); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(keys.get(jid)).setProvider(PROVIDER)); OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]); OutputStream compressedData = new PGPCompressedDataGenerator(COMP_ALG).open(encryptedOut); PGPSignatureGenerator sGen = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(kp.getPrivateKey().getPublicKeyPacket().getAlgorithm(), HASH_ALG) .setProvider(PROVIDER)); sGen.init(PGPSignature.BINARY_DOCUMENT, kp.getPrivateKey()); sGen.generateOnePassVersion(false).encode(compressedData); OutputStream finalOut = new PGPLiteralDataGenerator().open(compressedData, PGPLiteralData.BINARY, "", new Date(), new byte[BUFFER_SIZE]); byte[] buf = new byte[BUFFER_SIZE]; int len;/* w w w .ja v a 2 s .co m*/ while ((len = in.read(buf)) > 0) { finalOut.write(buf, 0, len); sGen.update(buf, 0, len); } in.close(); finalOut.close(); sGen.generate().encode(compressedData); compressedData.close(); encryptedOut.close(); out.close(); }
From source file:com.verhas.licensor.License.java
License:Open Source License
/** * Encode the currently loaded/created license. * /*from www .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:crypttools.PGPCryptoBC.java
License:Open Source License
public String signData(String data, String passphrase) throws Exception { Security.addProvider(new BouncyCastleProvider()); InputStream keyInputStream = new ByteArrayInputStream(this.armoredSecretKey); PGPSecretKey pgpSecretKey = readSecretKey(keyInputStream); PGPPrivateKey pgpPrivateKey = pgpSecretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passphrase.toCharArray())); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(pgpSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1) .setProvider("BC")); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, pgpPrivateKey); @SuppressWarnings("unchecked") Iterator<String> it = pgpSecretKey.getPublicKey().getUserIDs(); if (it.hasNext()) { PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, it.next()); signatureGenerator.setHashedSubpackets(spGen.generate()); }// www .ja va 2 s. c om ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); OutputStream outputStream = new ArmoredOutputStream(byteOutputStream); PGPCompressedDataGenerator compressDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB); BCPGOutputStream bcOutputStream = new BCPGOutputStream(compressDataGenerator.open(outputStream)); signatureGenerator.generateOnePassVersion(false).encode(bcOutputStream); PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); File fileToSign = File.createTempFile("temp", ".scrap"); FileUtils.writeStringToFile(fileToSign, data); OutputStream literalDataGenOutputStream = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY, fileToSign); FileInputStream fis = new FileInputStream(fileToSign); int ch; while ((ch = fis.read()) >= 0) { literalDataGenOutputStream.write(ch); signatureGenerator.update((byte) ch); } literalDataGenerator.close(); fis.close(); signatureGenerator.generate().encode(bcOutputStream); compressDataGenerator.close(); outputStream.close(); fileToSign.delete(); return new String(byteOutputStream.toByteArray(), "UTF-8"); }
From source file:dorkbox.util.crypto.CryptoPGP.java
License:Apache License
/** * Sign a message using our private PGP key file, with a variety of options *///from w w w . j ava 2s . c o m @SuppressWarnings("Duplicates") public static byte[] sign(InputStream privateKeyInputStream, String userId, char[] password, InputStream message, int signatureType, boolean compressSignature, boolean asciiArmoredOutput, boolean includeDataInSignature, boolean generateUserIdSubPacket, boolean generateOnePassVersion) throws PGPException { List<PGPSecretKey> secretKeys = getSecretKeys(privateKeyInputStream, userId); PGPSignatureGenerator signature = createSignature(secretKeys, password, signatureType, generateUserIdSubPacket); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream outputStream = byteArrayOutputStream; if (asciiArmoredOutput) { outputStream = new ArmoredOutputStream(byteArrayOutputStream); } PGPCompressedDataGenerator compressedDataGenerator = null; BCPGOutputStream bcOutputStream; if (compressSignature) { compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB); try { bcOutputStream = new BCPGOutputStream(compressedDataGenerator.open(outputStream)); } catch (IOException e) { throw new PGPException("Unable to open compression stream in the signature", e); } } else { bcOutputStream = new BCPGOutputStream(outputStream); } if (generateOnePassVersion) { try { signature.generateOnePassVersion(false).encode(bcOutputStream); } catch (IOException e) { throw new PGPException("Unable to generate OnePass signature header", e); } } PGPLiteralDataGenerator literalDataGenerator = null; OutputStream literalDataOutput = null; if (includeDataInSignature) { literalDataGenerator = new PGPLiteralDataGenerator(); try { literalDataOutput = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY, "_CONSOLE", message.available(), new Date()); } catch (IOException e1) { throw new PGPException("Unable to generate Literal Data signature header", e1); } } try { byte[] buffer = new byte[4096]; int read; // update bytes in the streams if (literalDataOutput != null) { while ((read = message.read(buffer)) > 0) { literalDataOutput.write(buffer, 0, read); signature.update(buffer, 0, read); } literalDataOutput.flush(); } else { while ((read = message.read(buffer)) > 0) { signature.update(buffer, 0, read); } } // close generators and update signature if (literalDataGenerator != null) { literalDataGenerator.close(); } signature.generate().encode(bcOutputStream); if (compressedDataGenerator != null) { compressedDataGenerator.close(); } } catch (Exception e) { e.printStackTrace(); } finally { IO.close(bcOutputStream); IO.close(outputStream); IO.close(literalDataOutput); } return byteArrayOutputStream.toByteArray(); }
From source file:dorkbox.util.crypto.CryptoPGP.java
License:Apache License
/** * Sign a message using our private PGP key file, with a variety of options *///from w w w.j a v a 2 s. c o m @SuppressWarnings("Duplicates") public static byte[] sign(InputStream privateKeyInputStream, String userId, char[] password, File fileMessage, int signatureType, boolean compressSignature, boolean asciiArmoredOutput, boolean includeDataInSignature, boolean generateUserIdSubPacket, boolean generateOnePassVersion) throws PGPException { List<PGPSecretKey> secretKeys = getSecretKeys(privateKeyInputStream, userId); PGPSignatureGenerator signature = createSignature(secretKeys, password, signatureType, generateUserIdSubPacket); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream outputStream = byteArrayOutputStream; if (asciiArmoredOutput) { outputStream = new ArmoredOutputStream(byteArrayOutputStream); } PGPCompressedDataGenerator compressedDataGenerator = null; BCPGOutputStream bcOutputStream; if (compressSignature) { compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB); try { bcOutputStream = new BCPGOutputStream(compressedDataGenerator.open(outputStream)); } catch (IOException e) { throw new PGPException("Unable to open compression stream in the signature", e); } } else { bcOutputStream = new BCPGOutputStream(outputStream); } if (generateOnePassVersion) { try { signature.generateOnePassVersion(false).encode(bcOutputStream); } catch (IOException e) { throw new PGPException("Unable to generate OnePass signature header", e); } } PGPLiteralDataGenerator literalDataGenerator = null; OutputStream literalDataOutput = null; if (includeDataInSignature) { literalDataGenerator = new PGPLiteralDataGenerator(); try { literalDataOutput = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY, fileMessage); } catch (IOException e1) { throw new PGPException("Unable to generate Literal Data signature header", e1); } } try { final FileInputStream fileInputStream = new FileInputStream(fileMessage); byte[] buffer = new byte[4096]; int read; // update bytes in the streams if (literalDataOutput != null) { while ((read = fileInputStream.read(buffer)) > 0) { literalDataOutput.write(buffer, 0, read); signature.update(buffer, 0, read); } literalDataOutput.flush(); } else { while ((read = fileInputStream.read(buffer)) > 0) { signature.update(buffer, 0, read); } } // close generators and update signature if (literalDataGenerator != null) { literalDataGenerator.close(); } signature.generate().encode(bcOutputStream); if (compressedDataGenerator != null) { compressedDataGenerator.close(); } } catch (Exception e) { e.printStackTrace(); } finally { IO.close(bcOutputStream); IO.close(outputStream); IO.close(literalDataOutput); } return byteArrayOutputStream.toByteArray(); }
From source file:eu.mrbussy.security.crypto.pgp.PGPEncryptor.java
License:Open Source License
public void encryptFile(File inputFile, File outputFile) throws IOException, NoSuchProviderException, PGPException { if (pedg == null) { pedg = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, checkIntegrity, new SecureRandom(), "BC"); try {/*from w ww .ja va 2 s. c o m*/ pedg.addMethod(publicKey); } catch (PGPException e) { throw new PGPException("Error when creating PGP encryptino data generator."); } } OutputStream fileOutStream = new FileOutputStream(outputFile); if (isArmored) { fileOutStream = new ArmoredOutputStream(fileOutStream); } OutputStream encryptdOutStream = pedg.open(fileOutStream, new byte[1 << 16]); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); OutputStream compressedOutStream = comData.open(encryptdOutStream); try { PGPSignatureGenerator sg = null; if (isSigning) { InputStream keyInputStream = new FileInputStream(new File(signingPrivateKeyFilePath)); PGPSecretKey secretKey = PGPUtils.findSecretKey(keyInputStream); PGPPrivateKey privateKey = secretKey.extractPrivateKey(signingPrivateKeyPassword.toCharArray(), "BC"); sg = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC"); sg.initSign(PGPSignature.BINARY_DOCUMENT, privateKey); Iterator it = secretKey.getPublicKey().getUserIDs(); if (it.hasNext()) { PGPSignatureSubpacketGenerator ssg = new PGPSignatureSubpacketGenerator(); ssg.setSignerUserID(false, (String) it.next()); sg.setHashedSubpackets(ssg.generate()); } sg.generateOnePassVersion(false).encode(compressedOutStream); } PGPLiteralDataGenerator lg = new PGPLiteralDataGenerator(); OutputStream literalDataOutStream = lg.open(compressedOutStream, PGPLiteralData.BINARY, inputFile); byte[] bytes = IOUtils.toByteArray(new FileInputStream(inputFile)); literalDataOutStream.write(bytes); if (isSigning) { sg.update(bytes); sg.generate().encode(compressedOutStream); } literalDataOutStream.close(); lg.close(); compressedOutStream.close(); comData.close(); pedg.close(); fileOutStream.close(); } catch (PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@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);/*from w w w .j a va 2 s . c o m*/ 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(); }