jose-jwt icon indicating copy to clipboard operation
jose-jwt copied to clipboard

Issue when encrypt using RSA_OAEP_256 and A256GCM

Open frankl1m opened this issue 1 year ago • 5 comments

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

frankl1m avatar Mar 29 '23 04:03 frankl1m

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

dvsekhvalnov avatar Mar 29 '23 19:03 dvsekhvalnov

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.

frankl1m avatar Apr 04 '23 09:04 frankl1m

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

dvsekhvalnov avatar Apr 06 '23 06:04 dvsekhvalnov

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

frankl1m avatar Apr 07 '23 08:04 frankl1m

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

dvsekhvalnov avatar Apr 10 '23 05:04 dvsekhvalnov