【发布时间】:2016-04-18 16:41:56
【问题描述】:
我目前正在用 java 编写一个加密的消息服务,并且我正在使用 bouncycastle PGP 库。我编写了一个生成密钥对并加密/解密消息的测试程序。这工作了一段时间,但最近在解密阶段停止了,给了我一个 InvalidKeyException。
我做了一些研究并下载了 JCE .jar 文件并将它们导入到我的项目中(通过 Eclipse 项目 -> 属性 -> 添加外部 JAR)。我看到对于 Windows 用户,它们应该被放入 java 库中的特定文件夹中,但我在我的 Mac 上找不到类似的文件夹。我尝试浏览 usr/library 文件夹,但找不到任何用处。
有人在 Mac 上解决了这个问题吗?
编辑:这是我的主要测试功能中的一些代码
// decrypt
byte[] decrypted = PGPEncryptDecrypt.decrypt(encFromFile, secKey, pass.toCharArray());
这是我的解密方法(这不是我写的,但我做了一个 PGPEncryptDecrypt 类来保存相关的静态方法,它对我有用)
public static byte[] decrypt(byte[] encrypted, InputStream keyIn, char[] password)
throws IOException, PGPException, NoSuchProviderException {
InputStream in = new ByteArrayInputStream(encrypted);
in = PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc = null;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
PGPUtil.getDecoderStream(keyIn));
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = findSecretKey(pgpSec, pbe.getKeyID(), password);
}
if (sKey == null) {
throw new IllegalArgumentException(
"secret key for message not found.");
}
InputStream clear = pbe.getDataStream(sKey, "BC");
PGPObjectFactory pgpFact = new PGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();
pgpFact = new PGPObjectFactory(cData.getDataStream());
PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();
InputStream unc = ld.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int ch;
while ((ch = unc.read()) >= 0) {
out.write(ch);
}
byte[] returnBytes = out.toByteArray();
out.close();
return returnBytes;
}
错误指向findSecretKey(在PGPEncryptDecrypt类中)方法,如下
public static PGPPrivateKey findSecretKey(
PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
throws PGPException, NoSuchProviderException {
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) {
return null;
}
return pgpSecKey.extractPrivateKey(pass, "BC");
}
当我第一次实现这些功能时,它们都运行良好,但它们停止工作了。
【问题讨论】:
-
请为抛出异常的部分添加一些代码
标签: java macos encryption bouncycastle pgp