Create a pem private and public key

This is how to create a private and public pem key. And also an example no how to take use of the key in .NET.

  1. Open up git bash, cd into a folder of your preference.
  2. Enter command to create a private key:
    winpty openssl genrsa -out private.pem 2048
    Note that if you want to create a private key with a keyphrase enter in the parameter des3
  3. Create a public key based from the private key:
    winpty openssl rsa -in private.pem -outform PEM -pubout -out public.pem
  4. Now if we check in our folder we have two files:
    private.pem and public.pem

And if you would want to Create a Token or Validate a token you have methods like these in .NET (C#):

        public string CreateToken(List<Claim> claimList)
        {
            string privateKeyBytes = File.ReadAllText("./Secrets/private.pem");

            using RSA rsa = RSA.Create();
            rsa.ImportFromPem(privateKeyBytes);
            var signingCredentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256)
            {
                CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
            };

            var now = DateTime.Now;
            var unixTimeSeconds = new DateTimeOffset(now).ToUnixTimeSeconds();

            var jwt = new JwtSecurityToken(
                issuer: "my-key",
                claims: claimList,
                notBefore: now,
                expires: now.AddMinutes(30),
                signingCredentials: signingCredentials
            );

            return new JwtSecurityTokenHandler().WriteToken(jwt);
        }

        public bool ValidateToken(string token)
        {
            var publicKey = File.ReadAllText("./Secrets/private.pem");

            using RSA rsa = RSA.Create();
            rsa.ImportFromPem(publicKey);

            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = false,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "my-key",
                IssuerSigningKey = new RsaSecurityKey(rsa),
                CryptoProviderFactory = new CryptoProviderFactory()
                {
                    CacheSignatureProviders = false
                }
            };

            try
            {
                var handler = new JwtSecurityTokenHandler();
                var principal = handler.ValidateToken(token, validationParameters, out var validatedSecurityToken);
                principal.Claims.ToList().ForEach(claim => Debug.WriteLine(claim.Value));
            }
            catch (Exception ex)
            {
                Console.WriteLine("an error... log it some way " + ex.Message);
                return false;
            }

            return true;
        }

In the above example we use the key to set a JwtSecurityToken. This would assume you have your file in a folder called Secrets where you have your public and private key. With .NET we have the System.Security.Cryptography library where we can utulize these RSA algorithm methods which makes it easy, such method is ImportFromPem which does actually what it sounds like, it will read our private key from the pem file and put it into the rsa object, which we then can get retrive a SigningCredentinals object which we then can put into a jwt property for example. The audiance property can be set with an list of Claims coming from an authentication response with claims such as firstname lastname and so forth.

For the validation part, we get to use our public key to match the incoming token with the method ValidateToken from our JwtSecurityTokenHandler object. All we need to validate it is to set some TokenValidationParameters and the most important being the actual public rsa key from our pem file.

0 0 votes
Article rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments