Example #1
0
		protected void Initialize(HashAlgorithm hash, byte[] secret, byte[] seed) {
			if (seed == null || secret == null || hash == null)
				throw new ArgumentNullException();
			m_Disposed = false;
			m_HMAC = new HMAC(hash, secret);
			m_Seed = seed;
			m_HashSize = m_HMAC.HashSize / 8;
			Reset();
		}
Example #2
0
        public static void VerifyIncrementalHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm)
        {
            using (referenceAlgorithm)
            using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey))
            {
                referenceAlgorithm.Key = s_hmacKey;

                VerifyIncrementalResult(referenceAlgorithm, incrementalHash);
            }
        }
Example #3
0
        protected void VerifyHmac_KeyAlreadySet(
            HMAC hmac,
            int testCaseId,
            string digest)
        {
            byte[] digestBytes = ByteUtils.HexToByteArray(digest);
            byte[] computedDigest;

            computedDigest = hmac.ComputeHash(_testData[testCaseId]);
            Assert.Equal(digestBytes, computedDigest);
        }
        public Rfc2898DeriveBytesFlexible(byte[] password, byte[] salt, int iterations, HMAC hmac = null)
        {
            if (password == null)
                throw new ArgumentNullException ("password");

            Salt = salt;
            IterationCount = iterations;
            if (_hmac == null) {
                _hmac = new HMACSHA1 ();
            }
            else {
                _hmac = hmac;
            }
            _hmac.Key = password;
        }
        public Rfc2898DeriveBytesFlexible(string password, int saltSize, int iterations, HMAC hmac = null)
        {
            if (password == null)
                throw new ArgumentNullException ("password");
            if (saltSize < 0)
                throw new ArgumentOutOfRangeException ("invalid salt length");

            Salt = KeyBuilder.Key (saltSize);
            IterationCount = iterations;

            if (hmac == null) {
                _hmac = new HMACSHA1 ();
            }
            else {
                _hmac = hmac;
            }
            _hmac.Key = Encoding.UTF8.GetBytes (password);
        }
Example #6
0
 public void SetHash()
 {
     hash = HMAC.GenerateSHA256(GetText(), UniP2PManager.MatchingSettings.MatchingSecretKey);
 }
Example #7
0
        /// <summary>
        /// Releases all resources used by the instance, and flushes any data currently held, into the stream
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                if (m_mode == OperationMode.Encrypt && !m_hasFlushedFinalBlock)
                    FlushFinalBlock();

                if (m_crypto != null)
                    m_crypto.Dispose();
                m_crypto = null;

                if (m_stream != null)
                    m_stream.Dispose();
                m_stream = null;
                m_extensions = null;
                if (m_helper != null)
                    m_helper.Dispose();
                m_helper = null;
                m_hmac = null;
            }
        }
Example #8
0
 public static string ComputeMacWithSpecificAlgorithm(HMAC algorithm, string canonicalizedString)
 {
     byte[] bytes = Encoding.UTF8.GetBytes(canonicalizedString);
     return(Convert.ToBase64String(algorithm.ComputeHash(bytes)));
 }
 public AmazonUriSigner(string appKey, string secretKey)
 {
     _appKey = appKey;
     _secret = Encoding.UTF8.GetBytes(secretKey);
     _hmac   = new HMACSHA256(_secret);
 }
        private string CreateSessionImpl(
            Template template,
            string billingRef,
            string answers,
            string[] markedVariables,
            InterviewFormat interviewFormat,
            OutputFormat outputFormat,
            Dictionary <string, string> settings,
            string theme,
            bool showDownloadLinks,
            bool uploadPackage)
        {
            if (!(template.Location is PackageTemplateLocation))
            {
                throw new Exception("HotDocs Cloud Services requires the use of template packages. Please use a PackageTemplateLocation derivative.");
            }
            PackageTemplateLocation packageTemplateLocation = (PackageTemplateLocation)template.Location;

            if (uploadPackage)
            {
                UploadPackage(packageTemplateLocation.PackageID, billingRef, packageTemplateLocation.GetPackageStream());
            }

            var timestamp = DateTime.UtcNow;

            string hmac = HMAC.CalculateHMAC(
                SigningKey,
                timestamp,
                SubscriberId,
                packageTemplateLocation.PackageID,
                billingRef,
                interviewFormat,
                outputFormat,
                settings);                 // Additional settings = null for this app

            StringBuilder urlBuilder = new StringBuilder(string.Format(
                                                             "{0}/embed/newsession/{1}/{2}?interviewformat={3}&outputformat={4}",
                                                             EndpointAddress, SubscriberId, packageTemplateLocation.PackageID,
                                                             interviewFormat.ToString(), outputFormat.ToString()));

            if (markedVariables != null && markedVariables.Length > 0)
            {
                urlBuilder.AppendFormat("&markedvariables={0}", string.Join(",", markedVariables));
            }

            if (!string.IsNullOrEmpty(theme))
            {
                urlBuilder.AppendFormat("&theme={0}", theme);
            }

            if (!string.IsNullOrEmpty(billingRef))
            {
                urlBuilder.AppendFormat("&billingref={0}", billingRef);
            }

            if (showDownloadLinks)
            {
                urlBuilder.Append("&showdownloadlinks=true");
            }

            if (settings != null)
            {
                foreach (KeyValuePair <string, string> kv in settings)
                {
                    urlBuilder.AppendFormat("&{0}={1}", kv.Key, kv.Value ?? "");
                }
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());

            request.Method               = "POST";
            request.ContentType          = "text/xml";
            request.Headers["x-hd-date"] = timestamp.ToString("r");
            request.Headers[HttpRequestHeader.Authorization] = hmac;
            request.ContentLength = answers != null ? answers.Length : 0;

            if (!string.IsNullOrEmpty(ProxyServerAddress))
            {
                request.Proxy = new WebProxy(ProxyServerAddress);
            }
            else
            {
                request.Proxy = null;
            }

            Stream stream = request.GetRequestStream();

            if (answers != null)
            {
                byte[] data = Encoding.UTF8.GetBytes(answers);
                stream.Write(data, 0, data.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader    reader   = new StreamReader(response.GetResponseStream());

            return(reader.ReadLine());
        }
Example #11
0
            /// <summary>
            /// Initialize the setup
            /// </summary>
            /// <param name="mode">The mode to prepare for</param>
            /// <param name="password">The password used to encrypt or decrypt</param>
            /// <param name="iv">The IV used, set to null if encrypting</param>
            public SetupHelper(OperationMode mode, string password, byte[] iv)
            {
                m_crypt = SymmetricAlgorithm.Create(CRYPT_ALGORITHM);

                //Not sure how to insert this with the CRYPT_ALGORITHM string
                m_crypt.Padding = PaddingMode.None;
                m_crypt.Mode = CipherMode.CBC;

                m_hash = HashAlgorithm.Create(HASH_ALGORITHM);
                m_rand = RandomNumberGenerator.Create(/*RAND_ALGORITHM*/);
                m_hmac = HMAC.Create(HMAC_ALGORITHM);

                if (mode == OperationMode.Encrypt)
                {
                    m_iv1 = GenerateIv1();
                    m_aesKey1 = GenerateAESKey1(EncodePassword(password));
                    m_iv2 = GenerateIv2();
                    m_aesKey2 = GenerateAESKey2();
                }
                else
                {
                    m_iv1 = iv;
                    m_aesKey1 = GenerateAESKey1(EncodePassword(password));
                }
            }
Example #12
0
        protected void EnableEncryption(Stream inputStream, SymmetricCryptoKey encryptionKey, SymmetricCryptoKey decryptionKey, HMAC authHMACEncrypt, HMAC authHMACDecrypt)
        {
            //create reader and writer objects
            _encryptionKey   = encryptionKey;
            _cryptoEncryptor = encryptionKey.GetEncryptor();
            _cryptoDecryptor = decryptionKey.GetDecryptor();

            //init variables
            _baseStream         = inputStream;
            _blockSizeBytes     = encryptionKey.BlockSize / 8;
            _writeBufferPadding = new byte[_blockSizeBytes];
            _authHMACEncrypt    = authHMACEncrypt;
            _authHMACDecrypt    = authHMACDecrypt;
            _authHMACSize       = authHMACEncrypt.HashSize / 8;

            _bytesSent   = 0;
            _connectedOn = DateTime.UtcNow;

            if (_reNegotiationTimer == null)
            {
                if ((_reNegotiateOnBytesSent > 0) || (_reNegotiateAfterSeconds > 0))
                {
                    _reNegotiationTimer = new Timer(ReNegotiationTimerCallback, null, _reNegotiationTimerInterval, Timeout.Infinite);
                }
            }
        }
Example #13
0
        public static void VerifyTrivialHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm)
        {
            using (referenceAlgorithm)
            using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey))
            {
                referenceAlgorithm.Key = s_hmacKey;

                byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>());
                byte[] incrementalResult = incrementalHash.GetHashAndReset();

                Assert.Equal(referenceHash, incrementalResult);
            }
        }
