Inheritance: HashAlgorithm
Beispiel #1
0
        public HmacInfo(KeyedHashAlgorithm algorithm, int keySize)
        {
            Contract.Requires(algorithm != null);

            KeySize = keySize;
            Hmac = key => new HmacAlgorithm(algorithm, keySize, key);
        }
		public RequestSigner(AwsCredentials credentials = null, RequestSignerAlgorithm algorithm = RequestSignerAlgorithm.HmacSha1)
		{


			switch (algorithm)
			{
				case RequestSignerAlgorithm.HmacSha1:
					{
						_algorithm = new HMACSHA1();
						break;
					}

				case RequestSignerAlgorithm.HmacSha256:
					{
						_algorithm = new HMACSHA256();
						break;
					}

				default:
					{
						throw new ArgumentException("Invalid value : " + algorithm, "algorithm");
					}
			}


			Credentials = credentials;
			RequestSignerAlgorithm = algorithm;
		}
Beispiel #3
0
 ProtectedKey GenerateKey(KeyedHashAlgorithm algorithm, DataProtectionScope dataProtectionScope)
 {
     using (algorithm)
     {
         return ProtectedKey.CreateFromPlaintextKey(algorithm.Key, dataProtectionScope);
     }
 }
Beispiel #4
0
		public ECIES (ECDomainNames name)
		{
			_domain = ECDomains.GetDomainParameter (name);
			_kdf = new ANSI_X963_KDF (new SHA1Managed ());
			_params = new ECIESParameters (_domain);
			_mac = new HMACSHA1 ();
		}
Beispiel #5
0
 public static string HMACSign(string data, SecureString key, KeyedHashAlgorithm algorithm)
 {
     string str;
     if (key == null)
     {
         throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");
     }
     if (string.IsNullOrEmpty(data))
     {
         throw new ArgumentNullException("data", "Please specify data to sign.");
     }
     if (algorithm == null)
     {
         throw new ArgumentNullException("algorithm", "Please specify a KeyedHashAlgorithm to use.");
     }
     IntPtr zero = IntPtr.Zero;
     char[] destination = new char[key.Length];
     try
     {
         zero = Marshal.SecureStringToBSTR(key);
         Marshal.Copy(zero, destination, 0, destination.Length);
         algorithm.Key = Encoding.UTF8.GetBytes(destination);
         str = Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(data.ToCharArray())));
     }
     finally
     {
         Marshal.ZeroFreeBSTR(zero);
         algorithm.Clear();
         Array.Clear(destination, 0, destination.Length);
     }
     return str;
 }
 private void ComputeSignature(KeyedHashAlgorithm hash)
 {
     this.Signature.SignedInfo.ComputeReferenceDigests();
     this.Signature.SignedInfo.ComputeHash(hash);
     byte[] signatureValue = hash.Hash;
     this.Signature.SetSignatureValue(signatureValue);
 }
		public ShortKeyedHashAlgorithm (KeyedHashAlgorithm baseAlgo, int outputHashBits)
		{
			_base = baseAlgo;
			_hashBits = outputHashBits;
			if (outputHashBits <= 0 || _base.HashSize < outputHashBits)
				throw new ArgumentOutOfRangeException ();
		}
 protected KeyHashAlgorithmGenerator(KeyedHashAlgorithm algorithm)
 {
     if (algorithm == null)
     {
         throw new ArgumentNullException("algorithm");
     }
     this._algorithm = algorithm;
 }
 public static string Sign(string data, SecureString key, KeyedHashAlgorithm algorithm)
 {
     if (key == null)
     {
         throw new AmazonCloudFrontException("The AWS Secret Access Key specified is NULL");
     }
     return AWSSDKUtils.HMACSign(data, key, algorithm);
 }
Beispiel #10
0
        public HmacAlgorithm(KeyedHashAlgorithm algorithm, int keySize, byte[] key)
        {
            Contract.Requires(algorithm != null);
            Contract.Requires(key != null);
            Contract.Requires(keySize == key.Length << 3);

            _algorithm = algorithm;
            algorithm.Key = key;
        }
