我正在尝试编写一个使用私钥对文件进行签名的 Java 程序。该程序采用 3 个参数 - 文件、密钥环和密码。输出应该在一个分离的文件 *.bpg 中。问题是当我尝试编译代码时出现以下错误:
C:\CNS3\BCastle>javac Sign.java
Note: Sign.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
我的代码如下:
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 && rIt.hasNext()) {
PGPSecretKeyRing kRing = (PGPSecretKeyRing)rIt.next();
Iterator kIt = kRing.getSecretKeys();
while ( key == null && 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()) >= 0 ) { sGen.update((byte)ch); }
sGen.generate().encode(bOut);
cGen.close();
out.close();
}
}
错误来自以下几行:
PGPPrivateKey pgpPrivKey =
key.extractPrivateKey(args[2].toCharArray(), "BC");
PGPSignatureGenerator sGen = new PGPSignatureGenerator(
key.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
有人对我如何解决这个问题有任何建议吗?非常感谢!