Example #14
0
		public void VerifyHMAC(MessageDigest digest, string[] results)
		{
			byte[] hash = HMAC.Digest(digest, key, small_data);
			string str = BitConverter.ToString(hash);
			if (str != results[0])
			{
				Console.WriteLine("{0} - Failed to calculate hash on {1}", digest.Name, small_data);
				Console.WriteLine("got {0} instead of {1}", str, results[0]);
			}
			else
			{
				Console.WriteLine("{0} - Test 1 passed.", digest.Name);
			}
			// Compute the large hash
			using (HMAC hmac = new HMAC())
			{
				byte[] buf = Encoding.ASCII.GetBytes(new string('a', 1000));
				hmac.Init(key, digest);
				for (int i = 0; i < 1000; i++)
				{
					hmac.Update(buf);
				}
				hash = hmac.DigestFinal();
				// Check for error
				str = BitConverter.ToString(hash);
				if (str != results[1])
				{
					Console.WriteLine("{0} - Failed to calculate hash on a*1000", digest.Name);
					Console.WriteLine("got {0} instead of {1}", str, results[1]);
				}
				else
				{
					Console.WriteLine("{0} - Test 2 passed.", digest.Name);
				}
			}
		}
 public Rfc2898DeriveBytesFlexible(string password, int saltSize, HMAC hmac = null)
     : this(password, saltSize, defaultIterations, null)
 {
 }
Example #16
0
            /// <summary>
            /// Disposes all members
            /// </summary>
            public void Dispose()
            {
                if (m_crypt != null)
                {
                    if (m_aesKey1 != null)
                        Array.Clear(m_aesKey1, 0, m_aesKey1.Length);
                    if (m_iv1 != null)
                        Array.Clear(m_iv1, 0, m_iv1.Length);
                    if (m_aesKey2 != null)
                        Array.Clear(m_aesKey2, 0, m_aesKey2.Length);
                    if (m_iv2 != null)
                        Array.Clear(m_iv2, 0, m_iv2.Length);

                    m_aesKey1 = null;
                    m_iv1 = null;
                    m_aesKey2 = null;
                    m_iv2 = null;

                    m_hash = null;
                    m_hmac = null;
                    m_rand = null;
                    m_crypt = null;
                }
            }
Example #17
0
 public void CheckB(string testName, HMAC algo, byte[] data, byte[] result)
 {
     byte[] hmac = algo.ComputeHash(data, 0, data.Length);
     Compare(result, hmac, testName + "b1");
     Compare(result, algo.Hash, testName + "b2");
 }
Example #18
0
        /// <summary>
        /// Constructs a new AESCrypt instance, operating on the supplied stream
        /// </summary>
        /// <param name="password">The password used for encryption or decryption</param>
        /// <param name="stream">The stream to operate on, must be writeable for encryption, and readable for decryption</param>
        /// <param name="mode">The mode of operation, either OperationMode.Encrypt or OperationMode.Decrypt</param>
        public SharpAESCrypt(string password, Stream stream, OperationMode mode)
        {
            //Basic input checks
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (password == null)
                throw new ArgumentNullException("password");
            if (mode != OperationMode.Encrypt && mode != OperationMode.Decrypt)
                throw new ArgumentException(Strings.InvalidOperationMode, "mode");
            if (mode == OperationMode.Encrypt && !stream.CanWrite)
                throw new ArgumentException(Strings.StreamMustBeWriteAble, "stream");
            if (mode == OperationMode.Decrypt && !stream.CanRead)
                throw new ArgumentException(Strings.StreamMustBeReadAble, "stream");

            m_mode = mode;
            m_stream = stream;
            m_extensions = new List<KeyValuePair<string, byte[]>>();

            if (mode == OperationMode.Encrypt)
            {
                this.Version = DefaultFileVersion;

                m_helper = new SetupHelper(mode, password, null);

                //Setup default extensions
                if (Extension_InsertCreateByIdentifier)
                    m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED_BY", System.Text.Encoding.UTF8.GetBytes(Extension_CreatedByIdentifier)));

                if (Extension_InsertTimeStamp)
                {
                    m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED_DATE", System.Text.Encoding.UTF8.GetBytes(DateTime.UtcNow.ToString("yyyy-MM-dd"))));
                    m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED_TIME", System.Text.Encoding.UTF8.GetBytes(DateTime.UtcNow.ToString("hh-mm-ss"))));
                }

                if (Extension_InsertPlaceholder)
                    m_extensions.Add(new KeyValuePair<string, byte[]>(String.Empty, new byte[127])); //Suggested extension space

                //We defer creation of the cryptostream until it is needed,
                // so the caller can change version, extensions, etc.
                // before we write the header
                m_crypto = null;
            }
            else
            {
                //Read and validate
                ReadEncryptionHeader(password);

                m_hmac = m_helper.GetHMAC();

                //Insert the HMAC before the decryption so the HMAC is calculated for the ciphertext
                m_crypto = new CryptoStream(new CryptoStream(new StreamHider(m_stream, m_version == 0 ? HASH_SIZE : (HASH_SIZE + 1)), m_hmac, CryptoStreamMode.Read), m_helper.CreateCryptoStream(m_mode), CryptoStreamMode.Read);
            }
        }