Beispiel #11
0
        public static string HMACSign(string data, System.Security.SecureString key, KeyedHashAlgorithm algorithm)
#endif
        {
#if UNITY
            if (String.IsNullOrEmpty(key))
#else
            if (null == key)
#endif
            {
                throw new ArgumentNullException("key", "The AWS Secret Access Key specified is NULL!");
            }

            if (String.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException("data", "Please specify data to sign.");
            }

            if (null == algorithm)
            {
                throw new ArgumentNullException("algorithm", "Please specify a KeyedHashAlgorithm to use.");
            }
#if UNITY
            try
            {
                algorithm.Key = Encoding.UTF8.GetBytes(key);
                return Convert.ToBase64String(algorithm.ComputeHash(
                    Encoding.UTF8.GetBytes(data.ToCharArray()))
                    );
            }
            finally
            {
                algorithm.Clear();
            }
#else
            // pointer to hold unmanaged reference to SecureString instance
            IntPtr bstr = IntPtr.Zero;
            char[] charArray = new char[key.Length];
            try
            {
                // Marshal SecureString into byte array
                bstr = Marshal.SecureStringToBSTR(key);
                Marshal.Copy(bstr, charArray, 0, charArray.Length);
                algorithm.Key = Encoding.UTF8.GetBytes(charArray);
                return Convert.ToBase64String(algorithm.ComputeHash(
                    Encoding.UTF8.GetBytes(data.ToCharArray()))
                    );
            }
            finally
            {
                // Make sure that the clear text data is zeroed out
                Marshal.ZeroFreeBSTR(bstr);
                algorithm.Clear();
                Array.Clear(charArray, 0, charArray.Length);
            }
#endif
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SymmetricSignatureProvider"/> class that uses an <see cref="SymmetricSecurityKey"/> to create and / or verify signatures over a array of bytes.
        /// </summary>
        /// <param name="key">The <see cref="SymmetricSecurityKey"/> used for signing.</param>
        /// <param name="algorithm">The signature algorithm to use.</param>
        /// <exception cref="ArgumentNullException">'key' is null.</exception>
        /// <exception cref="ArgumentNullException">'algorithm' is null.</exception>
        /// <exception cref="ArgumentException">'algorithm' contains only whitespace.</exception>
        /// <exception cref="ArgumentOutOfRangeException">'<see cref="SymmetricSecurityKey"/>.KeySize' is smaller than <see cref="SignatureProviderFactory.MinimumSymmetricKeySizeInBits"/>.</exception>
        /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetKeyedHashAlgorithm"/> throws.</exception>
        /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetKeyedHashAlgorithm"/> returns null.</exception>
        /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetSymmetricKey"/> throws.</exception>
        public SymmetricSignatureProvider(SymmetricSecurityKey key, string algorithm)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (null == algorithm)
            {
                throw new ArgumentNullException(algorithm);
            }

            if (string.IsNullOrWhiteSpace(algorithm))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10002, "algorithm"));
            }

            if (key.KeySize < SignatureProviderFactory.MinimumSymmetricKeySizeInBits)
            {
                throw new ArgumentOutOfRangeException("key.KeySize", key.KeySize, string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10603, key.GetType(), SignatureProviderFactory.MinimumSymmetricKeySizeInBits));
            }

            try
            {
                this.keyedHash = key.GetKeyedHashAlgorithm(algorithm);
            }
            catch (Exception ex)
            {
                if (DiagnosticUtility.IsFatal(ex))
                {
                    throw;
                }

                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10632, algorithm, key, ex), ex);
            }

            if (this.keyedHash == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10633, algorithm, key));
            }

            try
            {
                this.keyedHash.Key = key.GetSymmetricKey();
            }
            catch (Exception ex)
            {
                if (DiagnosticUtility.IsFatal(ex))
                {
                    throw;
                }

                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10634, algorithm, key, ex), ex);
            }
        }
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
        protected override void Dispose(bool disposing)
        {
            // Dispose managed ResourceMessages.
            if (this._hash != null)
            {
                this._hash.Dispose();
                this._hash = null;
            }

            base.Dispose(disposing);
        }
 public ManagedPsha1(byte[] secret, byte[] label, byte[] seed)
 {
     this.secret = secret;
     this.seed = DiagnosticUtility.Utility.AllocateByteArray(label.Length + seed.Length);
     label.CopyTo(this.seed, 0);
     seed.CopyTo(this.seed, label.Length);
     this.aValue = this.seed;
     this.chunk = new byte[0];
     this.index = 0;
     this.position = 0;
     this.hmac = CryptoHelper.NewHmacSha1KeyedHashAlgorithm(secret);
     this.buffer = DiagnosticUtility.Utility.AllocateByteArray((this.hmac.HashSize / 8) + this.seed.Length);
 }
