[英]How do I store and read PGP public keys as strings using Bouncycastle Java?
我一直在尝试创建,编码,存储,检索和解码Bouncy Castle PGP公钥。 当我尝试重新读回密钥时,得到的输出似乎是错误的,并且出现了EOFException。该密钥将作为字符串存储在数据库中。
从密钥环中提取原始的RSA加密公共密钥,如下所示:
@SuppressWarnings("unchecked")
public PGPPublicKey getPublicKey() {
PGPPublicKey pk = null;
Iterator<PGPPublicKey> it = publicKeyRing.getPublicKeys();
while (pk == null && it.hasNext()) {
PGPPublicKey key = it.next();
if (key.isEncryptionKey()) {
pk = key;
}
}
return pk;
}
它经过编码,ASCII防护并存储为字符串,如下所示:
PGPPublicKey contactPK = realContact.getPublicKey();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ArmoredOutputStream armored = new ArmoredOutputStream(out);
contactPK.encode(armored);
armored.close();
publicKey = new String(out.toByteArray(), Charset.forName("US-ASCII"));
这给了我一个PGP消息块,在这里我希望有一个PGP公钥块:
----- BEGIN PGP MESSAGE ----- \\ n版本:BCPG V1.50 \\ n \\ nuQINBFO8StkCEACQ4vrDnBTDjEvQkGwrAHuJSBZL8tNLxhZ9B74afhObhLVzW6ZB \\ nT3pk / 5XcSPOTvcWd9k1yOKJUabCuF5ixFmMz + niFqUVQTtnl7aqOZ + GrDEzmoYmG \\ nNQROP0EiA1TWtm2 + Ja0FqiJauXytt1sIF / Pr5L47FCjtmZKVoXTP8RVFfGLPB0kT \\ ndjOz53PaEE3GSValh85w24XIH2 / gczURUnjphCX1bRwTFr14SfA9X / rFWqv9SqWQ \\ nV8OiIWrSiwNd5RLJ9q0B + viDzoxrjmnMJZikxhKiuNVKJCu2ccBdMrbW42iBM2w3 \\ n
...(为简洁起见)
\\ n -----结束PGP消息-----
当我尝试重新读取字符串以重新创建公共密钥时,出现了EOFException:
// Import the public key.
ByteArrayInputStream in =
new ByteArrayInputStream(stored.publicKey.getBytes(
Charset.forName("US-ASCII")));
// Needed to read ASCII armored keys
InputStream decoded = PGPUtil.getDecoderStream(in);
BCPGInputStream bcpgIn = new BCPGInputStream(decoded);
RSAPublicBCPGKey bcpgKey = new RSAPublicBCPGKey(bcpgIn);
PublicKeyPacket pkPacket = new PublicKeyPacket(PublicKeyAlgorithmTags.RSA_ENCRYPT,
new Date(), bcpgKey);
publicKey = new PGPPublicKey(pkPacket, new BcKeyFingerprintCalculator());
创建RSAPublicBCPGKey时会发生异常。
我做错了什么,但我不知道这是什么。 有人可以帮忙吗?
假设您已经在String str中拥有pgp公钥(铠装ascii):
InputStream in=new ByteArrayInputStream(str.getBytes());
in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
JcaPGPPublicKeyRingCollection pgpPub = new JcaPGPPublicKeyRingCollection(in);
in.close();
PGPPublicKey key = null;
Iterator<PGPPublicKeyRing> rIt = pgpPub.getKeyRings();
while (key == null && rIt.hasNext())
{
PGPPublicKeyRing kRing = rIt.next();
Iterator<PGPPublicKey> kIt = kRing.getPublicKeys();
while (key == null && kIt.hasNext())
{
PGPPublicKey k = kIt.next();
if (k.isEncryptionKey())
{
key = k;
}
}
}
return key;
现在,您的可变键将具有您的PGPPublicKey。
我遇到了这个问题,结果证明公钥环实际上是公钥本身。 当我运行迭代器时,我实际上是在获取子密钥(该子密钥变成了该消息块而不是公共密钥块)。 如果我不能很好地解释,请查看此解释 。
假设realContact
是仅包含子键的公共密钥环,则实际上不需要通过getPublicKey()
运行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.