对称解密抛出错误

symmetric decryption throwing error

我正在努力添加解密使用 GPG 和对称加密加密的文件的功能。

然而,每当它试图获取私钥数据时,这个异常就会不断发生:

Unable to cast object of type 'Org.BouncyCastle.Bcpg.OpenPgp.PgpPbeEncryptedData' to type 'Org.BouncyCastle.Bcpg.OpenPgp.PgpPublicKeyEncryptedData'.

到处都是你的做法:

Stream inputStream = IoHelper.GetStream(inputData);
        PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
        PgpObject pgp = null;
        if (pgpFactory != null)
        {
            pgp = pgpFactory.NextPgpObject();
        }

        PgpEncryptedDataList encryptedData = null;
        if (pgp is PgpEncryptedDataList)
        {
            encryptedData = (PgpEncryptedDataList)pgp;
        }
        else
        {
            encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject();
        }

        Stream privateKeyStream = File.OpenRead(PrivateKeyOnlyPath);

        // find secret key
        PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));
        PgpPrivateKey privateKey = null;

        foreach (PgpPublicKeyEncryptedData pked in encryptedData.GetEncryptedDataObjects())
        {
            privateKey = FindSecretKey(pgpKeyRing, pked.KeyId, Password.ToCharArray());
            if (privateKey != null)
            {
                //pubKeyData = pked;
                break;
            }
        }

我引用的代码来自 here

我不知道为什么它不起作用,也不确定下一步该去哪里。

混合密码系统

OpenPGP(由 GnuPG 实现)中的 "normal" 加密方式是混合加密:public/private 密钥加密用于密钥管理和加密会话密钥,随后使用此会话密钥进行对称加密实际数据。

根据您所写的内容,似乎省略了 public/private 密钥加密步骤,而是使用密码生成会话密钥,例如使用命令 gpg --symmetric。您可以使用 pgpdump 确定它是如何加密的。对称加密文件的输出看起来像

Old: Symmetric-Key Encrypted Session Key Packet(tag 3)(13 bytes)
    New version(4)
    Sym alg - CAST5(sym 3)
    Iterated and salted string-to-key(s2k 3):
        Hash alg - SHA512(hash 10)
        Salt - 3b be 1b 03 64 c3 bb 7e 
        Count - 102400(coded count 105)
New: Symmetrically Encrypted Data Packet(tag 9)(26 bytes)
    Encrypted data [sym alg is specified in sym-key encrypted session key]

特别考虑带有对称密钥加密会话密钥数据包的第一行。

做什么

抱歉,我不太了解 C#,也没有使用过 Bouncy Castle,因此我无法提供现成的 运行 解决方案。此外,C# 文档似乎或多或少不存在。

我猜你必须使用 PgpPbeEncryptedData class, which seems to take an input stream and a passphrase and provides the decrypted information as an output stream. There is an example for the Java Bouncy Castle package,它可能非常相似,主要归结为

byte[] decryptedAgainByteArray = ByteArrayHandler.decrypt(encryptedAgain, PASS.toCharArray());