Exemplo n.º 1
0
  /**
   * Create a clear sign signature over the input data. (Not detached)
   *
   * @param input the content to be signed
   * @param keyring the keyring
   * @param keyId the 4 bytes identifier of the key, in hexadecimal format
   * @param passphrase the passphrase to retrieve the private key
   * @param output the output destination of the signature
   */
  public static void clearSign(
      InputStream input, InputStream keyring, String keyId, String passphrase, OutputStream output)
      throws IOException, PGPException, GeneralSecurityException {
    PGPSecretKey secretKey = getSecretKey(keyring, keyId);
    PGPPrivateKey privateKey =
        secretKey.extractPrivateKey(
            new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
                .build(passphrase.toCharArray()));

    int digest = PGPUtil.SHA1;

    PGPSignatureGenerator signatureGenerator =
        new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), digest));
    signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);

    ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output);
    armoredOutput.beginClearText(digest);

    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

    String line;
    while ((line = reader.readLine()) != null) {
      // trailing spaces must be removed for signature calculation (see
      // http://tools.ietf.org/html/rfc4880#section-7.1)
      byte[] data = trim(line).getBytes("UTF-8");

      armoredOutput.write(data);
      armoredOutput.write(EOL);

      signatureGenerator.update(data);
      signatureGenerator.update(EOL);
    }

    armoredOutput.endClearText();

    PGPSignature signature = signatureGenerator.generate();
    signature.encode(new BCPGOutputStream(armoredOutput));

    armoredOutput.close();
  }