使用BouncyCastle加密文件,输出看起来已损坏

本文关键字:输出 看起来 已损坏 文件 BouncyCastle 加密 使用 | 更新日期: 2023-09-27 18:01:07

所以我用这段代码来加密我的文件

如您所见,IAM 使用公共 PGP

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.6 (GNU/Linux)
masdSFVkRBADYxPZYC+nu9nhSVkxcVkVJ5axZKzCRuygqUxka
kZIBy2CAQVKz5dBkRaUkaaksbcyautks7asaov26Fc9cT25Rvnh7
wYIJhcRoIl4cxashdgutasd0qfcOnVB5JVCQDhXclBW7kwCgkoUW
....
...
...
-----END PGP PUBLIC KEY BLOCK-----

代码工作正常,但我认为编码文件的数据已损坏

因为它不以这种格式出现(如密钥(

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.6 (GNU/Linux)
masdSFVkRBADYxPZYC+nu9nhSVkxcVkVJ5axZKzCRuygqUxka
kZIBy2CAQVKz5dBkRaUkaaksbcyautks7asaov26Fc9cT25Rvnh7
wYIJhcRoIl4cxashdgutasd0qfcOnVB5JVCQDhXclBW7kwCgkoUW
....
...
...
-----END PGP PUBLIC KEY BLOCK-----

我错了吗?

输出不应该是相同的格式吗?

using System;
using System.Xml;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Bcpg;
class CPGPencrypt
{
    private static PgpPublicKey ReadPublicKey(Stream inputStream)
    {
        inputStream = PgpUtilities.GetDecoderStream(inputStream);
        PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);
        //
        // we just loop through the collection till we find a key suitable for encryption, in the real
        // world you would probably want to be a bit smarter about this.
        //
        //
        // iterate through the key rings.
        //
        foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings())
        {
            foreach (PgpPublicKey k in kRing.GetPublicKeys())
            {
                if (k.IsEncryptionKey)
                {
                    return k;
                }
            }
        }
        throw new ArgumentException("Can't find encryption key in key ring.");
    }
    private static byte[] EncryptFile(byte[] clearData, string fileName, PgpPublicKey encKey, bool withIntegrityCheck)
    {
        MemoryStream bOut = new MemoryStream();
        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
            CompressionAlgorithmTag.Zip);
        Stream cos = comData.Open(bOut); // open it with the final destination
        PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
        // we want to Generate compressed data. This might be a user option later,
        // in which case we would pass in bOut.
        Stream pOut = lData.Open(
            cos,                    // the compressed output stream
            PgpLiteralData.Binary,
            fileName,               // "filename" to store
            clearData.Length,       // length of clear data
            DateTime.UtcNow         // current time
        );
        pOut.Write(clearData, 0, clearData.Length);
        lData.Close();
        comData.Close();
        PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());
        cPk.AddMethod(encKey);
        byte[] bytes = bOut.ToArray();
        MemoryStream encOut = new MemoryStream();
        Stream os = encOut;
        Stream cOut = cPk.Open(os, bytes.Length);
        cOut.Write(bytes, 0, bytes.Length);  // obtain the actual bytes from the compressed stream
        cOut.Close();
        encOut.Close();
        return encOut.ToArray();
    }
    public static string Encrypt(string file_name,string file_to_read)
    {

        try
        {
            byte[] dataBytes = File.ReadAllBytes(file_to_read);
            Stream keyIn = File.OpenRead("pgpdata-public.asc");
            Stream outStream = File.Create(@"myfolder'"+file_name);
            byte[] encrypted = EncryptFile(dataBytes, @"myfolder'"+file_name, ReadPublicKey(keyIn), false);
            outStream.Write(encrypted, 0, encrypted.Length);
            keyIn.Close();
            outStream.Close();
        }
        catch (Exception e)
        {
            return e.Message;
        }
        return file_name;
    }

}

使用BouncyCastle加密文件,输出看起来已损坏

OpenPGP中有不同的编码方案,即

  1. 二进制数据和
  2. ASCII装甲数据。

特别是对于密钥交换,通常首选ASCII装甲格式,因为它更坚固且易于识别。对于邮件交换,这是强制性的(对于 7 位兼容性(。二进制版本也有优势,特别是在性能和存储(带宽(要求方面。

例如,GnuPG 默认使用二进制编码,除非您使用选项 --ascii 或缩写 -a 请求 ASCII 装甲版本。

看起来您的代码正在输出二进制编码,但工作正常。

您可以通过尝试解密(例如使用 GnuPG:gpg --decrypt file.pgp(轻松进行测试。或者,您可以使用gpg --list-packets file.pgp或使用更详细的实用程序pgpdump转储文件包含的OpenPGP数据包,该实用程序在大多数(unix(软件包存储库中可用:pgpdump file.pgp。与gpg --list-packets不同,它还将数据包和算法标识符解析为人类可读的字符串(gpg --list-packets只是转储其数字ID(。