Example #19
0
        public void InitalizeCipherSuite()
        {
            byte[] clientMAC;
            byte[] serverMAC;
            byte[] clientEncryptionKey;
            byte[] serverEncryptionKey;

            GenerateKeys(out clientMAC, out serverMAC, out clientEncryptionKey, out serverEncryptionKey);

            if (SecurityParameters.BulkCipherAlgorithm == BulkCipherAlgorithm.AES)
            {
                m_decryptionBulkAlgorithm           = new AesCryptoServiceProvider();
                m_decryptionBulkAlgorithm.Padding   = PaddingMode.None;
                m_decryptionBulkAlgorithm.KeySize   = SecurityParameters.EncKeyLength * 8;
                m_decryptionBulkAlgorithm.BlockSize = SecurityParameters.BlockLength * 8;

                m_encryptionBulkAlgorithm           = new AesCryptoServiceProvider();
                m_encryptionBulkAlgorithm.Padding   = PaddingMode.None;
                m_encryptionBulkAlgorithm.KeySize   = SecurityParameters.EncKeyLength * 8;
                m_encryptionBulkAlgorithm.BlockSize = SecurityParameters.BlockLength * 8;

                if (SecurityParameters.Entity == ConnectionEnd.Client)
                {
                    m_encryptionBulkAlgorithm.Key = clientEncryptionKey;
                    m_decryptionBulkAlgorithm.Key = serverEncryptionKey;
                }
                else
                {
                    m_decryptionBulkAlgorithm.Key = clientEncryptionKey;
                    m_encryptionBulkAlgorithm.Key = serverEncryptionKey;
                }
            }
            else
            {
                m_decryptionBulkAlgorithm = m_encryptionBulkAlgorithm = null;
            }

            if (SecurityParameters.MACAlgorithm == MACAlgorithm.HMACSha1)
            {
                if (SecurityParameters.Entity == ConnectionEnd.Client)
                {
                    m_encryptionHMAC = new HMACSHA1(clientMAC);
                    m_decryptionHMAC = new HMACSHA1(serverMAC);
                }
                else
                {
                    m_encryptionHMAC = new HMACSHA1(serverMAC);
                    m_decryptionHMAC = new HMACSHA1(clientMAC);
                }
            }
            else if (SecurityParameters.MACAlgorithm == MACAlgorithm.HMACSha256)
            {
                if (SecurityParameters.Entity == ConnectionEnd.Client)
                {
                    m_encryptionHMAC = new HMACSHA256(clientMAC);
                    m_decryptionHMAC = new HMACSHA256(serverMAC);
                }
                else
                {
                    m_encryptionHMAC = new HMACSHA256(serverMAC);
                    m_decryptionHMAC = new HMACSHA256(clientMAC);
                }
            }
            else
            {
                m_encryptionHMAC = m_decryptionHMAC = null;
            }
        }
Example #20
0
 public static string CreateHmac(string input)
 {
     using var hashAlgorithm = HMAC.Create();
     return(CreateHash(Encoding.UTF8.GetBytes(input), hashAlgorithm));
 }
Example #21
0
        public string Setup(SetupContext context)
        {
            string executionId;

            Logger.Information("Running setup for tenant '{0}'.", _shellSettings.Name);

            // The vanilla Orchard distibution has the following features enabled.
            string[] hardcoded =
            {
                // Framework
                "Orchard.Framework",
                // Core
                "Common",           "Containers",             "Contents",       "Dashboard",     "Feeds",         "Navigation",      "Scheduling", "Settings", "Shapes", "Title",
                // Modules
                "Orchard.Pages",    "Orchard.ContentPicker",  "Orchard.Themes", "Orchard.Users", "Orchard.Roles", "Orchard.Modules",
                "PackagingServices","Orchard.Packaging",      "Gallery",        "Orchard.Recipes"
            };

            context.EnabledFeatures = hardcoded.Union(context.EnabledFeatures ?? Enumerable.Empty <string>()).Distinct().ToList();

            var shellSettings = new ShellSettings(_shellSettings);

            if (String.IsNullOrEmpty(shellSettings.DataProvider))
            {
                shellSettings.DataProvider         = context.DatabaseProvider;
                shellSettings.DataConnectionString = context.DatabaseConnectionString;
                shellSettings.DataTablePrefix      = context.DatabaseTablePrefix;
            }

            shellSettings.EncryptionAlgorithm = "AES";
            shellSettings.EncryptionKey       = SymmetricAlgorithm.Create(shellSettings.EncryptionAlgorithm).Key.ToHexString();
            shellSettings.HashAlgorithm       = "HMACSHA256";
            shellSettings.HashKey             = HMAC.Create(shellSettings.HashAlgorithm).Key.ToHexString();

            var shellDescriptor = new ShellDescriptor {
                Features = context.EnabledFeatures.Select(name => new ShellFeature {
                    Name = name
                })
            };

            var shellBlueprint = _compositionStrategy.Compose(shellSettings, shellDescriptor);

            // Initialize database explicitly, and store shell descriptor.
            using (var bootstrapLifetimeScope = _shellContainerFactory.CreateContainer(shellSettings, shellBlueprint)) {
                using (var environment = bootstrapLifetimeScope.CreateWorkContextScope()) {
                    // Workaround to avoid a Transaction issue with PostgreSQL.
                    environment.Resolve <ITransactionManager>().RequireNew();

                    var schemaBuilder = new SchemaBuilder(environment.Resolve <IDataMigrationInterpreter>());

                    schemaBuilder.CreateTable("Orchard_Framework_DataMigrationRecord", table => table
                                              .Column <int>("Id", column => column.PrimaryKey().Identity())
                                              .Column <string>("DataMigrationClass")
                                              .Column <int>("Version"));

                    schemaBuilder.AlterTable("Orchard_Framework_DataMigrationRecord",
                                             table => table.AddUniqueConstraint("UC_DMR_DataMigrationClass_Version", "DataMigrationClass", "Version"));

                    var dataMigrationManager = environment.Resolve <IDataMigrationManager>();
                    dataMigrationManager.Update("Settings");

                    foreach (var feature in context.EnabledFeatures)
                    {
                        dataMigrationManager.Update(feature);
                    }

                    var descriptorManager = environment.Resolve <IShellDescriptorManager>();
                    descriptorManager.UpdateShellDescriptor(0, shellDescriptor.Features, shellDescriptor.Parameters);
                }
            }

            // In effect "pump messages" see PostMessage circa 1980.
            while (_processingEngine.AreTasksPending())
            {
                _processingEngine.ExecuteNextTask();
            }

            // Create a standalone environment.
            // Must mark state as Running - otherwise standalone environment is created "for setup".
            shellSettings.State = TenantState.Running;
            using (var environment = _orchardHost.CreateStandaloneEnvironment(shellSettings)) {
                try {
                    executionId = CreateTenantData(context, environment);
                }
                catch {
                    environment.Resolve <ITransactionManager>().Cancel();
                    throw;
                }
            }

            _shellSettingsManager.SaveSettings(shellSettings);

            return(executionId);
        }
Example #22
0
        /// <summary>
        /// Writes the header to the output stream and sets up the crypto stream
        /// </summary>
        private void WriteEncryptionHeader()
        {
            m_stream.Write(MAGIC_HEADER, 0, MAGIC_HEADER.Length);
            m_stream.WriteByte(m_version);
            m_stream.WriteByte(0); //Reserved or length % 16
            if (m_version >= 2)
            {
                foreach (KeyValuePair<string, byte[]> ext in m_extensions)
                    WriteExtension(ext.Key, ext.Value);
                m_stream.Write(new byte[] { 0, 0 }, 0, 2); //No more extensions
            }

            m_stream.Write(m_helper.IV1, 0, m_helper.IV1.Length);

            if (m_version == 0)
                m_helper.SetBulkKeyToKey1();
            else
            {
                //Generate and encrypt bulk key and its HMAC
                byte[] tmpKey = m_helper.EncryptAESKey2();
                m_stream.Write(tmpKey, 0, tmpKey.Length);
                tmpKey = m_helper.CalculateKeyHmac();
                m_stream.Write(tmpKey, 0, tmpKey.Length);
            }

            m_hmac = m_helper.GetHMAC();

            //Insert the HMAC before the stream to calculate the HMAC for the ciphertext
            m_crypto = new CryptoStream(new CryptoStream(new StreamHider(m_stream, 0), m_hmac, CryptoStreamMode.Write), m_helper.CreateCryptoStream(m_mode), CryptoStreamMode.Write);
            m_hasWrittenHeader = true;
        }
        public void ComputeSignature(KeyedHashAlgorithm macAlg)
        {
            int hashSize;

            if (macAlg == null)
            {
                throw new ArgumentNullException("macAlg");
            }
            HMAC hash = macAlg as HMAC;

            if (hash == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch"));
            }
            if (this.m_signature.SignedInfo.SignatureLength == null)
            {
                hashSize = hash.HashSize;
            }
            else
            {
                hashSize = Convert.ToInt32(this.m_signature.SignedInfo.SignatureLength, (IFormatProvider)null);
            }
            if ((hashSize < 0) || (hashSize > hash.HashSize))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength"));
            }
            if ((hashSize % 8) != 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2"));
            }
            this.BuildDigestedReferences();
            switch (hash.HashName)
            {
            case "SHA1":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
                break;

            case "SHA256":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
                break;

            case "SHA384":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
                break;

            case "SHA512":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
                break;

            case "MD5":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-md5";
                break;

            case "RIPEMD160":
                this.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160";
                break;

            default:
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch"));
            }
            byte[] src = this.GetC14NDigest(hash);
            SignedXmlDebugLog.LogSigning(this, hash);
            this.m_signature.SignatureValue = new byte[hashSize / 8];
            Buffer.BlockCopy(src, 0, this.m_signature.SignatureValue, 0, hashSize / 8);
        }
