public static String validateLicense ( String licenseText ) throws PGPException { licenseText = licenseText . trim ( ) . replaceAll ( "\\r|\\n" , "" ) ; licenseText = licenseText . replace ( "---- SCHNIPP (Armored PGP signed JSON as base64) ----" , "" ) ; licenseText = licenseText . replace ( "---- SCHNAPP ----" , "" ) ; try { final byte [ ] armoredPgp = BaseEncoding . base64 ( ) . decode ( licenseText ) ; final ArmoredInputStream in = new ArmoredInputStream ( new ByteArrayInputStream ( armoredPgp ) ) ; // // read the input, making sure we ignore the last newline. // // https://github.com/bcgit/bc-java/blob/master/pg/src/test/java/org/bouncycastle/openpgp/test/PGPClearSignedSignatureTest.java final ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; int ch ; while ( ( ch = in . read ( ) ) >= 0 && in . isClearText ( ) ) { bout . write ( ( byte ) ch ) ; } final KeyFingerPrintCalculator c = new BcKeyFingerprintCalculator ( ) ; final PGPObjectFactory factory = new PGPObjectFactory ( in , c ) ; final PGPSignatureList sigL = ( PGPSignatureList ) factory . nextObject ( ) ; final PGPPublicKeyRingCollection pgpRings = new PGPPublicKeyRingCollection ( new ArmoredInputStream ( LicenseHelper . class . getResourceAsStream ( "/KEYS" ) ) , c ) ; if ( sigL == null || pgpRings == null || sigL . size ( ) == 0 || pgpRings . size ( ) == 0 ) { throw new PGPException ( "Cannot find license signature" ) ; } final PGPSignature sig = sigL . get ( 0 ) ; final PGPPublicKey publicKey = pgpRings . getPublicKey ( sig . getKeyID ( ) ) ; if ( publicKey == null || sig == null ) { throw new PGPException ( "license signature key mismatch" ) ; } sig . init ( new BcPGPContentVerifierBuilderProvider ( ) , publicKey ) ; final ByteArrayOutputStream lineOut = new ByteArrayOutputStream ( ) ; final InputStream sigIn = new ByteArrayInputStream ( bout . toByteArray ( ) ) ; int lookAhead = readInputLine ( lineOut , sigIn ) ; processLine ( sig , lineOut . toByteArray ( ) ) ; if ( lookAhead != - 1 ) { do { lookAhead = readInputLine ( lineOut , lookAhead , sigIn ) ; sig . update ( ( byte ) ' ' ) ; sig . update ( ( byte ) ' ' ) ; processLine ( sig , lineOut . toByteArray ( ) ) ; } while ( lookAhead != - 1 ) ; } if ( ! sig . verify ( ) ) { throw new PGPException ( "Invalid license signature" ) ; } return bout . toString ( ) ; } catch ( final Exception e ) { throw new PGPException ( e . toString ( ) , e ) ; } }
Validate pgp signature of license