使用 RNGCryptoServiceProvider 生成秘钥

你可以使用C#的RNGCryptoServiceProvider类来生成随机的字节数组,然后将其转换为Base64编码的字符串作为JWT的秘钥。
using System;
using System.Security.Cryptography;

namespace YourNamespace
{
    public class JwtKeyGenerator
    {
        public static string GenerateJwtSecretKey(int keySize)
        {
            byte[] secretKeyBytes = new byte[keySize];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(secretKeyBytes);
            }
            return Convert.ToBase64String(secretKeyBytes);
        }

        public static void Main(string[] args)
        {
            // 生成256位(32字节)的随机秘钥
            string secretKey = GenerateJwtSecretKey(32);
            Console.WriteLine("Generated JWT Secret Key:");
            Console.WriteLine(secretKey);
        }
    }
}

 

 
posted @ 2024-06-04 15:32  龙卷风吹毁停车场  阅读(196)  评论(0)    收藏  举报