mattosaurus / PgpCore

.NET Core class library for using PGP
MIT License
234 stars 98 forks source link

PGPCore Error: Org.BouncyCastle.Bcpg.OpenPgp.PgpSecretKeyRing found where PgpPublicKeyRing expected #259

Closed Absamis closed 8 months ago

Absamis commented 9 months ago

Hello, i'm using PGPCore Version 6.0.0 in my C# application. I was able to generate Key to .asc file and also, encrypt string succesfuly. But the Description is showing me this error: Org.BouncyCastle.Bcpg.OpenPgp.PgpSecretKeyRing found where PgpPublicKeyRing expected Below is my code structure

Generating Key

        public void GenerateSecurityKey(string username = null, string password = null)
        {
            using(PGP pgp = new PGP())
            {
                string pubKeyFile = $"{_config["KeyPath"]}/publickey.asc";
                string prvKeyFile = $"{_config["KeyPath"]}/privatekey.asc";
                var fl = File.Create(pubKeyFile);
                fl.Close();
                fl = File.Create(prvKeyFile);
                fl.Close();

                var publicKey = new FileInfo(pubKeyFile);
                var privateKey = new FileInfo(prvKeyFile);
                pgp.GenerateKey(publicKey, privateKey, username, password);

                Console.WriteLine($"\r\nKey Generated successfully.\r\nLocate it at {pubKeyFile}, {prvKeyFile}");
            }
        }

Encrypt Text

public async Task<string> EncryptText(string publicKeyPath, string content)
        {
            try
            {
                string publicKey = File.ReadAllText(publicKeyPath);
                EncryptionKeys encryptionKeys = new EncryptionKeys(publicKey);

                // Encrypt
                PGP pgp = new PGP(encryptionKeys);
                string encryptedContent = await pgp.EncryptAsync(content);
                return encryptedContent;
            }catch(Exception ex)
            {
                return null;
            }
        }

Decrypt Text

public async Task<string> DecryptText(string privateKeyPath, string content)
        {
            try
            {
                string privateKey = File.ReadAllText(privateKeyPath);
                EncryptionKeys encryptionKeys = new EncryptionKeys(privateKey);

                // Decrypt
                PGP pgp = new PGP(encryptionKeys);
                string decryptedContent = await pgp.DecryptAsync(content);
                return decryptedContent;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

Kindly help to look into this as soon as possible

mattosaurus commented 9 months ago

For your decryption method you need to pass the password to the EncryptionKeys constructer as well. If you only pass a single argument it thinks it's a public key.

https://github.com/mattosaurus/PgpCore/blob/c5146c0f42c107efc65cbc526983c4e612a921f9/PgpCore/Models/EncryptionKeys.cs#L176