如何在C#中使用Bouncy Castle签署公共PGP密钥

时间:2017-07-18 17:54:52

标签: c# bouncycastle pgp

我想在我的应用程序中创建信任支持网站,允许我的用户使用他们的私钥,签署其他用户的公钥 - 使用C#和Bouncy Castle。

我已经弄清楚了大部分事情,比如创建PGP密钥,使用HTTP REST将它们提交给关键服务器,加密MIME消息并加密签名(使用MimeKit) - 但剩下的一个障碍就是想可以使用我的私钥的一些代码,使用Bouncy Castle签署另一个人的公钥。

由于BC的文件很糟糕,弄清楚这些部分,以前证明几乎不可能......

为了记录,我使用GnuPG作为密钥的存储空间。

如果到目前为止有人想查看我的代码,请随时查看here

我可能不应该在这里问这个问题,但是我也很喜欢它,如果那里的一些BC专家到目前为止可以对我的代码进行一般的审视,并检查我是否做了个傻瓜我自己到目前为止所做的事情......

1 个答案:

答案 0 :(得分:1)

经过大量试验和错误后找到了答案,这里是......

private static byte[] SignPublicKey(
    PgpSecretKey secretKey,
    string password,
    PgpPublicKey keyToBeSigned,
    bool isCertain)
{
    // Extracting private key, and getting ready to create a signature.
    PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey (password.ToCharArray());
    PgpSignatureGenerator sGen = new PgpSignatureGenerator (secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);
    sGen.InitSign (isCertain ? PgpSignature.PositiveCertification : PgpSignature.CasualCertification, pgpPrivKey);

    // Creating a stream to wrap the results of operation.
    Stream os = new MemoryStream();
    BcpgOutputStream bOut = new BcpgOutputStream (os);
    sGen.GenerateOnePassVersion (false).Encode (bOut);

    // Creating a generator.
    PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
    PgpSignatureSubpacketVector packetVector = spGen.Generate();
    sGen.SetHashedSubpackets (packetVector);
    bOut.Flush();

    // Returning the signed public key.
    return PgpPublicKey.AddCertification (keyToBeSigned, sGen.Generate()).GetEncoded();
}