/** * 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; }
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; }
public SecretKey generateKeyPair(final String id, final char[] pass) throws CryptoException { try { // This object generates individual key-pairs. final RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 2048, 12)); // First create the master (signing) key with the generator. final PGPKeyPair keyPair = new BcPGPKeyPair(PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date()); // Add a self-signature on the id final PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator(); signhashgen.setKeyFlags(true, KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA | KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); signhashgen.setPreferredCompressionAlgorithms(false, new int[] { CompressionAlgorithmTags.ZIP }); signhashgen.setPreferredHashAlgorithms(false, new int[] { HashAlgorithmTags.SHA1 }); signhashgen.setPreferredSymmetricAlgorithms(false, new int[] { SymmetricKeyAlgorithmTags.AES_256 }); signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION); // Create a signature on the encryption subkey. final PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator(); enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); // Objects used to encrypt the secret key. // Finally, create the keyring itself. The constructor // takes parameters that allow it to generate the self // signature. final PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); final PBESecretKeyEncryptor secretKeyEncryptor = new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_128, sha1Calc).build(pass); final BcPGPContentSignerBuilder contentSigner = new BcPGPContentSignerBuilder(keyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1); final PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, keyPair, id, sha1Calc, signhashgen.generate(), null, contentSigner, secretKeyEncryptor); // return new SimpleKeyPair(new BcPGPPublicKey(publicKeyRing.getPublicKey()), return new BcPGPSecretKey(keyRingGen.generateSecretKeyRing().getSecretKey()); } catch (final Exception e) { throw new CryptoException(e); } }
private PGPSignatureSubpacketVector generateMasterKeySettings() { final PGPSignatureSubpacketGenerator settings = new PGPSignatureSubpacketGenerator(); settings.setKeyFlags(false, Flags.toBitmask(KeyFlag.MASTER_KEY_DEFAULTS)); settings.setPreferredSymmetricAlgorithms(false, Flags.toIntArray(SymmetricAlgorithm.ACCEPTABLE_ALGORITHMS)); settings.setPreferredHashAlgorithms(false, Flags.toIntArray(HashAlgorithm.ACCEPTABLE_ALGORITHMS)); settings.setPreferredCompressionAlgorithms(false, Flags.toIntArray(CompressionAlgorithm.ACCEPTABLE_ALGORITHMS)); return settings.generate(); }
public final static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass, int s2kcount, KeyGenPane.BackgroundTask bgt) throws Exception { // This object generates individual key-pairs. RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); // Boilerplate RSA parameters, no need to change anything // except for the RSA key-size (2048). You can use whatever key-size // makes sense for you -- 4096, etc. kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 2048, 12)); bgt.setProgressPub(10); // First create the master (signing) key with the generator. PGPKeyPair rsakp_sign = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, kpg.generateKeyPair(), new Date()); // Then an encryption subkey. PGPKeyPair rsakp_enc = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, kpg.generateKeyPair(), new Date()); bgt.setProgressPub(50); // Add a self-signature on the id PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator(); bgt.setProgressPub(55); // Add signed metadata on the signature. // 1) Declare its purpose signhashgen.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER); bgt.setProgressPub(60); // 2) Set preferences for secondary crypto algorithms to use when // sending messages to this key. signhashgen.setPreferredSymmetricAlgorithms(false, new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 }); signhashgen.setPreferredHashAlgorithms(false, new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224, }); // 3) Request senders add additional checksums to the message (useful // when verifying unsigned messages.) signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION); // Create a signature on the encryption subkey. PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator(); // Add metadata to declare its purpose enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); // Objects used to encrypt the secret key. PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); PGPDigestCalculator sha256Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA256); bgt.setProgressPub(70); // bcpg 1.48 exposes this API that includes s2kcount. Earlier versions // use a default of 0x60. PBESecretKeyEncryptor pske = (new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha256Calc, s2kcount)).build(pass); // Finally, create the keyring itself. The constructor takes parameters // that allow it to generate the self signature. PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign, id, sha1Calc, signhashgen.generate(), null, new BcPGPContentSignerBuilder(rsakp_sign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1), pske); bgt.setProgressPub(80); // Add our encryption subkey, together with its signature. keyRingGen.addSubKey(rsakp_enc, enchashgen.generate(), null); bgt.setProgressPub(90); return keyRingGen; }
static PGPKeyRingGenerator generateKeyRingGenerator(String userId, int numBits, char[] passphrase) throws Exception { RSAKeyPairGenerator keyPairGenerator = new RSAKeyPairGenerator(); keyPairGenerator.init( new RSAKeyGenerationParameters( BigInteger.valueOf(0x10001), new SecureRandom(), numBits, 12 ) ); PGPKeyPair rsaKeyPairSign = new BcPGPKeyPair( PGPPublicKey.RSA_SIGN, keyPairGenerator.generateKeyPair(), new Date() ); PGPKeyPair rsaKeyPairEncrypt = new BcPGPKeyPair( PGPPublicKey.RSA_ENCRYPT, keyPairGenerator.generateKeyPair(), new Date() ); PGPSignatureSubpacketGenerator signHashGenerator = new PGPSignatureSubpacketGenerator(); signHashGenerator.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER); signHashGenerator.setPreferredSymmetricAlgorithms( false, new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 } ); signHashGenerator.setPreferredHashAlgorithms( false, new int[] { HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, // Not recommended HashAlgorithmTags.SHA224, // Not recommended } ); signHashGenerator.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION); PGPSignatureSubpacketGenerator encryptHashGenerator = new PGPSignatureSubpacketGenerator(); encryptHashGenerator.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); PGPDigestCalculator sha1DigestCalculator = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); PGPDigestCalculator sha512DigestCalculator = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA512); PBESecretKeyEncryptor secretKeyEncryptor = ( new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha512DigestCalculator) ) .build(passphrase); PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator( PGPSignature.NO_CERTIFICATION, rsaKeyPairSign, userId, sha1DigestCalculator, signHashGenerator.generate(), null, new BcPGPContentSignerBuilder(rsaKeyPairSign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA512), secretKeyEncryptor ); keyRingGen.addSubKey(rsaKeyPairEncrypt, encryptHashGenerator.generate(), null); return keyRingGen; }
/** * 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 ); } }
private static PGPKeyRingGenerator generateKeyRingGenerator( String id, char[] pass, int s2kcount, int keySize, KeyPair keyPair ) throws PGPException { // This object generates individual key-pairs. RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); // Boilerplate RSA parameters, no need to change anything // except for the RSA key-size (2048). You can use whatever // key-size makes sense for you -- 4096, etc. kpg.init( new RSAKeyGenerationParameters( BigInteger.valueOf( 0x10001 ), new SecureRandom(), keySize, 12 ) ); // First create the master (signing) key with the generator. PGPKeyPair rsakp_sign = new BcPGPKeyPair( PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date() ); // Then an encryption subkey. PGPKeyPair rsakp_enc = new BcPGPKeyPair( PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date() ); keyPair.setPrimaryKeyId( Long.toHexString( rsakp_sign.getKeyID() ) ); keyPair.setPrimaryKeyFingerprint( BytesToHex( rsakp_sign.getPublicKey().getFingerprint() ) ); keyPair.setSubKeyId( Long.toHexString( rsakp_enc.getKeyID() ) ); keyPair.setSubKeyFingerprint( BytesToHex( rsakp_enc.getPublicKey().getFingerprint() ) ); // Add a self-signature on the id PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator(); // Add signed metadata on the signature. // 1) Declare its purpose signhashgen.setKeyFlags( false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER ); // 2) Set preferences for secondary crypto algorithms to use // when sending messages to this key. signhashgen.setPreferredSymmetricAlgorithms( false, new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128, SymmetricKeyAlgorithmTags.CAST5, SymmetricKeyAlgorithmTags.TRIPLE_DES } ); signhashgen.setPreferredHashAlgorithms( false, new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224, } ); signhashgen.setPreferredCompressionAlgorithms( false, new int[] { CompressionAlgorithmTags.ZLIB, CompressionAlgorithmTags.BZIP2, CompressionAlgorithmTags.ZIP } ); // 3) Request senders add additional checksums to the // message (useful when verifying unsigned messages.) signhashgen.setFeature( false, Features.FEATURE_MODIFICATION_DETECTION ); // Create a signature on the encryption subkey. PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator(); // Add metadata to declare its purpose enchashgen.setKeyFlags( false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE ); // Objects used to encrypt the secret key. PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get( HashAlgorithmTags.SHA1 ); // bcpg 1.48 exposes this API that includes s2kcount. Earlier // versions use a default of 0x60. PBESecretKeyEncryptor pske = ( new BcPBESecretKeyEncryptorBuilder( PGPEncryptedData.CAST5, sha1Calc, s2kcount ) ).build( pass ); // Finally, create the keyring itself. The constructor // takes parameters that allow it to generate the self // signature. PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator( PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign, id, sha1Calc, signhashgen.generate(), null, new BcPGPContentSignerBuilder( rsakp_sign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1 ), pske ); // Add our encryption subkey, together with its signature. keyRingGen.addSubKey( rsakp_enc, enchashgen.generate(), null ); return keyRingGen; }
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[] 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(); }
private PushCertificate newSignedCert(String nonce, TestKey signingKey, Date now) 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)); if (now != null) { PGPSignatureSubpacketGenerator subGen = new PGPSignatureSubpacketGenerator(); subGen.setSignatureCreationTime(false, now); gen.setHashedSubpackets(subGen.generate()); } gen.init(PGPSignature.BINARY_DOCUMENT, signingKey.getPrivateKey()); gen.update(payload.getBytes(UTF_8)); PGPSignature sig = gen.generate(); 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(repo, signedPushConfig); return parser.parse(reader); }
public void run(final char[] passphrase, final InputStream inputStream, final OutputStream outputStream) throws IOException, CryptoException { try { final OutputStream armor = new ArmoredOutputStream(outputStream); final PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder( SymmetricKeyAlgorithmTags.AES_128).setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(new BouncyCastleProvider())); encryptedDataGenerator.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setSecureRandom(new SecureRandom()).setProvider( new BouncyCastleProvider())); final OutputStream encryptedOut = encryptedDataGenerator.open(armor, 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(new BouncyCastleProvider()) .build(passphrase)); final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(secretKey.getPublicKey() .getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(new BouncyCastleProvider())); 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, "", new Date(), new byte[4096]); final byte[] buf = new byte[4096]; for (int len = 0; (len = inputStream.read(buf)) > 0;) { literalOut.write(buf, 0, len); signatureGenerator.update(buf, 0, len); } literalDataGenerator.close(); signatureGenerator.generate().encode(compressedOut); compressedDataGenerator.close(); encryptedDataGenerator.close(); armor.close(); } catch (final Exception e) { throw new CryptoException(e); } }
private void generateTest( String message, String type) throws Exception { PGPSecretKey pgpSecKey = readSecretKey(new ByteArrayInputStream(secretKey)); PGPPrivateKey pgpPrivKey = pgpSecKey.extractPrivateKey("".toCharArray(), "BC"); PGPSignatureGenerator sGen = new PGPSignatureGenerator(pgpSecKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256, "BC"); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); sGen.initSign(PGPSignature.CANONICAL_TEXT_DOCUMENT, pgpPrivKey); Iterator it = pgpSecKey.getPublicKey().getUserIDs(); if (it.hasNext()) { spGen.setSignerUserID(false, (String)it.next()); sGen.setHashedSubpackets(spGen.generate()); } ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); ByteArrayInputStream bIn = new ByteArrayInputStream(message.getBytes()); aOut.beginClearText(PGPUtil.SHA256); // // note the last \n in the file is ignored // ByteArrayOutputStream lineOut = new ByteArrayOutputStream(); int lookAhead = readInputLine(lineOut, bIn); processLine(aOut, sGen, lineOut.toByteArray()); if (lookAhead != -1) { do { lookAhead = readInputLine(lineOut, lookAhead, bIn); sGen.update((byte)'\r'); sGen.update((byte)'\n'); processLine(aOut, sGen, lineOut.toByteArray()); } while (lookAhead != -1); } aOut.endClearText(); BCPGOutputStream bcpgOut = new BCPGOutputStream(aOut); sGen.generate().encode(bcpgOut); aOut.close(); messageTest(new String(bOut.toByteArray()), type); }
/** * Encrypt, sign and write input stream data to output stream. * Input and output stream are closed. */ private static void encryptAndSign( InputStream plainInput, OutputStream encryptedOutput, PersonalKey myKey, List<PGPUtils.PGPCoderKey> receiverKeys) throws IOException, PGPException { // setup data encryptor & generator BcPGPDataEncryptorBuilder encryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_192); encryptor.setWithIntegrityPacket(true); encryptor.setSecureRandom(new SecureRandom()); // add public key recipients PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptor); receiverKeys.forEach(key -> encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key.encryptKey))); OutputStream encryptedOut = encGen.open(encryptedOutput, new byte[BUFFER_SIZE]); // setup compressed data generator PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); OutputStream compressedOut = compGen.open(encryptedOut, new byte[BUFFER_SIZE]); // setup signature generator int algo = myKey.getSigningAlgorithm(); PGPSignatureGenerator sigGen = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA256)); sigGen.init(PGPSignature.BINARY_DOCUMENT, myKey.getPrivateSigningKey()); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, myKey.getUserId()); sigGen.setUnhashedSubpackets(spGen.generate()); sigGen.generateOnePassVersion(false).encode(compressedOut); // Initialize literal data generator PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator(); OutputStream literalOut = literalGen.open( compressedOut, PGPLiteralData.BINARY, "", new Date(), new byte[BUFFER_SIZE]); // read the "in" stream, compress, encrypt and write to the "out" stream // this must be done if clear data is bigger than the buffer size // but there are other ways to optimize... byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = plainInput.read(buf)) > 0) { literalOut.write(buf, 0, len); sigGen.update(buf, 0, len); } literalGen.close(); // generate the signature, compress, encrypt and write to the "out" stream sigGen.generate().encode(compressedOut); compGen.close(); encGen.close(); }
/** * 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 PGPObjectFactory(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"); } }
private PGPSignatureSubpacketVector generateSubKeySettings() { final PGPSignatureSubpacketGenerator settings = new PGPSignatureSubpacketGenerator(); settings.setKeyFlags(false, Flags.toBitmask(KeyFlag.SUB_KEY_DEFAULTS)); return settings.generate(); }
/** * Add user ID to signature file. * * <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()); } }
/** * Add user ID to signature file. * * <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()); } }