Beispiel #15
0
        /// <summary>
        /// Creates a new PBKDF2 stream.
        /// </summary>
        /// <param name="hmacAlgorithm">
        ///     The HMAC algorithm to use, for example <see cref="HMACSHA256"/>.
        ///     Make sure to set <see cref="KeyedHashAlgorithm.Key"/>.
        /// </param>
        /// <param name="salt">
        ///     The salt.
        ///     A unique salt means a unique PBKDF2 stream, even if the original key is identical.
        /// </param>
        /// <param name="iterations">The number of iterations to apply.</param>
        public Pbkdf2(KeyedHashAlgorithm hmacAlgorithm, byte[] salt, int iterations)
        {
            Check.Null("hmacAlgorithm", hmacAlgorithm);
            Check.Null("salt", salt);
            Check.Length("salt", salt, 0, int.MaxValue - 4);
            Check.Range("iterations", iterations, 1, int.MaxValue);
            if (hmacAlgorithm.HashSize == 0 || hmacAlgorithm.HashSize % 8 != 0)
                { throw Exceptions.Argument("hmacAlgorithm", "Unsupported hash size."); }

            int hmacLength = hmacAlgorithm.HashSize / 8;
            _saltBuffer = new byte[salt.Length + 4]; Array.Copy(salt, _saltBuffer, salt.Length);
            _iterations = iterations; _hmacAlgorithm = hmacAlgorithm;
            _digest = new byte[hmacLength]; _digestT1 = new byte[hmacLength];
        }
        /// <summary>
        /// Initialize a new instance of the <see cref="KeyedHashAlgorithmKeyCreator"/> class.
        /// </summary>
        /// <param name="algorithmType">The <see cref="HashAlgorithm"/> type that should be used.</param>
        public KeyedHashAlgorithmKeyCreator(Type algorithmType)
        {
            if (algorithmType == null) 
            {
                throw new ArgumentNullException("algorithmType");
            }

            if (!typeof(HashAlgorithm).IsAssignableFrom(algorithmType))
            {
                throw new ArgumentException(Resources.TypeShouldDeriveFromHashAlgorithm, "algorithmType");
            }
            
            this.algorithm = CreateAlgorithm(algorithmType);
            this.algorithmType = algorithmType;
        }
		public KeyedHashAlgorithm(HashAlgorithmNames algorithm)
		{
			switch (algorithm)
			{
				case HashAlgorithmNames.Sha1:
					alg = new C.HMACSHA1();
					break;
				case HashAlgorithmNames.Sha256:
					alg = new C.HMACSHA256();
                    break;
				case HashAlgorithmNames.Sha384:
					alg = new C.HMACSHA384();
                    break;
				case HashAlgorithmNames.Sha512:
					alg = new C.HMACSHA512();
                    break;
				case HashAlgorithmNames.Md5:
					alg = new C.HMACMD5();
                    break;
				default:
					throw new NotSupportedException();
			}
		}
        /// <summary>
        /// Computes the HMAC hash of a given byte[]. This is a wrapper over the Mac crypto functions.
        /// </summary>
        /// <param name="data">byte[] of content to hash</param>
        /// <param name="key">secret key to salt the hash. This is assumed to be UTF-8 encoded</param>
        /// <param name="hashType">determines which alogirthm to use. The recommendation is to use HMAC-SHA256</param>
        /// <returns>a byte[] presenting the HMAC hash of the source data. If the data object is null, null will be returned</returns>
        public static byte[] ComputeKeyedHash(this byte[] data, string key, KeyedHashAlgorithm hashType = KeyedHashAlgorithm.HMACSHA256)
        {
            if (data == null) return null;

            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            using (var algorithm = HMAC.Create(hashType.ToString()))
            {
                algorithm.Key = key.ToByteArray();
                return algorithm.ComputeHash(data);
            }
        }
        public TLSGenericDeriveBytes(TLSGenericType type, byte[] secret, byte[] seed)
        {
            /* Here should be all supported types */
            switch (type) {
            case TLSGenericType.MD5:
                _hmac = new HMACGeneric(secret, "MD5", 64);
                break;
            case TLSGenericType.SHA1:
                _hmac = new HMACGeneric(secret, "SHA1", 64);
                break;
            case TLSGenericType.SHA256:
                _hmac = new HMACGeneric(secret, "SHA256", 64);
                break;
            case TLSGenericType.SHA384:
                _hmac = new HMACGeneric(secret, "SHA384", 128);
                break;
            case TLSGenericType.SHA512:
                _hmac = new HMACGeneric(secret, "SHA512", 128);
                break;
            default:
                throw new Exception("Unsupported TLSGenericType");
            }

            /* Set the seed as our parameter */
            _seed = seed;

            /* Reset the HMAC generators */
            Reset();
        }
		static string CreateResourceUrl (KeyedHashAlgorithm kha, string assemblyName, string assemblyNameHash, string assemblyPath, string resourceNameHash, bool debug, bool notifyScriptLoaded)
		{
			string atime = String.Empty;
			string extra = String.Empty;
#if SYSTEM_WEB_EXTENSIONS
			extra = QueryParamSeparator + "n=" + (notifyScriptLoaded ? "t" : "f");
#endif

#if TARGET_JVM
			atime = QueryParamSeparator + "t=" + assemblyName.GetHashCode ();
#else
			if (!String.IsNullOrEmpty (assemblyPath) && File.Exists (assemblyPath))
				atime = QueryParamSeparator + "t=" + File.GetLastWriteTimeUtc (assemblyPath).Ticks;
			else
				atime = QueryParamSeparator + "t=" + DateTime.UtcNow.Ticks;
#endif
			string d = assemblyNameHash + "_" + resourceNameHash +  (debug ? "_t" : "_f");
			string href = HandlerFileName + "?d=" + d + atime + extra;
			HttpContext ctx = HttpContext.Current;
			HttpRequest req = ctx != null ? ctx.Request : null;
			if (req != null) {
				string appPath = VirtualPathUtility.AppendTrailingSlash (req.ApplicationPath);
				href = appPath + href;
			}
			
			return href;
		}
		static string GetResourceUrl (KeyedHashAlgorithm kha, Assembly assembly, string resourceName, bool notifyScriptLoaded)
		{
			string assemblyName = assembly == currAsm ? "s" : assembly.GetName ().FullName;
			string assemblyNameHash = GetStringHash (kha, assemblyName);
			string resourceNameHash = GetStringHash (kha, resourceName);
			bool debug = false;
			string url;
			AssemblyEmbeddedResources entry;

			try {
				_embeddedResourcesLock.EnterUpgradeableReadLock ();
				if (!_embeddedResources.TryGetValue (assemblyNameHash, out entry) || entry == null) {
					try {
						_embeddedResourcesLock.EnterWriteLock ();
						entry = new AssemblyEmbeddedResources () {
							AssemblyName = assemblyName
						};
						InitEmbeddedResourcesUrls (kha, assembly, assemblyName, assemblyNameHash, entry);
						_embeddedResources.Add (assemblyNameHash, entry);
					} finally {
						_embeddedResourcesLock.ExitWriteLock ();
					}
				}
				string lookupKey;
#if SYSTEM_WEB_EXTENSIONS
				debug = resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase);
				string dbgTail = debug ? "d" : String.Empty;
				lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f") + dbgTail;
#else
				lookupKey = resourceNameHash;
#endif
				EmbeddedResource res;
				if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
					url = res.Url;
				else {
#if SYSTEM_WEB_EXTENSIONS
					if (debug) {
						resourceNameHash = GetStringHash (kha, resourceName.Substring (0, resourceName.Length - 9) + ".js");
						lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f");
					
						if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
							url = res.Url;
						else
							url = null;
					} else
#endif
						url = null;
				}
			} finally {
				_embeddedResourcesLock.ExitUpgradeableReadLock ();
			}

			if (url == null)
				url = CreateResourceUrl (kha, assemblyName, assemblyNameHash, assembly.Location, resourceNameHash, debug, notifyScriptLoaded);
			
			return url;
		}
		static void InitEmbeddedResourcesUrls (KeyedHashAlgorithm kha, Assembly assembly, string assemblyName, string assemblyHash, AssemblyEmbeddedResources entry)
		{
			WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
			WebResourceAttribute attr;
			string apath = assembly.Location;
			for (int i = 0; i < attrs.Length; i++) {
				attr = attrs [i];
				string resourceName = attr.WebResource;
				if (!String.IsNullOrEmpty (resourceName)) {
					string resourceNameHash = GetStringHash (kha, resourceName);
#if SYSTEM_WEB_EXTENSIONS
					bool debug = resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase);
					string dbgTail = debug ? "d" : String.Empty;
					string rkNoNotify = resourceNameHash + "f" + dbgTail;
					string rkNotify = resourceNameHash + "t" + dbgTail;

					if (!entry.Resources.ContainsKey (rkNoNotify)) {
						var er = new EmbeddedResource () {
							Name = resourceName,
							Attribute = attr, 
							Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, rkNoNotify, debug, false)
						};
						
						entry.Resources.Add (rkNoNotify, er);
					}
					
					if (!entry.Resources.ContainsKey (rkNotify)) {
						var er = new EmbeddedResource () {
							Name = resourceName,
							Attribute = attr, 
							Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, rkNotify, debug, true)
						};
						
						entry.Resources.Add (rkNotify, er);
					}