Example #24
0
        ///  <summary>
        ///
        ///  </summary>
        ///  <param name="cryptographicRepresentative"></param>
        /// <param name="key"></param>
        /// TODO decompose
        public void DecryptDataWithHeader([NotNull] SymmetricCryptographicRepresentative cryptographicRepresentative, byte[] key)
        {
            ((IProgress <int>) this._progress)?.Report(0);

            ((IProgress <int>) this._progress)?.Report(10);

            HMAC hmacAlg = null;

            if (cryptographicRepresentative.HmacRepresentative != null)
            {
                hmacAlg = (HMAC)Activator.CreateInstance(cryptographicRepresentative.HmacRepresentative.Value.HashAlgorithm);
            }

            var @params = new object[]
            {
                1024 * 1024 * 8, new AesCng
                {
                    BlockSize = (int)cryptographicRepresentative.TransformationModeInfo.BlockSize,
                    KeySize   = (int)cryptographicRepresentative.TransformationModeInfo.KeySize,
                    Mode      = cryptographicRepresentative.TransformationModeInfo.CipherMode,
                    Padding   = cryptographicRepresentative.TransformationModeInfo.PaddingMode
                }
            };


            var decryptor = (SymmetricCryptoManager)Activator.CreateInstance(cryptographicRepresentative.TransformationModeInfo.CryptoManager, @params);

            FileStatics.RemovePrependData(this._filePath, App.This.HeaderLessTempFile, cryptographicRepresentative.HeaderLength);

            ((IProgress <int>) this._progress)?.Report(20);

            GCHandle keyHandle = GCHandle.Alloc(key, GCHandleType.Pinned);

            var isVerified = false;

            if (cryptographicRepresentative.HmacRepresentative != null)
            {
                // Check if the file and key make the same HMAC
                isVerified = MessageAuthenticator.VerifyHmac(App.This.HeaderLessTempFile, key,
                                                             cryptographicRepresentative.HmacRepresentative.Value.HashBytes, hmacAlg);
            }

            ((IProgress <int>) this._progress)?.Report(35);

            // If that didn't succeed, the file has been tampered with
            if (cryptographicRepresentative.HmacRepresentative != null && !isVerified)
            {
                throw new UnverifiableDataException("File could not be verified - may have been tampered, or the password is incorrect");
            }

            // Try decrypting the remaining data
            try
            {
                decryptor.DecryptFileBytes(App.This.HeaderLessTempFile, App.This.DataTempFile, key, cryptographicRepresentative.TransformationModeInfo.InitializationVector);

                ((IProgress <int>) this._progress)?.Report(75);

                // Move the file to the original file location
                File.Copy(App.This.DataTempFile, this._filePath, true);

                ((IProgress <int>) this._progress)?.Report(100);
            }
            finally
            {
                // Delete the key from memory for security
                Externals.ZeroMemory(keyHandle.AddrOfPinnedObject(), key.Length);
                keyHandle.Free();
            }
        }
Example #25
0
 public static string CreateHmac(Stream input)
 {
     using var hashAlgorithm = HMAC.Create();
     return(CreateHash(input, hashAlgorithm));
 }
