How to sign a JWT using RS256 with RSA private key in Asp.net core | Create and sign JWT token with RS256 using the private key in C#

Create and sign JWT token with RS256 using the private key

ASP.NET Core 2.0 does have support for RSA, including RSA encryption and digital signatures. 
The key size for RSA encryption and signatures in ASP.NET Core is generally not specified as "RSA 256".

To generate RS256 JWT (JSON Web Token) tokens in C#, you can use libraries like System.IdentityModel.Tokens.Jwt
Only Available .framework 6.1 and later versions.

Required:
1. (Jwt token (RSA256(Header+Payload,PrivateKey))  IVECTOR="16 Character any String" symmetricKeyValue="32 character string")
2. PrivateKeyFactory is not supported by lower frameworks.
you can use libraries like
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

// Header Input
string header = Convert.ToString(Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Header));
var encodedHeader = Base64UrlEncode(Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(header)));

// Payload Input
string payload = Convert.ToString(Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Payload));
var encodedPayload = Base64UrlEncode(Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(payload)));

var JwtString = RSA256(header, payload, PrivatekeyPlainwithoutHeader);  // Header,Payload,Privatekey without_header is needed

// Convert the key and data to byte arrays
//Append IVector+Jwt
JwtString = IVECTORChar + "" + JwtString;

byte[] keyBytes = Encoding.UTF8.GetBytes(symmetricKeyValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(JwtString);

// Create an AES encryption algorithm instance
using (Aes aesAlg = Aes.Create())
{
    aesAlg.Key = keyBytes;

    // Generate a random IV (Initialization Vector)
    //aesAlg.GenerateIV();
    aesAlg.IV = Encoding.UTF8.GetBytes(IVECTORChar); // Replace with your IV
                                                     //byte[] iv = Encoding.UTF8.GetBytes("hnykbweLKJ8uqxan"); // Replace with your IV

    // Create an encryptor with the AES algorithm
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

    // Create a memory stream to write the encrypted data
    using (MemoryStream msEncrypt = new MemoryStream())
    {
        // Create a CryptoStream to perform the encryption
        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
        {
            // Write the plaintext to the CryptoStream
            csEncrypt.Write(plainTextBytes, 0, plainTextBytes.Length);
            csEncrypt.FlushFinalBlock();

            // Get the IV and the encrypted data
            byte[] ivBytes = aesAlg.IV;
            byte[] encryptedBytes = msEncrypt.ToArray();

            // Convert the IV and encrypted data to base64 strings for storage or transmission
            string ivBase64 = Convert.ToBase64String(ivBytes);
            string encryptedBase64 = Convert.ToBase64String(encryptedBytes);

            //Console.WriteLine("IV: " + ivBase64);
            RequestSignatureEncryptedValueFinal = encryptedBase64;
        }
    }
}

Output:
********
public string RSA256(string header, string payload, string privateKey)
{
    ArrayList arlist = new ArrayList();
    DateTime issued = DateTime.Now;
    DateTime expire = DateTime.Now.AddHours(10);

    byte[] headerBytes = Encoding.UTF8.GetBytes(header);
    byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);

    arlist.Add(Base64UrlEncode(headerBytes));
    arlist.Add(Base64UrlEncode(payloadBytes));

    string stringToSign = string.Join(".", arlist.ToArray());

    byte[] bytesToSign = Encoding.UTF8.GetBytes(stringToSign);

    byte[] keyBytes = Convert.FromBase64String(privateKey);

    var asymmetricKeyParameter = PrivateKeyFactory.CreateKey(keyBytes);
    var rsaKeyParameter = (RsaKeyParameters)asymmetricKeyParameter;

    ISigner sig = SignerUtilities.GetSigner("SHA256withRSA");
    sig.Init(true, rsaKeyParameter);

    sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
    byte[] signature = sig.GenerateSignature();

    arlist.Add(Base64UrlEncode(signature));
    return string.Join(".", arlist.ToArray());
}
        private static string Base64UrlEncode(byte[] input)
        {
            var base64 = Convert.ToBase64String(input);
            var base64Url = base64.Replace("+", "-").Replace("/", "_").TrimEnd('=');
            return base64Url;
        }

Post a Comment

0 Comments