001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org> 002// 003// SPDX-License-Identifier: Apache-2.0 004 005package org.pgpainless.sop; 006 007import java.io.IOException; 008import java.io.InputStream; 009import java.io.OutputStream; 010 011import org.bouncycastle.openpgp.PGPException; 012import org.bouncycastle.openpgp.PGPPublicKeyRing; 013import org.bouncycastle.openpgp.PGPSecretKeyRing; 014import org.pgpainless.PGPainless; 015import org.pgpainless.key.util.KeyRingUtils; 016import org.pgpainless.util.ArmorUtils; 017import sop.operation.ExtractCert; 018import sop.Ready; 019import sop.exception.SOPGPException; 020 021public class ExtractCertImpl implements ExtractCert { 022 023 private boolean armor = true; 024 025 @Override 026 public ExtractCert noArmor() { 027 armor = false; 028 return this; 029 } 030 031 @Override 032 public Ready key(InputStream keyInputStream) throws IOException, SOPGPException.BadData { 033 PGPSecretKeyRing key = PGPainless.readKeyRing().secretKeyRing(keyInputStream); 034 if (key == null) { 035 throw new SOPGPException.BadData(new PGPException("No key data found.")); 036 } 037 038 PGPPublicKeyRing cert = KeyRingUtils.publicKeyRingFrom(key); 039 040 return new Ready() { 041 @Override 042 public void writeTo(OutputStream outputStream) throws IOException { 043 OutputStream out = armor ? ArmorUtils.createArmoredOutputStreamFor(cert, outputStream) : outputStream; 044 cert.encode(out); 045 046 if (armor) { 047 out.close(); 048 } 049 } 050 }; 051 } 052}