pgpainless/pgpainless-sop/src/main/java/org/pgpainless/sop/commands/Armor.java

76 lines
2.5 KiB
Java
Raw Normal View History

2020-12-16 20:09:01 +01:00
/*
* Copyright 2020 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pgpainless.sop.commands;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.util.io.Streams;
import org.pgpainless.util.ArmoredOutputStreamFactory;
2020-12-16 20:09:01 +01:00
import picocli.CommandLine;
import java.io.IOException;
import java.io.PushbackInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.pgpainless.sop.Print.err_ln;
2020-12-22 23:07:53 +01:00
@CommandLine.Command(name = "armor",
description = "Add ASCII Armor to standard input",
exitCodeOnInvalidInput = 37)
2020-12-16 20:09:01 +01:00
public class Armor implements Runnable {
private static final byte[] BEGIN_ARMOR = "-----BEGIN PGP".getBytes(StandardCharsets.UTF_8);
private enum Label {
auto,
sig,
key,
cert,
message
}
@CommandLine.Option(names = {"--label"}, description = "Label to be used in the header and tail of the armoring.", paramLabel = "{auto|sig|key|cert|message}")
Label label;
@CommandLine.Option(names = {"--allow-nested"}, description = "Allow additional armoring of already armored input")
boolean allowNested = false;
@Override
public void run() {
2021-07-01 18:44:57 +02:00
try (PushbackInputStream pbIn = new PushbackInputStream(System.in, BEGIN_ARMOR.length);
2021-05-25 18:08:04 +02:00
ArmoredOutputStream armoredOutputStream = ArmoredOutputStreamFactory.get(System.out)) {
2021-07-01 18:44:57 +02:00
// take a peek
byte[] firstBytes = new byte[BEGIN_ARMOR.length];
int readByteCount = pbIn.read(firstBytes);
if (readByteCount != -1) {
pbIn.unread(firstBytes, 0, readByteCount);
}
if (Arrays.equals(BEGIN_ARMOR, firstBytes) && !allowNested) {
2020-12-16 20:09:01 +01:00
Streams.pipeAll(pbIn, System.out);
} else {
Streams.pipeAll(pbIn, armoredOutputStream);
}
} catch (IOException e) {
err_ln("Input data cannot be ASCII armored.");
err_ln(e.getMessage());
System.exit(1);
}
}
}