private String signEnvelopeData ( String message ) throws LRException { // Throw an exception if any of the required fields are null if ( passPhrase == null || publicKeyLocation == null || privateKey == null ) { throw new LRException ( LRException . NULL_FIELD ) ; } // Get an InputStream for the private key InputStream privateKeyStream = getPrivateKeyStream ( privateKey ) ; // Get an OutputStream for the result ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; ArmoredOutputStream aOut = new ArmoredOutputStream ( result ) ; // Get the pass phrase char [ ] privateKeyPassword = passPhrase . toCharArray ( ) ; try { // Get the private key from the InputStream PGPSecretKey sk = readSecretKey ( privateKeyStream ) ; PGPPrivateKey pk = sk . extractPrivateKey ( new JcePBESecretKeyDecryptorBuilder ( ) . setProvider ( "BC" ) . build ( privateKeyPassword ) ) ; PGPSignatureGenerator sGen = new PGPSignatureGenerator ( new JcaPGPContentSignerBuilder ( sk . getPublicKey ( ) . getAlgorithm ( ) , PGPUtil . SHA256 ) . setProvider ( "BC" ) ) ; PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator ( ) ; // Clear sign the message java . util . Iterator it = sk . getPublicKey ( ) . getUserIDs ( ) ; if ( it . hasNext ( ) ) { spGen . setSignerUserID ( false , ( String ) it . next ( ) ) ; sGen . setHashedSubpackets ( spGen . generate ( ) ) ; } aOut . beginClearText ( PGPUtil . SHA256 ) ; sGen . init ( PGPSignature . CANONICAL_TEXT_DOCUMENT , pk ) ; byte [ ] msg = message . getBytes ( ) ; sGen . update ( msg , 0 , msg . length ) ; aOut . write ( msg , 0 , msg . length ) ; BCPGOutputStream bOut = new BCPGOutputStream ( aOut ) ; aOut . endClearText ( ) ; sGen . generate ( ) . encode ( bOut ) ; aOut . close ( ) ; String strResult = result . toString ( "utf8" ) ; // for whatever reason, bouncycastle is failing to put a linebreak before "-----BEGIN PGP SIGNATURE" strResult = strResult . replaceAll ( "([a-z0-9])-----BEGIN PGP SIGNATURE-----" , "$1\n-----BEGIN PGP SIGNATURE-----" ) ; return strResult ; } catch ( Exception e ) { throw new LRException ( LRException . SIGNING_FAILED ) ; } finally { try { if ( privateKeyStream != null ) { privateKeyStream . close ( ) ; } result . close ( ) ; } catch ( IOException e ) { //Could not close the streams } } }
Encodes the provided message with the private key and pass phrase set in configuration