use of org.bouncycastle.openpgp.PGPPublicKey in project camel by apache.
the class PGPKeyAccessDataFormat method getSignature.
protected PGPOnePassSignature getSignature(Exchange exchange, PGPOnePassSignatureList signatureList) throws Exception {
if (SIGNATURE_VERIFICATION_OPTION_IGNORE.equals(getSignatureVerificationOption())) {
return null;
}
if (SIGNATURE_VERIFICATION_OPTION_NO_SIGNATURE_ALLOWED.equals(getSignatureVerificationOption())) {
throw new PGPException("PGP message contains a signature although a signature is not expected. Either change the configuration of the PGP decryptor or send a PGP message with no signature.");
}
List<String> allowedUserIds = determineSignaturenUserIds(exchange);
for (int i = 0; i < signatureList.size(); i++) {
PGPOnePassSignature signature = signatureList.get(i);
// Determine public key from signature keyId
PGPPublicKey sigPublicKey = publicKeyAccessor.getPublicKey(exchange, signature.getKeyID(), allowedUserIds);
if (sigPublicKey == null) {
continue;
}
// choose that signature for which a public key exists!
signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider(getProvider()), sigPublicKey);
return signature;
}
if (signatureList.isEmpty()) {
return null;
} else {
throw new IllegalArgumentException("Cannot verify the PGP signature: No public key found for the key ID(s) contained in the PGP signature(s). " + "Either the received PGP message contains a signature from an unexpected sender or the Public Keyring does not contain the public key of the sender.");
}
}
use of org.bouncycastle.openpgp.PGPPublicKey in project camel by apache.
the class PGPKeyAccessDataFormat method marshal.
public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
//NOPMD
List<String> userids = determineEncryptionUserIds(exchange);
List<PGPPublicKey> keys = publicKeyAccessor.getEncryptionKeys(exchange, userids);
if (keys.isEmpty()) {
throw new IllegalArgumentException("Cannot PGP encrypt message. No public encryption key found for the User Ids " + userids + " in the public keyring. Either specify other User IDs or add correct public keys to the keyring.");
}
exchange.getOut().setHeader(NUMBER_OF_ENCRYPTION_KEYS, Integer.valueOf(keys.size()));
InputStream input = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
if (armored) {
outputStream = new ArmoredOutputStream(outputStream);
}
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(findAlgorithm(exchange)).setWithIntegrityPacket(integrity).setSecureRandom(new SecureRandom()).setProvider(getProvider()));
// several keys can be added
for (PGPPublicKey key : keys) {
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key));
}
OutputStream encOut = encGen.open(outputStream, new byte[BUFFER_SIZE]);
OutputStream comOut;
if (withCompressedDataPacket) {
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange));
comOut = new BufferedOutputStream(comData.open(encOut));
} else {
comOut = encOut;
LOG.debug("No Compressed Data packet is added");
}
List<PGPSignatureGenerator> sigGens = createSignatureGenerator(exchange, comOut);
PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
String fileName = findFileName(exchange);
OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, fileName, new Date(), new byte[BUFFER_SIZE]);
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
litOut.write(buffer, 0, bytesRead);
if (sigGens != null && !sigGens.isEmpty()) {
for (PGPSignatureGenerator sigGen : sigGens) {
// not nested therefore it is the same for all
// can this be improved that we only do it for one sigGen and set the result on the others?
sigGen.update(buffer, 0, bytesRead);
}
}
litOut.flush();
}
} finally {
IOHelper.close(litOut);
if (sigGens != null && !sigGens.isEmpty()) {
// reverse order
for (int i = sigGens.size() - 1; i > -1; i--) {
PGPSignatureGenerator sigGen = sigGens.get(i);
sigGen.generate().encode(comOut);
}
}
IOHelper.close(comOut, encOut, outputStream, input);
}
}
use of org.bouncycastle.openpgp.PGPPublicKey in project camel by apache.
the class PGPDataFormatUtil method findPublicKeys.
public static List<PGPPublicKey> findPublicKeys(List<String> useridParts, boolean forEncryption, PGPPublicKeyRingCollection pgpPublicKeyringCollection) {
List<PGPPublicKey> result = new ArrayList<PGPPublicKey>(useridParts.size());
for (Iterator<PGPPublicKeyRing> keyRingIter = pgpPublicKeyringCollection.getKeyRings(); keyRingIter.hasNext(); ) {
PGPPublicKeyRing keyRing = keyRingIter.next();
PGPPublicKey primaryKey = keyRing.getPublicKey();
String[] foundKeyUserIdForUserIdPart = findFirstKeyUserIdContainingOneOfTheParts(useridParts, primaryKey);
if (foundKeyUserIdForUserIdPart == null) {
LOG.debug("No User ID found in primary key with key ID {} containing one of the parts {}", primaryKey.getKeyID(), useridParts);
continue;
}
LOG.debug("User ID {} found in primary key with key ID {} containing one of the parts {}", new Object[] { foundKeyUserIdForUserIdPart[0], primaryKey.getKeyID(), useridParts });
// add adequate keys to the result
for (Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); keyIter.hasNext(); ) {
PGPPublicKey key = keyIter.next();
if (forEncryption) {
if (isEncryptionKey(key)) {
LOG.debug("Public encryption key with key user ID {} and key ID {} added to the encryption keys", foundKeyUserIdForUserIdPart[0], Long.toString(key.getKeyID()));
result.add(key);
}
} else if (!forEncryption && isSignatureKey(key)) {
// not used!
result.add(key);
LOG.debug("Public key with key user ID {} and key ID {} added to the signing keys", foundKeyUserIdForUserIdPart[0], Long.toString(key.getKeyID()));
}
}
}
return result;
}
use of org.bouncycastle.openpgp.PGPPublicKey in project keywhiz by square.
the class ExpirationExtractor method expirationFromOpenPGP.
@Nullable
public static Instant expirationFromOpenPGP(byte[] content) {
JcaPGPPublicKeyRingCollection collection;
try {
collection = new JcaPGPPublicKeyRingCollection(new ByteArrayInputStream(content));
} catch (IOException | PGPException e) {
// Unable to parse
logger.info("Failed to parse OpenPGP keyring", e);
return null;
}
Instant earliest = null;
// Iterate over all key rings in file
Iterator rings = collection.getKeyRings();
while (rings.hasNext()) {
Object ringItem = rings.next();
if (ringItem instanceof PGPPublicKeyRing) {
PGPPublicKeyRing ring = (PGPPublicKeyRing) ringItem;
// Iterate over all keys in ring
Iterator keys = ring.getPublicKeys();
while (keys.hasNext()) {
Object keyItem = keys.next();
if (keyItem instanceof PGPPublicKey) {
PGPPublicKey key = (PGPPublicKey) keyItem;
// Get validity for key (zero means no expiry)
long validSeconds = key.getValidSeconds();
if (validSeconds > 0) {
Instant expiry = key.getCreationTime().toInstant().plusSeconds(validSeconds);
if (earliest == null || expiry.isBefore(earliest)) {
earliest = expiry;
}
}
}
}
}
}
return earliest;
}
use of org.bouncycastle.openpgp.PGPPublicKey in project gerrit by GerritCodeReview.
the class GpgKeys method parse.
@Override
public GpgKey parse(AccountResource parent, IdString id) throws ResourceNotFoundException, PGPException, OrmException, IOException {
checkVisible(self, parent);
String str = CharMatcher.whitespace().removeFrom(id.get()).toUpperCase();
if ((str.length() != 8 && str.length() != 40) || !CharMatcher.anyOf("0123456789ABCDEF").matchesAllOf(str)) {
throw new ResourceNotFoundException(id);
}
byte[] fp = parseFingerprint(id.get(), getGpgExtIds(parent));
try (PublicKeyStore store = storeProvider.get()) {
long keyId = keyId(fp);
for (PGPPublicKeyRing keyRing : store.get(keyId)) {
PGPPublicKey key = keyRing.getPublicKey();
if (Arrays.equals(key.getFingerprint(), fp)) {
return new GpgKey(parent.getUser(), keyRing);
}
}
}
throw new ResourceNotFoundException(id);
}
Aggregations