#else
					if (!entry.Resources.ContainsKey (resourceNameHash)) {
						var er = new EmbeddedResource () {
							Name = resourceName,
							Attribute = attr, 
							Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, resourceNameHash, false, false)
						};
						entry.Resources.Add (resourceNameHash, er);
					}
#endif
				}
			}
		}
		static string GetStringHash (KeyedHashAlgorithm kha, string str)
		{
			if (String.IsNullOrEmpty (str))
				return String.Empty;

			string result;
			Dictionary <string, string> cache = StringHashCache;
			if (cache.TryGetValue (str, out result))
				return result;
			
			result = Convert.ToBase64String (kha.ComputeHash (Encoding.UTF8.GetBytes (str)));
			cache.Add (str, result);
			return result;
		}
        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);
        }
 private bool CheckSignedInfo(KeyedHashAlgorithm macAlg)
 {
     int hashSize;
     if (macAlg == null)
     {
         throw new ArgumentNullException("macAlg");
     }
     SignedXmlDebugLog.LogBeginCheckSignedInfo(this, this.m_signature.SignedInfo);
     if (this.m_signature.SignedInfo.SignatureLength == null)
     {
         hashSize = macAlg.HashSize;
     }
     else
     {
         hashSize = Convert.ToInt32(this.m_signature.SignedInfo.SignatureLength, (IFormatProvider) null);
     }
     if ((hashSize < 0) || (hashSize > macAlg.HashSize))
     {
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength"));
     }
     if ((hashSize % 8) != 0)
     {
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2"));
     }
     if (this.m_signature.SignatureValue == null)
     {
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureValueRequired"));
     }
     if (this.m_signature.SignatureValue.Length != (hashSize / 8))
     {
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength"));
     }
     byte[] actualHashValue = this.GetC14NDigest(macAlg);
     SignedXmlDebugLog.LogVerifySignedInfo(this, macAlg, actualHashValue, this.m_signature.SignatureValue);
     for (int i = 0; i < this.m_signature.SignatureValue.Length; i++)
     {
         if (this.m_signature.SignatureValue[i] != actualHashValue[i])
         {
             return false;
         }
     }
     return true;
 }
 public bool CheckSignature(KeyedHashAlgorithm macAlg)
 {
     if (!this.CheckSignatureFormat())
     {
         return false;
     }
     if (!this.CheckSignedInfo(macAlg))
     {
         SignedXmlDebugLog.LogVerificationFailure(this, SecurityResources.GetResourceString("Log_VerificationFailed_SignedInfo"));
         return false;
     }
     if (!this.CheckDigestedReferences())
     {
         SignedXmlDebugLog.LogVerificationFailure(this, SecurityResources.GetResourceString("Log_VerificationFailed_References"));
         return false;
     }
     SignedXmlDebugLog.LogVerificationResult(this, macAlg, true);
     return true;
 }
