/// <summary>
        /// Encode a ProxyToken to base64 JWT, and sign it with the private key
        /// provided by the certificate.
        /// </summary>
        /// <param name="payload">
        /// The ProxyToken to be encoded.
        /// </param>
        /// <param name="signingCertificate">
        /// The X509Certificate which includes the private key to sign the JWT.
        /// </param>
        /// <returns>
        /// The base64 encoded JWT with signature appended.
        /// </returns>
        public static string Encode(ProxyToken payload, X509Certificate2 signingCertificate)
        {
            // header, payload and signature are joint by dot
            // header.payload.signature
            var segments = new List <string>();

            // RS256 is the ONLY algorithm that works
            var header = new JwtHeader {
                typ = Type, alg = SigningAlgorithm
            };

            // x5t is the base64 encoded SHA1 hash of the certificate
            // must use SHA1 hash algorithm here
            header.x5t = Base64Helper.Base64Encode(signingCertificate.GetCertHash());

            // header and payload should be encoded using UTF8
            var base64header  = Base64Helper.Base64Encode(Encoding.UTF8.GetBytes(header.ToString()));
            var base64payload = Base64Helper.Base64Encode(Encoding.UTF8.GetBytes(payload.ToString()));

            segments.Add(base64header);
            segments.Add(base64payload);

            // what we sign is the base64 encoded result
            var stringToSign = string.Join(".", segments.ToArray());

            // sign the data: header and payload
            var signature = RSASigningHelper.SignData(
                // data to be signed should use ASCII encoding
                Encoding.ASCII.GetBytes(stringToSign),
                signingCertificate, HashAlgorithm);

            segments.Add(Base64Helper.Base64Encode(signature));

            return(string.Join(".", segments.ToArray()));
        }
Exemplo n.º 2
0
        public string SignatureEncode(PersonDTO personDTO)
        {
            //medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec

            var header = new JwtHeader()
            {
                type = "JWT", algorithm = "HMACmd5"
            };
            var payload = new JwtPayload()
            {
                Id = personDTO.Id, Email = personDTO.Email, PersonId = personDTO.PersonId
            };

            var data = System.Text.Encoding.UTF8.GetBytes(header.ToString() + payload.ToString());
            //var signature
            var key = System.Text.Encoding.UTF8.GetBytes("key123");

            // Create HMAC-MD5 Algorithm;
            var hmac = new HMACMD5(key);

            // Compute hash.
            var hashBytes = hmac.ComputeHash(data);

            // Convert to HEX string.
            return(System.BitConverter.ToString(hashBytes).Replace("-", "").ToLower());
        }