Example #26
0
        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="request"></param>
        /// <param name="password"></param>
        /// <param name="desiredKeyDerivationMilliseconds"></param>
        public void EncryptDataWithHeader(RequestStateRecord request, SecureString password,
                                          int desiredKeyDerivationMilliseconds)
        {
            if (request.Contract.InstanceKeyContract == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            ((IProgress <int>) this._progress)?.Report(0);
            password.MakeReadOnly();


            var salt = new byte[request.Contract.InstanceKeyContract.Value.SaltLengthBytes];

            var iv  = new byte[request.Contract.TransformationContract.InitializationVectorSizeBytes];
            var rng = new RNGCryptoServiceProvider();

            try
            {
                rng.GetBytes(salt);
                rng.GetBytes(iv);
            }
            catch (CryptographicException exception)
            {
                FileStatics.WriteToLogFile(exception);
                MessageBox.Show(
                    "There was an error generating secure random numbers. Please try again - check log file for more details");
            }

            var performanceDerivative =
                new PerformanceDerivative(request.Contract.InstanceKeyContract.Value.PerformanceDerivative);


            ((IProgress <int>) this._progress)?.Report(25);

            // Get the password

            if (password.Length == 0)
            {
                MessageBox.Show("You must enter a password");

                ((IProgress <int>) this._progress)?.Report(0);
                return;
            }
#if TRACE
            if (password.Length < App.This.CurrentSettings.MinPasswordLength)
            {
                MessageBox.Show("Password too short");
                ((IProgress <int>)_progress)?.Report(0);
                return;
            }
#endif
            GCHandle byteHandle = SecureStringConverter.SecureStringToKeyDerive(password, salt,
                                                                                performanceDerivative, request.Contract.InstanceKeyContract.Value.KeyAlgorithm, out KeyDerive keyDevice);

            ((IProgress <int>) this._progress)?.Report(35);

            HMAC hmacAlg = null;

            if (request.Contract.HmacContract != null)
            {
                // Create the algorithm using reflection
                hmacAlg = (HMAC)Activator.CreateInstance(request.Contract.HmacContract.Value.HashAlgorithm);
            }

            Aes aesAlgorithm = new AesCng
            {
                BlockSize = (int)request.Contract.TransformationContract.BlockSize,
                KeySize   = (int)request.Contract.TransformationContract.KeySize,
                Mode      = request.Contract.TransformationContract.CipherMode,
                Padding   = request.Contract.TransformationContract.PaddingMode
            };

            var @params = new object[] { 1024 * 1024 * 1024, aesAlgorithm };

            var encryptor =
                (SymmetricCryptoManager)Activator.CreateInstance(request.Contract.TransformationContract.CryptoManager,
                                                                 @params);


            byte[] key = keyDevice.GetBytes((int)request.Contract.TransformationContract.KeySize / 8);

            Externals.ZeroMemory(byteHandle.AddrOfPinnedObject(), ((byte[])byteHandle.Target).Length);

            byteHandle.Free();

            // Create a handle to the key to allow control of it
            GCHandle keyHandle = GCHandle.Alloc(key, GCHandleType.Pinned);

            // Encrypt the data to a temporary file
            encryptor.EncryptFileBytes(this._filePath, App.This.DataTempFile, key, iv);

            ((IProgress <int>) this._progress)?.Report(90);


            byte[] hash = null;

            if (request.Contract.HmacContract != null)
            {
                // Create the signature derived from the encrypted data and key
                byte[] signature = MessageAuthenticator.CreateHmac(App.This.DataTempFile, key, hmacAlg);

                // Set the signature correctly in the CryptographicRepresentative object
                hash = signature;
            }

            HmacRepresentative?hmac = request.Contract.HmacContract.HasValue
                                        ? new HmacRepresentative(request.Contract.HmacContract.Value.HashAlgorithm, hash)
                                        : (HmacRepresentative?)null;

            KeyRepresentative?keyRepresentative = new KeyRepresentative
                                                  (
                request.Contract.InstanceKeyContract.Value.KeyAlgorithm,
                request.Contract.InstanceKeyContract.Value.PerformanceDerivative,
                salt
                                                  );

            // Delete the key from memory for security
            Externals.ZeroMemory(keyHandle.AddrOfPinnedObject(), key.Length);
            keyHandle.Free();

            var cryptographicInfo = new SymmetricCryptographicRepresentative
                                    (
                new TransformationRepresentative
                (
                    request.Contract.TransformationContract.CryptoManager,
                    iv,
                    request.Contract.TransformationContract.CipherMode,
                    request.Contract.TransformationContract.PaddingMode,
                    request.Contract.TransformationContract.KeySize,
                    request.Contract.TransformationContract.BlockSize
                ),
                keyRepresentative,
                hmac
                                    );

            // Write the CryptographicRepresentative object to a file
            cryptographicInfo.WriteHeaderToFile(this._filePath);

            ((IProgress <int>) this._progress)?.Report(98);
            FileStatics.AppendToFile(this._filePath, App.This.DataTempFile);

            ((IProgress <int>) this._progress)?.Report(100);
        }
Example #27
0
        public string Setup(SetupContext context)
        {
            string executionId;

            // The vanilla Orchard distibution has the following features enabled.
            string[] hardcoded =
            {
                // Framework
                "Orchard.Framework",
                // Core
                "Common",           "Containers",             "Contents",       "Dashboard",     "Feeds",         "Navigation",      "Reports", "Scheduling", "Settings", "Shapes", "Title",
                // Modules
                "Orchard.Pages",    "Orchard.ContentPicker",  "Orchard.Themes", "Orchard.Users", "Orchard.Roles", "Orchard.Modules",
                "PackagingServices","Orchard.Packaging",      "Gallery",        "Orchard.Recipes"
            };

            context.EnabledFeatures = hardcoded.Union(context.EnabledFeatures ?? Enumerable.Empty <string>()).Distinct().ToList();

            var shellSettings = new ShellSettings(_shellSettings);

            if (string.IsNullOrEmpty(shellSettings.DataProvider))
            {
                shellSettings.DataProvider         = context.DatabaseProvider;
                shellSettings.DataConnectionString = context.DatabaseConnectionString;
                shellSettings.DataTablePrefix      = context.DatabaseTablePrefix;
            }

            #region Encryption Settings

            shellSettings.EncryptionAlgorithm = "AES";
            // randomly generated key
            shellSettings.EncryptionKey = SymmetricAlgorithm.Create(shellSettings.EncryptionAlgorithm).Key.ToHexString();

            shellSettings.HashAlgorithm = "HMACSHA256";
            // randomly generated key
            shellSettings.HashKey = HMAC.Create(shellSettings.HashAlgorithm).Key.ToHexString();

            #endregion

            var shellDescriptor = new ShellDescriptor {
                Features = context.EnabledFeatures.Select(name => new ShellFeature {
                    Name = name
                })
            };

            var shellBlueprint = _compositionStrategy.Compose(shellSettings, shellDescriptor);

            // initialize database explicitly, and store shell descriptor
            using (var bootstrapLifetimeScope = _shellContainerFactory.CreateContainer(shellSettings, shellBlueprint)) {
                using (var environment = bootstrapLifetimeScope.CreateWorkContextScope()) {
                    // check if the database is already created (in case an exception occured in the second phase)
                    var schemaBuilder = new SchemaBuilder(environment.Resolve <IDataMigrationInterpreter>());
                    try {
                        var tablePrefix = String.IsNullOrEmpty(shellSettings.DataTablePrefix) ? "" : shellSettings.DataTablePrefix + "_";
                        schemaBuilder.ExecuteSql("SELECT * FROM " + tablePrefix + "Settings_ShellDescriptorRecord");
                    }
                    catch {
                        var reportsCoordinator = environment.Resolve <IReportsCoordinator>();

                        reportsCoordinator.Register("Data Migration", "Setup", "Orchard installation");

                        schemaBuilder.CreateTable("Orchard_Framework_DataMigrationRecord",
                                                  table => table
                                                  .Column <int>("Id", column => column.PrimaryKey().Identity())
                                                  .Column <string>("DataMigrationClass")
                                                  .Column <int>("Version"));

                        var dataMigrationManager = environment.Resolve <IDataMigrationManager>();
                        dataMigrationManager.Update("Settings");

                        foreach (var feature in context.EnabledFeatures)
                        {
                            dataMigrationManager.Update(feature);
                        }

                        environment.Resolve <IShellDescriptorManager>().UpdateShellDescriptor(
                            0,
                            shellDescriptor.Features,
                            shellDescriptor.Parameters);
                    }
                }
            }



            // in effect "pump messages" see PostMessage circa 1980
            while (_processingEngine.AreTasksPending())
            {
                _processingEngine.ExecuteNextTask();
            }

            // creating a standalone environment.
            // in theory this environment can be used to resolve any normal components by interface, and those
            // components will exist entirely in isolation - no crossover between the safemode container currently in effect

            // must mark state as Running - otherwise standalone enviro is created "for setup"
            shellSettings.State = TenantState.Running;
            using (var environment = _orchardHost.CreateStandaloneEnvironment(shellSettings)) {
                try {
                    executionId = CreateTenantData(context, environment);
                }
                catch {
                    environment.Resolve <ITransactionManager>().Cancel();
                    throw;
                }
            }

            _shellSettingsManager.SaveSettings(shellSettings);

            return(executionId);
        }
Example #28
0
        public void ComputeSignature(KeyedHashAlgorithm macAlg)
        {
            if (macAlg == null)
            {
                throw new ArgumentNullException(nameof(macAlg));
            }

            HMAC hash = macAlg as HMAC;

            if (hash == null)
            {
                throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch);
            }

            int signatureLength;

            if (m_signature.SignedInfo.SignatureLength == null)
            {
                signatureLength = hash.HashSize;
            }
            else
            {
                signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null);
            }
            // signatureLength should be less than hash size
            if (signatureLength < 0 || signatureLength > hash.HashSize)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength);
            }
            if (signatureLength % 8 != 0)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2);
            }

            BuildDigestedReferences();
            switch (hash.HashName)
            {
            case "SHA1":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigHMACSHA1Url;
                break;

            case "SHA256":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA256Url;
                break;

            case "SHA384":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA384Url;
                break;

            case "SHA512":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA512Url;
                break;

            case "MD5":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACMD5Url;
                break;

            case "RIPEMD160":
                SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACRIPEMD160Url;
                break;

            default:
                throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch);
            }

            byte[] hashValue = GetC14NDigest(hash);

            SignedXmlDebugLog.LogSigning(this, hash);
            m_signature.SignatureValue = new byte[signatureLength / 8];
            Buffer.BlockCopy(hashValue, 0, m_signature.SignatureValue, 0, signatureLength / 8);
        }
