List of usage examples for org.bouncycastle.openpgp PGPSignatureGenerator setUnhashedSubpackets
public void setUnhashedSubpackets(PGPSignatureSubpacketVector unhashedPcks)
From source file:org.kontalk.crypto.Coder.java
License:Open Source License
/** * Creates encrypted and signed message body. * Errors that may occur are saved to the message. * @param message/*from w w w .ja v a2 s .c o m*/ * @return the encrypted and signed text. */ public static Optional<byte[]> processOutMessage(OutMessage message) { if (message.getCoderStatus().getEncryption() != Encryption.DECRYPTED) { LOGGER.warning("message does not want to be encrypted"); return Optional.empty(); } LOGGER.info("encrypting message..."); // get keys KeysResult keys = getKeys(message.getUser()); if (keys.myKey == null || keys.otherKey == null) { message.setSecurityErrors(keys.errors); return Optional.empty(); } // secure the message against the most basic attacks using Message/CPIM String from = keys.myKey.getUserId(); String to = keys.otherKey.userID + "; "; String mime = "text/plain"; // TODO encrypt more possible content String text = message.getContent().getPlainText(); CPIMMessage cpim = new CPIMMessage(from, to, new Date(), mime, text); byte[] plainText; try { plainText = cpim.toByteArray(); } catch (UnsupportedEncodingException ex) { LOGGER.log(Level.WARNING, "UTF-8 not supported", ex); plainText = cpim.toString().getBytes(); } // 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); //for (PGPPublicKey rcpt : mRecipients) encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(keys.otherKey.encryptKey)); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(plainText); try { // catch all io and pgp exceptions OutputStream encryptedOut = encGen.open(out, 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 = keys.myKey.getPublicEncryptionKey().getAlgorithm(); PGPSignatureGenerator sigGen = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA1)); sigGen.init(PGPSignature.BINARY_DOCUMENT, keys.myKey.getPrivateEncryptionKey()); PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, keys.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 = in.read(buf)) > 0) { literalOut.write(buf, 0, len); try { sigGen.update(buf, 0, len); } catch (SignatureException ex) { LOGGER.log(Level.WARNING, "can't read data for signature", ex); message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA)); return Optional.empty(); } } in.close(); literalGen.close(); // generate the signature, compress, encrypt and write to the "out" stream try { sigGen.generate().encode(compressedOut); } catch (SignatureException ex) { LOGGER.log(Level.WARNING, "can't create signature", ex); message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA)); return Optional.empty(); } compGen.close(); encGen.close(); } catch (IOException | PGPException ex) { LOGGER.log(Level.WARNING, "can't encrypt message", ex); message.setSecurityErrors(EnumSet.of(Error.UNKNOWN_ERROR)); return Optional.empty(); } LOGGER.info("encryption successful"); return Optional.of(out.toByteArray()); }
From source file:org.sufficientlysecure.keychain.pgp.PgpKeyOperation.java
License:Open Source License
static PGPSignature generateSubkeyBindingSignature(PGPSignatureGenerator sGen, Date creationTime, PGPPublicKey masterPublicKey, PGPPrivateKey masterPrivateKey, PGPSignatureGenerator subSigGen, PGPPrivateKey subPrivateKey, PGPPublicKey pKey, int flags, long expiry) throws IOException, PGPException, SignatureException { PGPSignatureSubpacketGenerator unhashedPacketsGen = new PGPSignatureSubpacketGenerator(); // If this key can sign, we need a primary key binding signature if ((flags & KeyFlags.SIGN_DATA) > 0) { // cross-certify signing keys PGPSignatureSubpacketGenerator subHashedPacketsGen = new PGPSignatureSubpacketGenerator(); subHashedPacketsGen.setSignatureCreationTime(false, creationTime); subSigGen.init(PGPSignature.PRIMARYKEY_BINDING, subPrivateKey); subSigGen.setHashedSubpackets(subHashedPacketsGen.generate()); PGPSignature certification = subSigGen.generateCertification(masterPublicKey, pKey); unhashedPacketsGen.setEmbeddedSignature(true, certification); }//from ww w .ja va2s . c o m PGPSignatureSubpacketGenerator hashedPacketsGen; { hashedPacketsGen = new PGPSignatureSubpacketGenerator(); hashedPacketsGen.setSignatureCreationTime(true, creationTime); hashedPacketsGen.setKeyFlags(true, flags); if (expiry > 0) { hashedPacketsGen.setKeyExpirationTime(true, expiry - pKey.getCreationTime().getTime() / 1000); } } sGen.init(PGPSignature.SUBKEY_BINDING, masterPrivateKey); sGen.setHashedSubpackets(hashedPacketsGen.generate()); sGen.setUnhashedSubpackets(unhashedPacketsGen.generate()); return sGen.generateCertification(masterPublicKey, pKey); }
From source file:org.sufficientlysecure.keychain.pgp.UncachedKeyringCanonicalizeTest.java
License:Open Source License
private static PGPSignature forgeSignature(PGPSecretKey key, int type, PGPSignatureSubpacketGenerator hashedSubs, PGPSignatureSubpacketGenerator unhashedSubs, PGPPublicKey publicKey, PGPPublicKey signedKey) throws Exception { PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder() .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray()); PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor); PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder(publicKey.getAlgorithm(), PGPUtil.SHA1).setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder); sGen.setHashedSubpackets(hashedSubs.generate()); sGen.setUnhashedSubpackets(unhashedSubs.generate()); sGen.init(type, privateKey);//from ww w .ja v a2 s . c o m return sGen.generateCertification(publicKey, signedKey); }