Beispiel #27
0
        /// <summary>
        /// Computes RFC 2104-compliant HMAC signature
        /// </summary>
        /// <param name="data">The data to be signed</param>
        /// <param name="key">The secret signing key</param>
        /// <param name="algorithm">The algorithm to sign the data with</param>
        /// <exception cref="T:System.ArgumentNullException"/>
        /// <returns>A string representing the HMAC signature</returns>
        public static string HMACSign(byte[] data, string key, KeyedHashAlgorithm algorithm)
        {
            if (String.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");
            }

            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data", "Please specify data to sign.");
            }

            if (null == algorithm)
            {
                throw new ArgumentNullException("algorithm", "Please specify a KeyedHashAlgorithm to use.");
            }

            try
            {
                algorithm.Key = Encoding.UTF8.GetBytes(key);
                byte[] bytes = algorithm.ComputeHash(data);
                return Convert.ToBase64String(bytes);
            }
            finally
            {
                algorithm.Clear();
            }
        }
Beispiel #28
0
 internal JWT(JWTHeader header, KeyedHashAlgorithm algorithm)
 {
     Header    = header;
     Algorithm = algorithm;
 }
        /// <summary>
        /// Computes RFC 2104-compliant HMAC signature
        /// </summary>
        /// <param name="data">The data to be signed</param>
        /// <param name="key">The secret signing key</param>
        /// <param name="algorithm">The algorithm to sign the data with</param>
        /// <returns>A string representing the HMAC signature</returns>
        public static string Sign(string data, System.Security.SecureString key, KeyedHashAlgorithm algorithm)
        {
            if (key == null)
            {
                throw new GrandCloudCSException("The Secret Access Key specified is NULL!");
            }

            return CSSDKUtils.HMACSign(data, key, algorithm);
        }
