001package org.vafer.jdeb.utils; 002 003import java.io.ByteArrayOutputStream; 004import java.io.IOException; 005import java.io.OutputStream; 006 007import org.bouncycastle.bcpg.ArmoredOutputStream; 008import org.bouncycastle.openpgp.PGPException; 009import org.bouncycastle.openpgp.PGPSignature; 010import org.bouncycastle.openpgp.PGPSignatureGenerator; 011 012/** 013 * An output stream that calculates the signature of the input data as it 014 * is written 015 */ 016public class PGPSignatureOutputStream extends OutputStream { 017 private final PGPSignatureGenerator signatureGenerator; 018 019 public PGPSignatureOutputStream( PGPSignatureGenerator signatureGenerator ) { 020 super(); 021 this.signatureGenerator = signatureGenerator; 022 } 023 024 public void write( int b ) throws IOException { 025 signatureGenerator.update(new byte[] { (byte)b }); 026 } 027 028 public void write( byte[] b ) throws IOException { 029 signatureGenerator.update(b); 030 } 031 032 public void write( byte[] b, int off, int len ) throws IOException { 033 signatureGenerator.update(b, off, len); 034 } 035 036 public PGPSignature generateSignature() throws PGPException { 037 return signatureGenerator.generate(); 038 } 039 040 public String generateASCIISignature() throws PGPException { 041 try { 042 PGPSignature signature = generateSignature(); 043 ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 044 ArmoredOutputStream armorStream = new ArmoredOutputStream(buffer); 045 signature.encode(armorStream); 046 armorStream.close(); 047 return new String(buffer.toByteArray()); 048 } catch(IOException e) { 049 //Should never happen since we are just using a memory buffer 050 throw new RuntimeException(e); 051 } 052 } 053 054}