Example #29
0
        private void CompareBlocks(HmacAlg Algorithm)
        {
            if (Algorithm == HmacAlg.Sha256Hmac)
            {
                byte[] hashKey = new byte[32];
                byte[] buffer = new byte[640];
                byte[] hash1 = new byte[32];
                byte[] hash2 = new byte[32];

                using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                {
                    rng.GetBytes(hashKey);
                    rng.GetBytes(buffer);
                }

                using (System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(hashKey))
                    hash1 = hmac.ComputeHash(buffer);

                // test 1: HMAC interface
                HMAC hmac1 = new HMAC(new SHA256Digest());
                hmac1.Init(hashKey);
                hmac1.BlockUpdate(buffer, 0, buffer.Length);
                hmac1.DoFinal(hash2, 0);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac is not equal!");

                // test 2: class with dofinal
                using (SHA256HMAC hmac = new SHA256HMAC())
                {
                    hmac.Init(hashKey);
                    hmac.BlockUpdate(buffer, 0, buffer.Length);
                    hmac.DoFinal(hash2, 0);
                }

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 3: class with computemac
                using (SHA256HMAC hmac = new SHA256HMAC(hashKey))
                    hash2 = hmac.ComputeMac(buffer);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac2 is not equal!");
            }
            else
            {
                // SHA512 //
                byte[] hash1 = new byte[64];
                byte[] hash2 = new byte[64];
                byte[] hashKey = new byte[64];
                byte[] buffer = new byte[128];

                using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                {
                    rng.GetBytes(hashKey);
                    rng.GetBytes(buffer);
                }

                using (System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(hashKey))
                    hash1 = hmac.ComputeHash(buffer);

                // test 1: HMAC interface
                HMAC hmac1 = new HMAC(new SHA512Digest());
                hmac1.Init(hashKey);
                hmac1.BlockUpdate(buffer, 0, buffer.Length);
                hmac1.DoFinal(hash2, 0);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 2: class with dofinal
                using (SHA512HMAC hmac = new SHA512HMAC())
                {
                    hmac.Init(hashKey);
                    hmac.BlockUpdate(buffer, 0, buffer.Length);
                    hmac.DoFinal(hash2, 0);
                }

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 3: class with computemac
                using (SHA512HMAC hmac = new SHA512HMAC(hashKey))
                    hash2 = hmac.ComputeMac(buffer);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac2 is not equal!");
            }
        }
 static HMAC CreateHMAC(string name)
 {
     return(HMAC.Create(name));
 }
Example #31
0
        public static string ComputeMacWithSpecificAlgorithm(HMAC algorithm, RequestContext requestContext, NephosUriComponents uriComponents)
        {
            string str = MessageCanonicalizer.CanonicalizeHttpRequest(requestContext, uriComponents, false);

            return(MessageHashFunctions.ComputeMacWithSpecificAlgorithm(algorithm, str));
        }
        /// <inheritdoc cref="IEncryptedMessageReader.ReadFrom"/>
        public IEncryptedMessage ReadFrom(ref SpanBufferReader bufferReader, byte[] key, HMAC hmac, byte?packetProperty)
        {
            var sequenceId      = bufferReader.ReadUInt32();
            var iv              = bufferReader.ReadBytes(16).ToArray();
            var decryptedBuffer = bufferReader.RemainingData.ToArray();

            using (var cryptoTransform = _aesCryptoServiceProvider.CreateDecryptor(key, iv))
            {
                var bytesWritten = 0;
                for (var i = decryptedBuffer.Length; i >= cryptoTransform.InputBlockSize; i -= bytesWritten)
                {
                    var inputCount = cryptoTransform.CanTransformMultipleBlocks
                        ? (i / cryptoTransform.InputBlockSize * cryptoTransform.InputBlockSize)
                        : cryptoTransform.InputBlockSize;
                    bytesWritten = cryptoTransform.TransformBlock(
                        decryptedBuffer, bytesWritten, inputCount,
                        decryptedBuffer, bytesWritten
                        );
                }
            }

            var paddingByteCount    = decryptedBuffer[decryptedBuffer.Length - 1] + 1;
            var hmacStart           = decryptedBuffer.Length - paddingByteCount - 10;
            var decryptedBufferSpan = decryptedBuffer.AsSpan();
            var hash             = decryptedBufferSpan.Slice(hmacStart, 10);
            var hashBufferWriter = new SpanBufferWriter(stackalloc byte[decryptedBuffer.Length + 4]);

            hashBufferWriter.WriteBytes(decryptedBufferSpan.Slice(0, hmacStart));
            hashBufferWriter.WriteUInt32(sequenceId);
            Span <byte> computedHash = stackalloc byte[32];

            if (!hmac.TryComputeHash(hashBufferWriter.Data, computedHash, out _))
            {
                throw new Exception("Failed to compute message hash.");
            }
            if (!hash.SequenceEqual(computedHash.Slice(0, 10)))
            {
                throw new Exception("Message hash does not match the computed hash.");
            }

            bufferReader = new SpanBufferReader(decryptedBuffer);
            if (_messageReader.ReadFrom(ref bufferReader, packetProperty) is not IEncryptedMessage message)
            {
                throw new Exception(
                          "Successfully decrypted message but failed to cast to type " +
                          $"'{nameof(IEncryptedMessage)}'."
                          );
            }

            message.SequenceId = sequenceId;
            return(message);
        }
Example #33
0
 public HmacMd5Hasher(byte[] key)
 {
     _hasher = new HMACMD5(key);
 }
Example #34
0
        /// <summary>
        ///     Pass request method and URI parameters to get the Authorization header value
        /// </summary>
        /// <param name="method">Request Method</param>
        /// <param name="url">Request URI</param>
        /// <returns>Authorization header value</returns>
        public string getAuthorizationHeader(string method, string url)
        {
            var uri     = new Uri(url);
            var baseUri = uri.GetLeftPart(UriPartial.Path);

            //MessageBox.Show(baseUri);
            Dictionary <string, string> headerParams = new Dictionary <string, string>(configHeaderParams);

            /// Add the realm parameter to the header params
            headerParams.Add("realm", baseUri);

            /// Start composing the base string from the method and request URI
            var baseString = method.ToUpper()
                             + "&"
                             + Uri.EscapeDataString(baseUri)
                             + "&";

            var index = url.IndexOf("?");

            if (index > 0)
            {
                var urlParams = url.Substring(index).Remove(0, 1);

                var args = ParseQueryString(urlParams);

                foreach (var k in args)
                {
                    headerParams.Add(k.Key, k.Value);
                }
            }

            /// Gather, encode, and sort the base string parameters
            var encodedParams = new SortedDictionary <string, string>();

            foreach (var parameter in headerParams)
            {
                if (false == parameter.Key.Equals("realm"))
                {
                    encodedParams.Add(Uri.EscapeDataString(parameter.Key), Uri.EscapeDataString(parameter.Value));
                }
            }

            /// Expand the base string by the encoded parameter=value pairs
            var paramStrings = new List <string>();

            foreach (var parameter in encodedParams)
            {
                paramStrings.Add(parameter.Key + "=" + parameter.Value);
            }
            var paramString = Uri.EscapeDataString(string.Join <string>("&", paramStrings));

            baseString += paramString;

            /// Create the OAuth signature
            var signatureKey = Uri.EscapeDataString(appSecret) + "&" + Uri.EscapeDataString(accessSecret);
            var hasher       = HMAC.Create();

            hasher.Key = Encoding.UTF8.GetBytes(signatureKey);
            var rawSignature   = hasher.ComputeHash(Encoding.UTF8.GetBytes(baseString));
            var oAuthSignature = Convert.ToBase64String(rawSignature);

            /// Include the OAuth signature parameter in the header parameters array
            headerParams.Add("oauth_signature", oAuthSignature);

            /// Construct the header string
            var headerParamStrings = new List <string>();

            foreach (var parameter in headerParams)
            {
                headerParamStrings.Add(parameter.Key + "=\"" + parameter.Value + "\"");
            }
            var authHeader = "OAuth " + string.Join <string>(", ", headerParamStrings);

            return(authHeader);
        }
Example #35
0
 public void CheckA(string testName, HMAC algo, byte[] data, byte[] result)
 {
     byte[] hmac = algo.ComputeHash(data);
     Compare(result, hmac, testName + "a1");
     Compare(result, algo.Hash, testName + "a2");
 }
