* @param algorithm the algorithm to use. Can be extracted from public key.
* @return reference to the new key added to the consumers
*/
public Key<byte[]> start( final PGPPrivateKey key, int algorithm ) {
BcPGPContentSignerBuilder contentSignerBuilder = new BcPGPContentSignerBuilder( algorithm, SHA1 );
final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( contentSignerBuilder );
try {
signatureGenerator.init( BINARY_DOCUMENT, key );
} catch ( PGPException e ) {
throw new RuntimeException( "Could not initialize PGP signature generator", e );
}
final Key<byte[]> object = new Key<byte[]>();
consumers.put( object, new Consumer<byte[]>() {
public void consume( final ByteBuffer buffer ) {
if ( !buffer.hasRemaining() ) {
return;
}
try {
write( buffer );
} catch ( SignatureException e ) {
throw new RuntimeException( "Could not write buffer to PGP signature generator.", e );
}
}
private void write( ByteBuffer buffer ) throws SignatureException {
if ( buffer.hasArray() ) {
byte[] bufferBytes = buffer.array();
int offset = buffer.arrayOffset();
int position = buffer.position();
int limit = buffer.limit();
signatureGenerator.update( bufferBytes, offset + position, limit - position );
buffer.position( limit );
} else {
int length = buffer.remaining();
byte[] bytes = new byte[JCAUtil.getTempArraySize( length )];
while ( length > 0 ) {
int chunk = Math.min( length, bytes.length );
buffer.get( bytes, 0, chunk );
signatureGenerator.update( bytes, 0, chunk );
length -= chunk;
}
}
}
public byte[] finish() {
try {
return signatureGenerator.generate().getEncoded();
} catch ( Exception e ) {
throw new RuntimeException( "Could not generate signature.", e );
}
}
});