Пример #1
0
        public Func <byte[], byte[]> GetHashAlgorithm(IRequest req)
        {
            Func <byte[], byte[]> hashAlgorithm = null;

            if (HmacAlgorithms.TryGetValue(HashAlgorithm, out var hmac))
            {
                var authKey = GetAuthKey(req);
                if (authKey == null)
                {
                    throw new NotSupportedException("AuthKey required to use: " + HashAlgorithm);
                }

                hashAlgorithm = data => hmac(authKey, data);
            }

            if (RsaSignAlgorithms.TryGetValue(HashAlgorithm, out var rsa))
            {
                var privateKey = GetPrivateKey(req);
                if (privateKey == null)
                {
                    throw new NotSupportedException("PrivateKey required to use: " + HashAlgorithm);
                }

                hashAlgorithm = data => rsa(privateKey.Value, data);
            }

            if (hashAlgorithm == null)
            {
                throw new NotSupportedException("Invalid algorithm: " + HashAlgorithm);
            }

            return(hashAlgorithm);
        }
Пример #2
0
        public Func <byte[], byte[]> GetHashAlgorithm()
        {
            Func <byte[], byte[]> hashAlgoritm = null;

            Func <byte[], byte[], byte[]> hmac;

            if (HmacAlgorithms.TryGetValue(HashAlgorithm, out hmac))
            {
                if (AuthKey == null)
                {
                    throw new NotSupportedException("AuthKey required to use: " + HashAlgorithm);
                }

                hashAlgoritm = data => hmac(AuthKey, data);
            }

            Func <RSAParameters, byte[], byte[]> rsa;

            if (RsaSignAlgorithms.TryGetValue(HashAlgorithm, out rsa))
            {
                if (PrivateKey == null)
                {
                    throw new NotSupportedException("PrivateKey required to use: " + HashAlgorithm);
                }

                hashAlgoritm = data => rsa(PrivateKey.Value, data);
            }

            if (hashAlgoritm == null)
            {
                throw new NotSupportedException("Invalid algoritm: " + HashAlgorithm);
            }

            return(hashAlgoritm);
        }
Пример #3
0
        /// <summary>
        /// Returns the hash code.
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        public override int GetHashCode()
        {
            var hmac = HmacAlgorithms.Create(HmacAlgorithms.HmacSha1, this.SecretKey);

            try {
                CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);

                byte[] hbytes = ASCIIEncoding.ASCII.GetBytes(this.Handle);

                cs.Write(hbytes, 0, hbytes.Length);
                cs.Close();

                byte[] hash = hmac.Hash;
                hmac.Clear();

                long val = 0;
                for (int i = 0; i < hash.Length; i++)
                {
                    val = val ^ (long)hash[i];
                }

                val = val ^ this.Expires.ToFileTimeUtc();

                return((int)val);
            } finally {
                ((IDisposable)hmac).Dispose();
            }
        }
        protected override string GetSignature(ITamperResistantOAuthMessage message)
        {
            string key = GetConsumerAndTokenSecretString(message);

            using (var hasher = HmacAlgorithms.Create(HmacAlgorithms.HmacSha1, Encoding.ASCII.GetBytes(key))) {
                string baseString = ConstructSignatureBaseString(message, this.Channel.MessageDescriptions.GetAccessor(message));
                byte[] digest     = hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString));
                return(Convert.ToBase64String(digest));
            }
        }
Пример #5
0
        public string CreateJwtBearerToken(IAuthSession session, IEnumerable <string> roles = null, IEnumerable <string> perms = null)
        {
            var jwtPayload = CreateJwtPayload(session, Issuer, ExpireTokensIn, Audience, roles, perms);

            CreatePayloadFilter?.Invoke(jwtPayload, session);

            if (EncryptPayload)
            {
                if (PrivateKey == null || PublicKey == null)
                {
                    throw new NotSupportedException("PrivateKey is required to EncryptPayload");
                }

                return(CreateEncryptedJweToken(jwtPayload, PublicKey.Value));
            }

            var jwtHeader = CreateJwtHeader(HashAlgorithm, GetKeyId());

            CreateHeaderFilter?.Invoke(jwtHeader, session);

            Func <byte[], byte[]> hashAlgoritm = null;

            Func <byte[], byte[], byte[]> hmac;

            if (HmacAlgorithms.TryGetValue(HashAlgorithm, out hmac))
            {
                if (AuthKey == null)
                {
                    throw new NotSupportedException("AuthKey required to use: " + HashAlgorithm);
                }

                hashAlgoritm = data => hmac(AuthKey, data);
            }

            Func <RSAParameters, byte[], byte[]> rsa;

            if (RsaSignAlgorithms.TryGetValue(HashAlgorithm, out rsa))
            {
                if (PrivateKey == null)
                {
                    throw new NotSupportedException("PrivateKey required to use: " + HashAlgorithm);
                }

                hashAlgoritm = data => rsa(PrivateKey.Value, data);
            }

            if (hashAlgoritm == null)
            {
                throw new NotSupportedException("Invalid algoritm: " + HashAlgorithm);
            }

            var bearerToken = CreateJwtBearerToken(jwtHeader, jwtPayload, hashAlgoritm);

            return(bearerToken);
        }
