title: Java signing files with BouncyCastle - Create signature of a file using secret keyring
body: <p>I'm trying to write a Java program that signs a file with a private key. The program takes 3 arguments - file, secret keyring and a password. The output should be in a detached file *.bpg. The problem is that I get the following errors when I try to compile my code:</p>
  
  <pre><code>C:\CNS3\BCastle&gt;javac Sign.java
  Note: Sign.java uses or overrides a deprecated API.
  Note: Recompile with -Xlint:deprecation for details.
  </code></pre>
  
  <p>My code is as follows:</p>
  
  <pre><code>import java.io.*;
  import java.security.*;
  import java.util.Iterator;
  
  import org.bouncycastle.bcpg.*;
  import org.bouncycastle.jce.provider.BouncyCastleProvider;
  import org.bouncycastle.openpgp.*;
  
  public class Sign {
    public static void main(String[] args) throws Exception {
      Security.addProvider(new BouncyCastleProvider());
      FileInputStream keyIn = new FileInputStream(args[1]);
      FileOutputStream out = new FileOutputStream(args[0] + ".bpg");
      InputStream in = PGPUtil.getDecoderStream(keyIn);
      PGPSecretKeyRingCollection pgpSec = 
                                 new PGPSecretKeyRingCollection(in);
      PGPSecretKey key = null;
      Iterator rIt = pgpSec.getKeyRings();
      while (key == null &amp;&amp; rIt.hasNext()) {
        PGPSecretKeyRing kRing = (PGPSecretKeyRing)rIt.next();
        Iterator kIt = kRing.getSecretKeys();
        while ( key == null &amp;&amp; kIt.hasNext() ) {
          PGPSecretKey k = (PGPSecretKey)kIt.next();
          if ( k.isSigningKey() ) { key = k; }
        }
      }
      if (key == null) {
        throw new IllegalArgumentException("Can't find key");
      }
      PGPPrivateKey pgpPrivKey = 
           key.extractPrivateKey(args[2].toCharArray(), "BC");
      PGPSignatureGenerator sGen = new PGPSignatureGenerator(
           key.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
      sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
      PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(
           PGPCompressedDataGenerator.ZLIB);
      BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out));
      FileInputStream fIn = new FileInputStream(args[0]);
      int ch = 0;
      while ( (ch = fIn.read()) &gt;= 0 ) { sGen.update((byte)ch); }
      sGen.generate().encode(bOut);
      cGen.close();
      out.close();
    }
  }
  </code></pre>
  
  <p>The errors come from the following lines:</p>
  
  <pre><code>    PGPPrivateKey pgpPrivKey = 
           key.extractPrivateKey(args[2].toCharArray(), "BC");
      PGPSignatureGenerator sGen = new PGPSignatureGenerator(
           key.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
      sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
  </code></pre>
  
  <p>Anyone have any suggestion on how I might fix this? Thanks a lot!</p>