Encrypting JWT payload

后端 未结 3 1774
刺人心
刺人心 2020-12-31 01:07

JWTs have 3 parts:

  1. HEADER:ALGORITHM & TOKEN TYPE
  2. PAYLOAD:DATA
  3. SIGNATURE TO BE VERIFIED WITH THE SECRET KEY

Is it possible to

3条回答
  •  有刺的猬
    2020-12-31 02:06

    Below is a very simple and effective method for encrypting using AES. Note you will need to get your own key (link included in comments).

    Note that when you encrypt, it will set an IV for each encryption call. You will need this to decrypt.

    public class CustomEncryption
    {
        public static string Encrypt256(string text, byte[] AesKey256, out byte[] iv)
        {
            // AesCryptoServiceProvider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 256;
            aes.Key = aesKey256();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            iv = aes.IV;
    
            byte[] src = Encoding.Unicode.GetBytes(text);
    
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
    
                return Convert.ToBase64String(dest);
            }
        }
    
        public static string Decrypt256(string text, byte[] AesKey256, byte[] iv)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 256;
            aes.IV = iv;
            aes.Key = aesKey256();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
    
            byte[] src = System.Convert.FromBase64String(text);
    
            using (ICryptoTransform decrypt = aes.CreateDecryptor())
            {
                byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
                return Encoding.Unicode.GetString(dest);
            }
        }
    
        private static byte[] aesKey256()
        {
            //you will need to get your own aesKey
            //for testing you can generate one from
            //https://asecuritysite.com/encryption/keygen
    
            return new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5 };
        }
    }
    

    }

提交回复
热议问题