Пример #6
0
        /// <summary>
        /// Gets the return to signature.
        /// </summary>
        /// <param name="returnTo">The return to.</param>
        /// <param name="cryptoKey">The crypto key.</param>
        /// <returns>
        /// The generated signature.
        /// </returns>
        /// <remarks>
        /// Only the parameters in the return_to URI are signed, rather than the base URI
        /// itself, in order that OPs that might change the return_to's implicit port :80 part
        /// or other minor changes do not invalidate the signature.
        /// </remarks>
        private byte[] GetReturnToSignature(Uri returnTo, CryptoKey cryptoKey = null)
        {
            Requires.NotNull(returnTo, "returnTo");

            // Assemble the dictionary to sign, taking care to remove the signature itself
            // in order to accurately reproduce the original signature (which of course didn't include
            // the signature).
            // Also we need to sort the dictionary's keys so that we sign in the same order as we did
            // the last time.
            var returnToParameters = HttpUtility.ParseQueryString(returnTo.Query);

            returnToParameters.Remove(ReturnToSignatureParameterName);
            var sortedReturnToParameters = new SortedDictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (string key in returnToParameters)
            {
                sortedReturnToParameters.Add(key, returnToParameters[key]);
            }

            Logger.Bindings.DebugFormat("ReturnTo signed data: {0}{1}", Environment.NewLine, sortedReturnToParameters.ToStringDeferred());

            // Sign the parameters.
            byte[] bytesToSign = KeyValueFormEncoding.GetBytes(sortedReturnToParameters);
            byte[] signature;
            try {
                if (cryptoKey == null)
                {
                    cryptoKey = this.cryptoKeyStore.GetKey(SecretUri.AbsoluteUri, returnToParameters[ReturnToSignatureHandleParameterName]);
                    ErrorUtilities.VerifyProtocol(
                        cryptoKey != null,
                        MessagingStrings.MissingDecryptionKeyForHandle,
                        SecretUri.AbsoluteUri,
                        returnToParameters[ReturnToSignatureHandleParameterName]);
                }

                using (var signer = HmacAlgorithms.Create(HmacAlgorithms.HmacSha256, cryptoKey.Key)) {
                    signature = signer.ComputeHash(bytesToSign);
                }
            } catch (ProtocolException ex) {
                throw ErrorUtilities.Wrap(ex, OpenIdStrings.MaximumAuthenticationTimeExpired);
            }

            return(signature);
        }
        public string CreateJwtBearerToken(IAuthSession session)
        {
            IEnumerable <string> roles = null, perms = null;
            var authRepo = HostContext.TryResolve <IAuthRepository>() as IManageRoles;

            if (authRepo != null)
            {
                roles = authRepo.GetRoles(session.UserAuthId);
                perms = authRepo.GetPermissions(session.UserAuthId);
            }

            var jwtPayload = CreateJwtPayload(session, Issuer, ExpireTokensIn, Audience, roles, perms);

            if (CreatePayloadFilter != null)
            {
                CreatePayloadFilter(jwtPayload, session);
            }

            if (EncryptPayload)
            {
                if (PrivateKey == null || PublicKey == null)
                {
                    throw new NotSupportedException("PrivateKey is required to EncryptPayload");
                }

                return(CreateEncryptedJweToken(jwtPayload, PublicKey.Value));
            }

            var jwtHeader = CreateJwtHeader(HashAlgorithm, GetKeyId());

            if (CreateHeaderFilter != null)
            {
                CreateHeaderFilter(jwtHeader, session);
            }

            Func <byte[], byte[]> hashAlgoritm = null;

            Func <byte[], byte[], byte[]> hmac;

            if (HmacAlgorithms.TryGetValue(HashAlgorithm, out hmac))
            {
                hashAlgoritm = data => hmac(AuthKey, data);
            }

            Func <RSAParameters, byte[], byte[]> rsa;

            if (RsaSignAlgorithms.TryGetValue(HashAlgorithm, out rsa))
            {
                if (PrivateKey == null)
                {
                    throw new NotSupportedException("PrivateKey required to use: " + HashAlgorithm);
                }

                hashAlgoritm = data => rsa(PrivateKey.Value, data);
            }

            if (hashAlgoritm == null)
            {
                throw new NotSupportedException("Invalid algoritm: " + HashAlgorithm);
            }

            var bearerToken = CreateJwtBearerToken(jwtHeader, jwtPayload, hashAlgoritm);

            return(bearerToken);
        }
Пример #8
0
 /// <summary>
 /// Creates the <see cref="HashAlgorithm"/> using a given shared secret for the mac.
 /// </summary>
 /// <param name="secret">The HMAC secret.</param>
 /// <returns>The algorithm.</returns>
 internal HashAlgorithm CreateHasher(byte[] secret)
 {
     return(HmacAlgorithms.Create(this.HmacAlgorithmName, secret));
 }