Beispiel #30
0
		public SignedXml SignHMAC (string uri, KeyedHashAlgorithm mac, bool ok)
		{
			string input = "<foo/>";

			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (input);

			SignedXml sig = new SignedXml (doc);
			Reference r = new Reference ("");
			r.AddTransform (new XmlDsigEnvelopedSignatureTransform ());
			r.DigestMethod = uri;
			sig.AddReference (r);

			sig.ComputeSignature (mac);
			doc.DocumentElement.AppendChild (doc.ImportNode (sig.GetXml (), true));
			// doc.Save (System.Console.Out);

			sig.LoadXml (doc.DocumentElement ["Signature"]);
			Assert.AreEqual (ok, sig.CheckSignature (mac), "CheckSignature");
			return sig;
		}
Beispiel #31
0
		static void CheckErratum (SignedXml signed, KeyedHashAlgorithm hmac, string message)
		{
			if (erratum) {
				try {
					signed.CheckSignature (hmac);
					Assert.Fail (message + ": unexcepted success");
				}
				catch (CryptographicException) {
				}
				catch (Exception e) {
					Assert.Fail (message + ": unexcepted " + e.ToString ());
				}
			} else {
				Assert.IsTrue (signed.CheckSignature (hmac), message);
			}
		}
Beispiel #32
0
 /// <summary>Creates an instance of the default implementation of a keyed hash algorithm.</summary>
 /// <returns>A new <see cref="T:System.Security.Cryptography.HMACSHA1" /> instance, unless the default settings have been changed.</returns>
 /// <PermissionSet>
 ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
 /// </PermissionSet>
 public new static KeyedHashAlgorithm Create()
 {
     return(KeyedHashAlgorithm.Create("System.Security.Cryptography.KeyedHashAlgorithm"));
 }