Skip to content

Instantly share code, notes, and snippets.

@brcolow
Created June 21, 2021 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brcolow/a6746ceba494825a0e93b202909312a5 to your computer and use it in GitHub Desktop.
Save brcolow/a6746ceba494825a0e93b202909312a5 to your computer and use it in GitHub Desktop.
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.operator.DigestCalculator;
import org.bouncycastle.operator.DigestCalculatorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.bc.BcDefaultDigestProvider;
import org.bouncycastle.operator.bc.BcDigestProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
public class DebugDigestCalculatorProvider implements DigestCalculatorProvider {
private final BcDigestProvider digestProvider = BcDefaultDigestProvider.INSTANCE;
private static final Logger LOGGER = LoggerFactory.getLogger(DebugDigestCalculatorProvider.class);
public DigestCalculator get(final AlgorithmIdentifier algorithm) throws OperatorCreationException {
Digest dig = digestProvider.get(algorithm);
final DigestOutputStream stream = new DigestOutputStream(dig);
return new DigestCalculator() {
@Override
public AlgorithmIdentifier getAlgorithmIdentifier() {
return algorithm;
}
@Override
public OutputStream getOutputStream() {
return stream;
}
@Override
public byte[] getDigest() {
return stream.getDigest();
}
};
}
private static class DigestOutputStream extends OutputStream {
private final Digest dig;
DigestOutputStream(Digest dig) {
LOGGER.info("DigestOutputStream, digest = " + dig.getAlgorithmName());
this.dig = dig;
}
public void write(byte[] bytes, int off, int len) throws IOException {
System.out.print(new String(bytes, off, len, StandardCharsets.ISO_8859_1).replace("\t", "[TAB]").replace("\r", "[CR]").replace("\n", "[LF]"));
dig.update(bytes, off, len);
}
public void write(byte[] bytes) throws IOException {
System.out.print(new String(bytes, StandardCharsets.ISO_8859_1).replace("\t", "[TAB]").replace("\r", "[CR]").replace("\n", "[LF]"));
dig.update(bytes, 0, bytes.length);
}
public void write(int b) throws IOException {
System.out.print(new String(new byte[] { (byte) b }, StandardCharsets.ISO_8859_1).replace("\t", "[TAB]").replace("\r", "[CR]").replace("\n", "[LF]"));
dig.update((byte) b);
}
byte[] getDigest() {
byte[] d = new byte[dig.getDigestSize()];
dig.doFinal(d, 0);
LOGGER.info("Digest: " + CertificateUtils.bytesToHex(d));
return d;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment