将PgpPublicKey保存到字符串

时间:2016-06-21 02:53:13

标签: c# bouncycastle openpgp

我正在生成公钥和密钥,并希望将公钥保存在字符串字段中。将其保存到文件中工作正常。但我怎么把它变成一个字符串......

    private string SaveAndReturn(PgpPublicKey publicKey, bool armor = true)
    {
        var fileStream = new FileInfo($@"C:\encrypt\Keys\pub2.asc").OpenWrite() as Stream;
        SaveFile(publicKey, fileStream, armor);
        fileStream.Close();
        var keyString = GetStringFromKey(publicKey);
        return keyString;
    }

    public void SaveFile(PgpPublicKey publicKey, Stream outStream, bool armor = true)
    {
        if (armor)
        {
            outStream = new ArmoredOutputStream(outStream);
        }
        publicKey.Encode(outStream);
        outStream.Close();

    }

    private string GetStringFromKey(PgpPublicKey publicKey)
    {
        var armor = true;
        var stream = new MemoryStream() as Stream;
        publicKey.Encode(stream);
        stream.Position = 0;
        var keyString = GetString(stream);
        stream.Close();
        Console.WriteLine(keyString);
        return keyString;
    }
    private string GetString(Stream theStream, Encoding encoding = null)
    {
        encoding = encoding ?? Encoding.UTF8;
        using (var reader = new StreamReader(theStream, encoding))
        {
            return reader.ReadToEnd();
        }
    }

pub2.asc文件创建正常并且在那里。而不是将密钥保存到文件中,我希望它成为一个字符串..以下代码给我一个空字符串。我究竟做错了什么? 因此,我在读取流之前更新了代码以设置位置。但返回的字符串与我在文件中看到的文本不同。 我认为ArmoredOutputStream执行Base64编码。如何获取与文本文件相同的字符串

以上代码中的字符串:

??? z}?。?u?l:?|?5?test ??瓦? $ ??? _ 11 CHπ L〜?? + ?? BC $?RN ??克???米?的???? 0?Z 4-1ķ???ģ?? mzBQ $ φ UËΔ V | / ?,升??? ??? = p ???? ???5 %% 9 ?? AE S | 8Lh \ ??? |的pB ?? G * 8 ???? N9'????????+(| R 11 Q因子@ř ?? _ 9D

如果我使用ASCII编码,则字符串为

??瓦{? ?? ; CGX ?? HO )... C〜????吨ROS 4 - :??????????????èFFÙR + = ?p 450#1 ?????一个14 B} ???? - 。3 O 10 q的i5 ??? Ff.??6???????6r?HdX ??} ?S?4?(j)3?测试?瓦? ∂ U + U ??????????? v ?????? BJEwp * 0'?LZ2 ?? 6Δ P,A 380 Q 10 2M ?? 3 A,带?? 9 ??? * ???? M%| U ^>??????????? q&安培;Δ V 20 N

来自Pub2.asc文件的文本

-----开始PGP公共钥匙块----- 版本:BCPG C#v1.8.1.0

mIsEV2h5lwEEAJakqTE + XcRBQ0b2P2vjNuDrgi9IcCsgEGdD3bpH6d1W8CSR + YKZ EV / PwmNI1dyh8Ex + zqHQKwaPCIfEQhNjF2sIJKVyTtjpZ4YukoRto3PBjdse0zAB 2Freiv7Ha9ct0wSQRwID2haKbXpCUSQN5 / j8xbx90y60ddxsOoV8C7A1AAUTtAR0 ZXN0iJwEEAECAAYFAldosdcACgkQPIdhk1pxnGAhxwQAg4NRYbuSDg5WVw3G1tVm 1xM746 + O5J6B5RHnaQvFePpVVUm / tpLyCbHPNeYlJao5FeHRYWWpU4d8OExo4phc iv7JfHBCx9tHKso4uccS3ROaTjknw + jwuLErKLN8UvjaUUBSn8wVXzlEDVXSRYCt Vnwv / Sxsxe7mgT2qBJSYcKY = = PYEC -----结束PGP公共密钥块-----

1 个答案:

答案 0 :(得分:0)

position的{​​{1}}仍设置为您在其中写入的字符串的结尾。在尝试再次阅读之前,您需要将位置重置为MemoryStream。您可以在调用代码中或直接在0中执行此操作。以下是调用代码中的修复:

GetString()

您还可以在How do you get a string from a MemoryStream?

找到一些有用的信息