Example #36
0
        private String _GenerateToken(String path, bool isUrl)
        {
            if (StartTime == NOW)
            {
                StartTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            }
            else if (StartTime != null && WindowSeconds < 0)
            {
                throw new AuthTokenException("startTime must be ( > 0 )");
            }

            if (EndTime == null)
            {
                if (WindowSeconds != null && WindowSeconds > 0)
                {
                    if (StartTime == null)
                    {
                        EndTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds +
                                  WindowSeconds;
                    }
                    else
                    {
                        EndTime = StartTime + WindowSeconds;
                    }
                }
                else
                {
                    throw new AuthTokenException("You must provide an expiration time or a duration window ( > 0 )");
                }
            }
            else if (EndTime <= 0)
            {
                throw new AuthTokenException("endTime must be ( > 0 )");
            }

            if (StartTime != null && (EndTime <= StartTime))
            {
                throw new AuthTokenException("Token will have already expired.");
            }

            if (Verbose)
            {
                Console.WriteLine("Akamai Token Generation Parameters");
                if (isUrl)
                {
                    Console.WriteLine("    URL             : " + path);
                }
                else
                {
                    Console.WriteLine("    ACL             : " + path);
                }
                Console.WriteLine("    Token Type      : " + TokenType);
                Console.WriteLine("    Token Name      : " + TokenName);
                Console.WriteLine("    Key/Secret      : " + Key);
                Console.WriteLine("    Algo            : " + Algorithm);
                Console.WriteLine("    Salt            : " + Salt);
                Console.WriteLine("    IP              : " + Ip);
                Console.WriteLine("    Payload         : " + Payload);
                Console.WriteLine("    Session ID      : " + SessionId);
                Console.WriteLine("    Start Time      : " + StartTime);
                Console.WriteLine("    Window(seconds) : " + WindowSeconds);
                Console.WriteLine("    End Time        : " + EndTime);
                Console.WriteLine("    Field Delimiter : " + FieldDelimiter);
                Console.WriteLine("    ACL Delimiter   : " + ACL_DELIMITER);
                Console.WriteLine("    Escape Early    : " + EscapeEarly);
            }


            StringBuilder newToken = new StringBuilder();

            if (!string.IsNullOrEmpty(Ip))
            {
                newToken.Append(string.Format("ip={0}{1}", Ip, FieldDelimiter));
            }

            if (StartTime != null)
            {
                newToken.Append(string.Format("st={0}{1}", StartTime, FieldDelimiter));
            }

            newToken.Append(string.Format("exp={0}{1}", EndTime, FieldDelimiter));

            if (!isUrl)
            {
                newToken.Append(string.Format("acl={0}{1}", path, FieldDelimiter));
            }

            if (!string.IsNullOrEmpty(SessionId))
            {
                newToken.Append(string.Format("id={0}{1}", SessionId, FieldDelimiter));
            }

            if (!string.IsNullOrEmpty(Payload))
            {
                newToken.Append(string.Format("data={0}{1}", Payload, FieldDelimiter));
            }

            StringBuilder hashSource = new StringBuilder(newToken.ToString());

            if (isUrl)
            {
                hashSource.Append(string.Format("url={0}{1}", path, FieldDelimiter));
            }

            if (!string.IsNullOrEmpty(Salt))
            {
                hashSource.Append(string.Format("salt={0}{1}", Salt, FieldDelimiter));
            }

            hashSource.Remove(hashSource.Length - 1, 1);

            try
            {
                HMAC hmac = HMAC.Create(Algorithm);
                hmac.Key = _HexStringToByteArray(Key);

                byte[] rawHmac = hmac.ComputeHash(Encoding.ASCII.GetBytes(hashSource.ToString()));

                StringBuilder hmacStr = new StringBuilder();
                foreach (var b in rawHmac)
                {
                    hmacStr.AppendFormat("{0:x2}", b);
                }

                return(string.Format("{0}hmac={1}", newToken, hmacStr));
            }
            catch (Exception e)
            {
                throw new AuthTokenException(e.ToString());
            }
        }
Example #37
0
 public void CheckD(string testName, HMAC algo, byte[] data, byte[] result)
 {
     algo.TransformFinalBlock(data, 0, data.Length);
     Compare(result, algo.Hash, testName + "d");
     algo.Initialize();
 }
Example #38
0
 public SignatureValidator(string key, string algorithm)
 {
     _encoder                = new UTF8Encoding();
     _signatureGenerator     = HMAC.Create(algorithm);
     _signatureGenerator.Key = _encoder.GetBytes(key);
 }
        private void ReadFrom(Stream s, string password)
        {
            byte[] format = new byte[2];
            s.Read(format, 0, 2);

            if (Encoding.ASCII.GetString(format) != "CC")
            {
                throw new InvalidCryptoContainerException("Invalid CryptoContainer format.");
            }

            switch (s.ReadByte()) //version
            {
            case 0:
                ReadPlainTextFrom(s);
                break;

            case 1:     //depricated version
            {
                if (password == null)
                {
                    throw new InvalidCryptoContainerException("Password required.");
                }

                //CryptoAlgo
                SymmetricEncryptionAlgorithm cryptoAlgo = (SymmetricEncryptionAlgorithm)s.ReadByte();

                //KeySizeBytes
                int keySizeBytes = s.ReadByte();

                byte[] IV = new byte[s.ReadByte()];
                s.Read(IV, 0, IV.Length);

                byte[] key;

                switch (keySizeBytes)
                {
                case 16:
                    key = HashAlgorithm.Create("MD5").ComputeHash(Encoding.UTF8.GetBytes(password));
                    break;

                case 32:
                    key = HashAlgorithm.Create("SHA256").ComputeHash(Encoding.UTF8.GetBytes(password));
                    break;

                default:
                    throw new CryptoException("CryptoContainer key size not supported.");
                }

                _containerKey = new SymmetricCryptoKey(cryptoAlgo, key, IV);
                ReadPlainTextFrom(_containerKey.GetCryptoStreamReader(s));

                //auto upgrade to version 2 with PBKDF2-HMAC-SHA256 when calling WriteTo
                _kdf          = PBKDF2.CreateHMACSHA256(password, keySizeBytes, PBKDF2_ITERATION_COUNT);
                key           = _kdf.GetBytes(keySizeBytes);
                _containerKey = new SymmetricCryptoKey(cryptoAlgo, key, IV);
                _hmac         = new HMACSHA256(key);
            }
            break;

            case 2:     //using PBKDF2-HMAC-SHA256
            {
                if (password == null)
                {
                    throw new InvalidCryptoContainerException("Password required.");
                }

                //CryptoAlgo
                SymmetricEncryptionAlgorithm cryptoAlgo = (SymmetricEncryptionAlgorithm)s.ReadByte();

                //KeySizeBytes
                int keySizeBytes = s.ReadByte();

                byte[] IV = new byte[s.ReadByte()];
                s.Read(IV, 0, IV.Length);

                byte[] salt = new byte[s.ReadByte()];
                s.Read(salt, 0, salt.Length);

                byte[] HMAC = new byte[s.ReadByte()];
                s.Read(HMAC, 0, HMAC.Length);

                _kdf = PBKDF2.CreateHMACSHA256(password, salt, PBKDF2_ITERATION_COUNT);
                byte[] key = _kdf.GetBytes(keySizeBytes);

                //authenticate data
                _hmac = new HMACSHA256(key);
                long   startPosition = s.Position;
                byte[] computedHMAC  = _hmac.ComputeHash(s);
                s.Position = startPosition;

                //verify hmac
                for (int i = 0; i < HMAC.Length; i++)
                {
                    if (HMAC[i] != computedHMAC[i])
                    {
                        throw new CryptoException("Invalid password or data tampered.");
                    }
                }

                //decrypt data
                _containerKey = new SymmetricCryptoKey(cryptoAlgo, key, IV);
                ReadPlainTextFrom(_containerKey.GetCryptoStreamReader(s));
            }
            break;

            case -1:
                throw new EndOfStreamException();

            default:
                throw new InvalidCryptoContainerException("CryptoContainer format version not supported.");
            }
        }
