dvsekhvalnov / jose-jwt

Ultimate Javascript Object Signing and Encryption (JOSE), JSON Web Token (JWT) and Json Web Keys (JWK) Implementation for .NET and .NET Core
MIT License
921 stars 183 forks source link

Issue when encrypt using RSA_OAEP_256 and A256GCM #220

Open frankl1m opened 1 year ago

frankl1m commented 1 year ago

public static string EncodeJWE(string body) { string spki = "-----BEGIN PUBLIC KEY-----\nENCODED PUBLIC KEY\n-----END PUBLIC KEY-----".Replace("\n-----END PUBLIC KEY-----", "").Replace("-----BEGIN PUBLIC KEY-----\n", ""); JweRecipient r3 = new JweRecipient(JweAlgorithm.RSA_OAEP_256,Convert.FromBase64String(spki)); return JWE.Encrypt(body, new[] { r3 }, JweEncryption.A256GCM); }

When i try to encrypt always i have only public Key, but always i get System.ArgumentException: 'RsaKeyManagement algorithm expects key to be of CngKey, RSACryptoServiceProvider, RSA types or Jwk type with kty='rsa'.' I am using Netfx 4.7.2

dvsekhvalnov commented 1 year ago

Hi @frankl1m ,

your spki var is a string and this is not something library accepts as a key.

Checkout docs: https://github.com/dvsekhvalnov/jose-jwt#rsa--key-management-family-of-algorithms

Your easiest option is to use openssl to convert you PEM encoded key into .p12 or see https://stackoverflow.com/questions/11506891/how-to-load-the-rsa-public-key-from-file-in-c-sharp

frankl1m commented 1 year ago

private static RSA rsa = null;

    public static void GenRSAIfNull()
    {
        if (rsa == null)
        {
            rsa = RSA.Create();
            rsa.FromXmlString(certificatestringxml);
            string text = EncodeJWE("prueba");

            string dec = DecodeJWE(text);

        }
    }

    public static string EncodeJWE(string body)
    {
        return JWT.Encode(body, rsa,JweAlgorithm.RSA_OAEP_256, JweEncryption.A256GCM);
    }

    public static string DecodeJWE(string encbody)
    {
        return JWT.Decode(encbody, rsa, JweAlgorithm.RSA_OAEP_256, JweEncryption.A256GCM);
    }

i have this code, all on encryption is OK, when i try decode the same string encoded before, always get same Exception System.Security.Cryptography.CryptographicException: 'Invalid key to use in the specified state.

dvsekhvalnov commented 1 year ago

Hey @frankl1m , did you export private key? To decode encrypted payload you need private part of keypair.

Typically when exporting RSA key you want RSA.ToXmlString(true) to preserve private part in xml

frankl1m commented 1 year ago

The certificate used only have Public Key, so if RSA.ToXmlString(true) get exception

dvsekhvalnov commented 1 year ago

@frankl1m you can't decrypt with public key only. You need private key to do it.