List of usage examples for org.bouncycastle.openpgp PGPSignatureGenerator setHashedSubpackets
public void setHashedSubpackets(PGPSignatureSubpacketVector hashedPcks)
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
/** * Add user ID to signature file.//from w w w .j a va 2 s.c o m * * <p>This adds information about the identity of the signer to the signature file. It's not * required, but I'm guessing it could be a lifesaver if somewhere down the road, people lose * track of the public keys and need to figure out how to verify a couple blobs. This would at * least tell them which key to download from the MIT keyserver. * * <p>But the main reason why I'm using this is because I copied it from the code of another * Googler who was also uncertain about the precise reason why it's needed. */ private void addUserInfoToSignature(PGPPublicKey publicKey, PGPSignatureGenerator signer) { @SuppressWarnings("unchecked") // Safe by specification. Iterator<String> uidIter = publicKey.getUserIDs(); if (uidIter.hasNext()) { PGPSignatureSubpacketGenerator spg = new PGPSignatureSubpacketGenerator(); spg.setSignerUserID(false, uidIter.next()); signer.setHashedSubpackets(spg.generate()); } }
From source file:google.registry.rde.RydePgpSigningOutputStream.java
License:Open Source License
/** * Add user ID to signature file./*from w w w . j a v a 2s .c o m*/ * * <p>This adds information about the identity of the signer to the signature file. It's not * required, but I'm guessing it could be a lifesaver if somewhere down the road, people lose * track of the public keys and need to figure out how to verify a couple blobs. This would at * least tell them which key to download from the MIT keyserver. * * <p>But the main reason why I'm using this is because I copied it from the code of another * googler who was also uncertain about the precise reason why it's needed. */ private static void addUserInfoToSignature(PGPPublicKey publicKey, PGPSignatureGenerator signer) { @SuppressWarnings("unchecked") // safe by specification. Iterator<String> uidIter = publicKey.getUserIDs(); if (uidIter.hasNext()) { PGPSignatureSubpacketGenerator spg = new PGPSignatureSubpacketGenerator(); spg.setSignerUserID(false, uidIter.next()); signer.setHashedSubpackets(spg.generate()); } }
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()); }//from w ww.ja va 2s . c o m 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:org.apache.camel.converter.crypto.PGPDataFormat.java
License:Apache License
protected PGPSignatureGenerator createSignatureGenerator(Exchange exchange, OutputStream out) throws IOException, PGPException, NoSuchProviderException, NoSuchAlgorithmException { String sigKeyFileName = findSignatureKeyFileName(exchange); String sigKeyUserid = findSignatureKeyUserid(exchange); String sigKeyPassword = findSignatureKeyPassword(exchange); byte[] sigKeyRing = findSignatureKeyRing(exchange); if ((sigKeyFileName == null && sigKeyRing == null) || sigKeyUserid == null || sigKeyPassword == null) { return null; }/*from www . j a va 2 s. c om*/ PGPSecretKey sigSecretKey = PGPDataFormatUtil.findSecretKey(exchange.getContext(), sigKeyFileName, sigKeyRing, sigKeyPassword, sigKeyUserid, getProvider()); if (sigSecretKey == null) { throw new IllegalArgumentException(String.format( "Cannot PGP encrypt message. No secret key found for User ID %s. Either add a key with this User ID to the secret keyring or change the configured User ID.", sigKeyUserid)); } PGPPrivateKey sigPrivateKey = sigSecretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder() .setProvider(getProvider()).build(sigKeyPassword.toCharArray())); if (sigPrivateKey == null) { // this exception will never happen throw new IllegalArgumentException("Signature private key is null, cannot proceed"); } PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, sigKeyUserid); int algorithm = sigSecretKey.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); return sigGen; }
From source file:org.apache.camel.converter.crypto.PGPKeyAccessDataFormat.java
License:Apache License
protected List<PGPSignatureGenerator> createSignatureGenerator(Exchange exchange, OutputStream out) throws Exception { if (secretKeyAccessor == null) { return null; }/* w w w .j a v a2 s . c om*/ 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; }
From source file:org.opentestsystem.delivery.testreg.transformer.GPGEncryptor.java
License:Open Source License
/** * Uses the Legion of the Bouncy Castle (aka BouncyCastle) PGP API to encrypt, compress, and sign the input. * // w w w . j av a 2s . c om * The configured landing zone public key is used to encrypt the input. Only the landing zone private key will be * able to decrypt. * * The configured test registration private key is used to sign the input. This can be verified by the landing zone * to prove that this specific test registration instance created the data. * * @param input * A byte array * @return A byte array comprised of a PGP/GPG compatible binary encrypted and signed output */ @Transformer public Message<File> encryptStream(final File input, final @Header("dwBatchUuid") String dwBatchUuid, final @Header("fileSuffix") String fileSuffix, final @Header("recordsSent") int recordsSent, final @Header("tempPaths") List<Path> tempPaths, final @Header("dwConfigType") DwConfigType dwConfigType) { String debugPrefix = dwConfigType + " DW Config: "; long curTime = System.currentTimeMillis(); File tmpEncFile; try { PGPPublicKey landingZonePubKey = findLandingZonePublicKey(dwConfigType); PGPSecretKey testRegSecretKey = findTestRegSecretKey(); PGPPrivateKey testRegPrivateKey = testRegSecretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(getPassphrase())); // //////////////////// // setup encryptor PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_256).setWithIntegrityPacket(true) .setSecureRandom(new SecureRandom()).setProvider("BC")); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(landingZonePubKey).setProvider("BC")); // This outputstream, encryptedSignedOutputStream is the ultimate target that will contain the encrypted and // signed output Path tempEncPath = Files.createTempFile(DwBatchHandler.DW_ENC_TMP_PREFIX, (dwConfigType == DwConfigType.SBAC ? DwBatchHandler.SBAC_DW_NAME : DwBatchHandler.LOCAL_DW_NAME) + fileSuffix); tempPaths.add(tempEncPath); tmpEncFile = tempEncPath.toFile(); FileOutputStream encryptedSignedOutputStream = new FileOutputStream(tmpEncFile); LOGGER.debug(debugPrefix + "Created temp encrypted output file " + tmpEncFile.getAbsolutePath()); OutputStream encryptOutStream = encGen.open(encryptedSignedOutputStream, new byte[BUFFER_SIZE]); // //////////////////////////// // setup data compression PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP); OutputStream compressOutStream = comData.open(encryptOutStream); // ///////////////////// // sign encrypted file with test reg private key // create a signature generator PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(testRegSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1) .setProvider("BC")); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, testRegPrivateKey); @SuppressWarnings("unchecked") Iterator<String> it = testRegSecretKey.getPublicKey().getUserIDs(); if (it.hasNext()) { PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, it.next()); signatureGenerator.setHashedSubpackets(spGen.generate()); } // setup signature generator to encode the contents of the compressed output stream signatureGenerator.generateOnePassVersion(false).encode(compressOutStream); // create a PGP Literal Data Generator and open it to wrap the compression output stream PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); OutputStream signedOutStream = lGen.open(compressOutStream, PGPLiteralData.BINARY, "", new java.util.Date(), new byte[BUFFER_SIZE]); // create an input stream out of the input bytes FileInputStream clearInputStream = new FileInputStream(input); // read the input and write all data to the signing output stream, also update the signature // generator with the same input data byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = clearInputStream.read(buf)) > 0) { signedOutStream.write(buf, 0, len); signatureGenerator.update(buf, 0, len); } // close everything and generate the final signature signedOutStream.close(); lGen.close(); signatureGenerator.generate().encode(compressOutStream); compressOutStream.close(); comData.close(); encryptOutStream.close(); encGen.close(); clearInputStream.close(); encryptedSignedOutputStream.close(); } catch (IOException | PGPException | SignatureException e) { throw new GPGEncryptionException(debugPrefix + "Failure to encrypt and sign input", e); } LOGGER.debug(debugPrefix + "Generated encrypted data in " + (System.currentTimeMillis() - curTime)); return MessageBuilder.withPayload(tmpEncFile).setHeader("dwBatchUuid", dwBatchUuid) .setHeader("fileSuffix", fileSuffix).setHeader("recordsSent", recordsSent) .setHeader("tempPaths", tempPaths).setHeader("dwConfigType", dwConfigType).build(); }
From source file:org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.java
License:Open Source License
public PGPSignatureGenerator getDataSignatureGenerator(int hashAlgo, boolean cleartext, Map<ByteBuffer, byte[]> signedHashes, Date creationTimestamp) throws PgpGeneralException { if (mPrivateKeyState == PRIVATE_KEY_STATE_LOCKED) { throw new PrivateKeyNotUnlockedException(); }/*from w ww .ja va 2 s . com*/ // We explicitly create a signature creation timestamp in this place. // That way, we can inject an artificial one from outside, ie the one // used in previous runs of this function. if (creationTimestamp == null) { // to sign using nfc PgpSignEncrypt is executed two times. // the first time it stops to return the PendingIntent for nfc connection and signing the hash // the second time the signed hash is used. // to get the same hash we cache the timestamp for the second round! creationTimestamp = new Date(); } PGPContentSignerBuilder contentSignerBuilder = getContentSignerBuilder(hashAlgo, signedHashes); int signatureType; if (cleartext) { // for sign-only ascii text (cleartext signature) signatureType = PGPSignature.CANONICAL_TEXT_DOCUMENT; } else { signatureType = PGPSignature.BINARY_DOCUMENT; } try { PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder); signatureGenerator.init(signatureType, mPrivateKey); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, mRing.getPrimaryUserIdWithFallback()); spGen.setSignatureCreationTime(false, creationTimestamp); signatureGenerator.setHashedSubpackets(spGen.generate()); return signatureGenerator; } catch (PgpKeyNotFoundException | PGPException e) { // TODO: simply throw PGPException! throw new PgpGeneralException("Error initializing signature!", e); } }
From source file:org.sufficientlysecure.keychain.pgp.PgpCertifyOperation.java
License:Open Source License
public PgpCertifyResult certify(CanonicalizedSecretKey secretKey, CanonicalizedPublicKeyRing publicRing, OperationLog log, int indent, CertifyAction action, Map<ByteBuffer, byte[]> signedHashes, Date creationTimestamp) { if (!secretKey.isMasterKey()) { throw new AssertionError("tried to certify with non-master key, this is a programming error!"); }/*from w w w . j a va 2 s . c o m*/ if (publicRing.getMasterKeyId() == secretKey.getKeyId()) { throw new AssertionError("key tried to self-certify, this is a programming error!"); } // create a signatureGenerator from the supplied masterKeyId and passphrase PGPSignatureGenerator signatureGenerator = secretKey.getCertSignatureGenerator(signedHashes); { // supply signatureGenerator with a SubpacketVector PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); if (creationTimestamp != null) { spGen.setSignatureCreationTime(false, creationTimestamp); Log.d(Constants.TAG, "For NFC: set sig creation time to " + creationTimestamp); } PGPSignatureSubpacketVector packetVector = spGen.generate(); signatureGenerator.setHashedSubpackets(packetVector); } // get the master subkey (which we certify for) PGPPublicKey publicKey = publicRing.getPublicKey().getPublicKey(); SecurityTokenSignOperationsBuilder requiredInput = new SecurityTokenSignOperationsBuilder(creationTimestamp, publicKey.getKeyID(), publicKey.getKeyID()); try { if (action.mUserIds != null) { log.add(LogType.MSG_CRT_CERTIFY_UIDS, 2, action.mUserIds.size(), KeyFormattingUtils.convertKeyIdToHex(action.mMasterKeyId)); // fetch public key ring, add the certification and return it for (String userId : action.mUserIds) { try { PGPSignature sig = signatureGenerator.generateCertification(userId, publicKey); publicKey = PGPPublicKey.addCertification(publicKey, userId, sig); } catch (NfcInteractionNeeded e) { requiredInput.addHash(e.hashToSign, e.hashAlgo); } } } if (action.mUserAttributes != null) { log.add(LogType.MSG_CRT_CERTIFY_UATS, 2, action.mUserAttributes.size(), KeyFormattingUtils.convertKeyIdToHex(action.mMasterKeyId)); // fetch public key ring, add the certification and return it for (WrappedUserAttribute userAttribute : action.mUserAttributes) { PGPUserAttributeSubpacketVector vector = userAttribute.getVector(); try { PGPSignature sig = signatureGenerator.generateCertification(vector, publicKey); publicKey = PGPPublicKey.addCertification(publicKey, vector, sig); } catch (NfcInteractionNeeded e) { requiredInput.addHash(e.hashToSign, e.hashAlgo); } } } } catch (PGPException e) { Log.e(Constants.TAG, "signing error", e); return new PgpCertifyResult(); } if (!requiredInput.isEmpty()) { return new PgpCertifyResult(requiredInput.build()); } PGPPublicKeyRing ring = PGPPublicKeyRing.insertPublicKey(publicRing.getRing(), publicKey); return new PgpCertifyResult(new UncachedKeyRing(ring)); }
From source file:org.sufficientlysecure.keychain.pgp.PgpKeyOperation.java
License:Open Source License
private static PGPSignature generateUserIdSignature(PGPSignatureGenerator sGen, Date creationTime, PGPPrivateKey masterPrivateKey, PGPPublicKey pKey, String userId, boolean primary, int flags, long expiry) throws IOException, PGPException, SignatureException { PGPSignatureSubpacketGenerator hashedPacketsGen = generateHashedSelfSigSubpackets(creationTime, pKey, primary, flags, expiry);/* w w w .j a v a 2 s .c o m*/ sGen.setHashedSubpackets(hashedPacketsGen.generate()); sGen.init(PGPSignature.POSITIVE_CERTIFICATION, masterPrivateKey); return sGen.generateCertification(userId, pKey); }
From source file:org.sufficientlysecure.keychain.pgp.PgpKeyOperation.java
License:Open Source License
private static PGPSignature generateUserAttributeSignature(PGPSignatureGenerator sGen, Date creationTime, PGPPrivateKey masterPrivateKey, PGPPublicKey pKey, PGPUserAttributeSubpacketVector vector, int flags, long expiry) throws IOException, PGPException, SignatureException { PGPSignatureSubpacketGenerator hashedPacketsGen = generateHashedSelfSigSubpackets(creationTime, pKey, false, flags, expiry);/*from w ww . ja v a 2 s.c o m*/ sGen.setHashedSubpackets(hashedPacketsGen.generate()); sGen.init(PGPSignature.POSITIVE_CERTIFICATION, masterPrivateKey); return sGen.generateCertification(vector, pKey); }