Example #40
0
 protected HmacAlgorithmBase(HMAC hmac)
 {
     this.hmac = hmac;
 }
 public ApiCredentials(string username, string apiKey, string apiSecret)
 {
     Username = username;
     ApiKey   = apiKey;
     _hmac    = new HMACSHA256(EncodingHelpers.EncodeString(apiSecret));
 }
        public static RootOptions UseApiKey(this RootOptions options, string algorithmName, string subject, JwtPayload customPayload, out string token, out SecurityKey privateKey)
        {
            if (null == options.Authentication)
            {
                options.Authentication = new AuthenticationOptions();
            }

            if (null == options.Authentication.MonitorApiKey)
            {
                options.Authentication.MonitorApiKey = new MonitorApiKeyOptions();
            }

            SigningCredentials signingCreds;
            JsonWebKey         exportableJwk;

            switch (algorithmName)
            {
            case SecurityAlgorithms.EcdsaSha256:
            case SecurityAlgorithms.EcdsaSha256Signature:
            case SecurityAlgorithms.EcdsaSha384:
            case SecurityAlgorithms.EcdsaSha384Signature:
            case SecurityAlgorithms.EcdsaSha512:
            case SecurityAlgorithms.EcdsaSha512Signature:
                ECDsa            ecDsa    = ECDsa.Create(GetEcCurveFromName(algorithmName));
                ECDsaSecurityKey ecSecKey = new ECDsaSecurityKey(ecDsa);
                signingCreds = new SigningCredentials(ecSecKey, algorithmName);
                ECDsa            pubEcDsa    = ECDsa.Create(ecDsa.ExportParameters(false));
                ECDsaSecurityKey pubEcSecKey = new ECDsaSecurityKey(pubEcDsa);
                exportableJwk = JsonWebKeyConverter.ConvertFromECDsaSecurityKey(pubEcSecKey);
                privateKey    = ecSecKey;
                break;

            case SecurityAlgorithms.RsaSha256:
            case SecurityAlgorithms.RsaSha256Signature:
            case SecurityAlgorithms.RsaSha384:
            case SecurityAlgorithms.RsaSha384Signature:
            case SecurityAlgorithms.RsaSha512:
            case SecurityAlgorithms.RsaSha512Signature:
                RSA            rsa       = RSA.Create(GetRsaKeyLengthFromName(algorithmName));
                RsaSecurityKey rsaSecKey = new RsaSecurityKey(rsa);
                signingCreds = new SigningCredentials(rsaSecKey, algorithmName);
                RSA            pubRsa       = RSA.Create(rsa.ExportParameters(false));
                RsaSecurityKey pubRsaSecKey = new RsaSecurityKey(pubRsa);
                exportableJwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(pubRsaSecKey);
                privateKey    = rsaSecKey;
                break;

            case SecurityAlgorithms.HmacSha256:
            case SecurityAlgorithms.HmacSha384:
            case SecurityAlgorithms.HmacSha512:
                HMAC hmac = HMAC.Create(GetHmacAlgorithmFromName(algorithmName));
                SymmetricSecurityKey hmacSecKey = new SymmetricSecurityKey(hmac.Key);
                signingCreds  = new SigningCredentials(hmacSecKey, algorithmName);
                exportableJwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(hmacSecKey);
                privateKey    = hmacSecKey;
                break;

            default:
                throw new ArgumentException($"Algorithm name '{algorithmName}' not supported", nameof(algorithmName));
            }

            JwtHeader               newHeader    = new JwtHeader(signingCreds, null, JwtConstants.HeaderType);
            JwtSecurityToken        newToken     = new JwtSecurityToken(newHeader, customPayload);
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            string resultToken = tokenHandler.WriteToken(newToken);

            JsonSerializerOptions serializerOptions = JsonSerializerOptionsFactory.Create(JsonSerializerOptionsFactory.JsonIgnoreCondition.WhenWritingNull);
            string publicKeyJson = JsonSerializer.Serialize(exportableJwk, serializerOptions);

            string publicKeyEncoded = Base64UrlEncoder.Encode(publicKeyJson);

            options.Authentication.MonitorApiKey.Subject   = subject;
            options.Authentication.MonitorApiKey.PublicKey = publicKeyEncoded;

            token = resultToken;

            return(options);
        }
Example #43
0
 public Return()
 {
     _poolItem = _sut.Create();
 }
Example #44
0
        /// <param name="newConnectionAtResponderToRequesterNullable">
        /// direct P2P stream from N to A
        /// if newConnectionAtResponderToRequesterNullable is specified, the procedure
        /// verifies RequesterHMAC, decrypts endpoint of A (ToRequesterTxParametersEncrypted), initializes P2P stream
        /// </param>
        public static RegisterAck2Packet Decode_OptionallyVerify_InitializeP2pStreamAtResponder(Logger logger, byte[] registerAckPacketData,
                                                                                                RegisterRequestPacket reqNullable,
                                                                                                RegisterAck1Packet ack1Nullable,
                                                                                                ConnectionToNeighbor newConnectionAtResponderToRequesterNullable
                                                                                                )
        {
            var reader = BinaryProcedures.CreateBinaryReader(registerAckPacketData, 1);

            var ack = new RegisterAck2Packet();

            ack.DecodedUdpPayloadData = registerAckPacketData;
            ack.Flags = reader.ReadByte();
            if ((ack.Flags & FlagsMask_MustBeZero) != 0)
            {
                throw new NotImplementedException();
            }
            if ((ack.Flags & Flag_AtoEP) == 0)
            {
                ack.NeighborToken32 = NeighborToken32.Decode(reader);
            }

            ack.ReqTimestamp64          = reader.ReadInt64();
            ack.RequesterRegistrationId = RegistrationId.Decode(reader);
            if (reqNullable != null)
            {
                ack.AssertMatchToSyn(reqNullable);
            }

            ack.ToRequesterTxParametersEncrypted = reader.ReadBytes(ToRequesterTxParametersEncryptedLength);
            if (newConnectionAtResponderToRequesterNullable != null)
            {
                newConnectionAtResponderToRequesterNullable.Decrypt_ack2_ToRequesterTxParametersEncrypted_AtResponder_InitializeP2pStream(logger, reqNullable, ack1Nullable, ack);
            }

            ack.RequesterSignature = RegistrationSignature.Decode(reader);
            if (newConnectionAtResponderToRequesterNullable != null)
            {
                if (reqNullable == null)
                {
                    throw new ArgumentException();
                }
                if (ack1Nullable == null)
                {
                    throw new ArgumentException();
                }
                if (!ack.RequesterSignature.Verify(newConnectionAtResponderToRequesterNullable.Engine.CryptoLibrary,
                                                   w =>
                {
                    reqNullable.GetSharedSignedFields(w, true);
                    ack1Nullable.GetSharedSignedFields(w, true, true);
                    ack.GetSharedSignedFields(w, false, true);
                },
                                                   reqNullable.RequesterRegistrationId))
                {
                    throw new BadSignatureException("invalid REGISTER ACK2 RequesterSignature 6106");
                }
            }

            ack.ReqP2pSeq16 = RequestP2pSequenceNumber16.Decode(reader);

            if ((ack.Flags & Flag_AtoEP) == 0)
            {
                ack.NeighborHMAC = HMAC.Decode(reader); // is verified by Filter
            }

            return(ack);
        }