private byte[] SignData(byte[] cipherText, byte[] masterKey, SymmetricAlgorithm symmetricAlgorithm, KeyedHashAlgorithm hashAlgorithm, int keyDerivationIterationCount) { hashAlgorithm.Key = DerivedSigningKey(masterKey, symmetricAlgorithm, keyDerivationIterationCount); byte[] signature = hashAlgorithm.ComputeHash(cipherText); hashAlgorithm.Clear(); return(signature); }
/// <summary> /// Computes an AWS4 authorization for a request, suitable for embedding /// in query parameters. /// </summary> /// <param name="headers"> /// The request headers; 'Host' and 'X-Amz-Date' will be added to this set. /// </param> /// <param name="queryParameters"> /// Any query parameters that will be added to the endpoint. The parameters /// should be specified in canonical format. /// </param> /// <param name="bodyHash"> /// Precomputed SHA256 hash of the request body content; this value should also /// be set as the header 'X-Amz-Content-SHA256' for non-streaming uploads. /// </param> /// <param name="awsAccessKey"> /// The user's AWS Access Key. /// </param> /// <param name="awsSecretKey"> /// The user's AWS Secret Key. /// </param> /// <returns> /// The string expressing the Signature V4 components to add to query parameters. /// </returns> public string ComputeSignature(IDictionary <string, string> headers, string queryParameters, string bodyHash, string awsAccessKey, string awsSecretKey) { // first get the date and time for the subsequent request, and convert to ISO 8601 format // for use in signature generation var requestDateTime = DateTime.UtcNow; var dateTimeStamp = requestDateTime.ToString(ISO8601BasicFormat, CultureInfo.InvariantCulture); // extract the host portion of the endpoint to include in the signature calculation, // unless already set if (!headers.ContainsKey("Host")) { var hostHeader = EndpointUri.Host; if (!EndpointUri.IsDefaultPort) { hostHeader += ":" + EndpointUri.Port; } headers.Add("Host", hostHeader); } var dateStamp = requestDateTime.ToString(DateStringFormat, CultureInfo.InvariantCulture); var scope = string.Format("{0}/{1}/{2}/{3}", dateStamp, Region, Service, TERMINATOR); // canonicalized headers need to be expressed in the query // parameters processed in the signature var canonicalizedHeaderNames = CanonicalizeHeaderNames(headers); var canonicalizedHeaders = CanonicalizeHeaders(headers); // reform the query parameters to (a) add the parameters required for // Signature V4 and (b) canonicalize the set before they go into the // signature calculation. Note that this assumes parameter names and // values added outside this routine are already url encoded var paramDictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(queryParameters)) { paramDictionary = queryParameters.Split('&').Select(p => p.Split('=')) .ToDictionary(nameval => nameval[0], nameval => nameval.Length > 1 ? nameval[1] : ""); } // add the fixed authorization params required by Signature V4 paramDictionary.Add(X_Amz_Algorithm, HttpHelpers.UrlEncode(string.Format("{0}-{1}", SCHEME, ALGORITHM))); paramDictionary.Add(X_Amz_Credential, HttpHelpers.UrlEncode(string.Format("{0}/{1}", awsAccessKey, scope))); paramDictionary.Add(X_Amz_SignedHeaders, HttpHelpers.UrlEncode(canonicalizedHeaderNames)); // x-amz-date is now added as a query parameter, not a header, but still needs to be in ISO8601 basic form paramDictionary.Add(X_Amz_Date, HttpHelpers.UrlEncode(dateTimeStamp)); // build the expanded canonical query parameter string that will go into the // signature computation var sb = new StringBuilder(); var paramKeys = new List <string>(paramDictionary.Keys); paramKeys.Sort(StringComparer.Ordinal); foreach (var p in paramKeys) { if (sb.Length > 0) { sb.Append("&"); } sb.AppendFormat("{0}={1}", p, paramDictionary[p]); } var canonicalizedQueryParameters = sb.ToString(); // express all the header and query parameter data as a canonical request string var canonicalRequest = CanonicalizeRequest(EndpointUri, HttpMethod, canonicalizedQueryParameters, canonicalizedHeaderNames, canonicalizedHeaders, bodyHash); Console.WriteLine("\nCanonicalRequest:\n{0}", canonicalRequest); byte[] canonicalRequestHashBytes = CanonicalRequestHashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest)); // construct the string to be signed var stringToSign = new StringBuilder(); stringToSign.AppendFormat("{0}-{1}\n{2}\n{3}\n", SCHEME, ALGORITHM, dateTimeStamp, scope); stringToSign.Append(ToHexString(canonicalRequestHashBytes, true)); Console.WriteLine("\nStringToSign:\n{0}", stringToSign); // compute the multi-stage signing key KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(HMACSHA256); kha.Key = DeriveSigningKey(HMACSHA256, awsSecretKey, Region, dateStamp, Service); // compute the final signature for the request, place into the result and return to the // user to be embedded in the request as needed var signature = kha.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString())); var signatureString = ToHexString(signature, true); Console.WriteLine("\nSignature:\n{0}", signatureString); // form up the authorization parameters for the caller to place in the query string var authString = new StringBuilder(); var authParams = new string[] { X_Amz_Algorithm, X_Amz_Credential, X_Amz_Date, X_Amz_SignedHeaders }; foreach (var p in authParams) { if (authString.Length > 0) { authString.Append("&"); } authString.AppendFormat("{0}={1}", p, paramDictionary[p]); } authString.AppendFormat("&{0}={1}", X_Amz_Signature, signatureString); var authorization = authString.ToString(); Console.WriteLine("\nAuthorization:\n{0}", authorization); return(authorization); }
/// <summary> /// Signs data /// </summary> private static byte[] SignData(string password, byte[] data, byte[] salt, SymmetricAlgorithm encryptator, KeyedHashAlgorithm signer) { // Get key signer.Key = KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA512, KeyDerivationIterationCount, encryptator.KeySize / 8); // Compute hash byte[] signature = signer.ComputeHash(data); // Clear the algorithm signer.Clear(); // Return data return(signature); }
/// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using a /// keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="mac">hash algoirthm doing the verification</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, KeyedHashAlgorithm mac, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(mac != null, "mac != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerifySignedInfoHmac"), mac.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_ActualHashValue"), FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_RawSignatureValue"), FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } }
public ShaPrfAlgorithm(KeyedHashAlgorithm hashAlgorithm) { this.hashAlgorithm = hashAlgorithm; }
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 async Task UploadToS3Worker(FileInfo Info, string Region, string KeyId, string AccessKey, string BucketName, string FolderName) { // -------------------------------------------------- // "AWS Signature Version 4" // http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html // -------------------------------------------------- LogInformation(" Uploading " + Info.Name); // -------------------------------------------------- // http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html string TimeStamp = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ"); string DateExpire = DateTime.UtcNow.AddDays(1).ToString("yyyy-MM-dd"); string AWSDate = DateTime.UtcNow.AddDays(1).ToString("yyyyMMdd"); string MimeType = (MimeTypeMapping.ContainsKey(Info.Extension)) ? MimeTypeMapping[Info.Extension] : "application/octet-stream"; string MimePath = MimeType.Split('/')[0]; string AWSCredential = KeyId + "/" + AWSDate + "/" + Region + "/s3/aws4_request"; // -------------------------------------------------- string policy = "{ \"expiration\": \"" + DateExpire + "T12:00:00.000Z\"," + " \"conditions\": [" + " { \"bucket\": \"" + BucketName + "\" }," + " [ \"starts-with\", \"$key\", \"" + FolderName + "/\" ]," + " { \"acl\": \"public-read\" }," + " [ \"starts-with\", \"$content-type\", \"" + MimePath + "/\" ],"; if (Info.Extension.EndsWith("gz")) { policy += " [ \"starts-with\", \"$content-encoding\", \"gzip\" ],"; } policy += " { \"x-amz-credential\": \"" + AWSCredential + "\" }," + " { \"x-amz-algorithm\": \"AWS4-HMAC-SHA256\" }," + " { \"x-amz-date\": \"" + TimeStamp + "\" }" + " ]" + "}"; string policyBase64 = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(policy), Base64FormattingOptions.InsertLineBreaks); // -------------------------------------------------- // http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html var kha = KeyedHashAlgorithm.Create("HmacSHA256"); kha.Key = Encoding.UTF8.GetBytes(("AWS4" + AccessKey).ToCharArray()); // kSecret byte[] sig = kha.ComputeHash(Encoding.UTF8.GetBytes(AWSDate)); kha.Key = sig; // kDate sig = kha.ComputeHash(Encoding.UTF8.GetBytes(Region)); kha.Key = sig; // kRegion sig = kha.ComputeHash(Encoding.UTF8.GetBytes("s3")); kha.Key = sig; // kService sig = kha.ComputeHash(Encoding.UTF8.GetBytes("aws4_request")); kha.Key = sig; // kSigning sig = kha.ComputeHash(Encoding.UTF8.GetBytes(policyBase64)); string signature = BitConverter.ToString(sig).Replace("-", "").ToLower(); // for Authorization // debugging... //Console.WriteLine("policy: [" + policy + "]"); //Console.WriteLine("policyBase64: [" + policyBase64 + "]"); //Console.WriteLine("signature: [" + signature + "]"); // -------------------------------------------------- HttpClient httpClient = new HttpClient(); var formData = new MultipartFormDataContent(); formData.Add(new StringContent(FolderName + "/" + Info.Name), "key"); formData.Add(new StringContent("public-read"), "acl"); formData.Add(new StringContent(AWSCredential), "X-Amz-Credential"); formData.Add(new StringContent("AWS4-HMAC-SHA256"), "X-Amz-Algorithm"); formData.Add(new StringContent(signature), "X-Amz-Signature"); formData.Add(new StringContent(TimeStamp), "X-Amz-Date"); formData.Add(new StringContent(policyBase64), "Policy"); formData.Add(new StringContent(MimeType), "Content-Type"); if (Info.Extension.EndsWith("gz")) { formData.Add(new StringContent("gzip"), "Content-Encoding"); } // debugging... //Console.WriteLine("key: [" + FolderName + "/" + Info.Name + "]"); //Console.WriteLine("AWSCredential: [" + AWSCredential + "]"); //Console.WriteLine("TimeStamp: [" + TimeStamp + "]"); //Console.WriteLine("MimeType: [" + MimeType + "]"); // the file ---------------------------------------- var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(Info.FullName)); fileContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(MimeType); formData.Add(fileContent, "file", Info.Name); int adjustTimeout = (int)(Info.Length / (100 * 1000)); // [seconds] give 10 secs for each ~MB ( (10s * 1000ms) / ( 1024KB * 1024MB * 1000ms ) ) if (adjustTimeout > 100) // default timeout is 100 sec { httpClient.Timeout = TimeSpan.FromSeconds(adjustTimeout); // increase timeout } //Console.WriteLine("httpClient Timeout: [" + httpClient.Timeout + "]" ); // upload ---------------------------------------- string URL = "https://" + BucketName + ".s3.amazonaws.com/"; var response = await httpClient.PostAsync(URL, formData); if (response.IsSuccessStatusCode) { LogInformation("Upload done: " + Info.Name); } else { var contents = response.Content.ReadAsStringAsync(); var reason = Regex.Replace( /* grab inner block */ Regex.Replace(contents.Result, "<[^>]+>\n<[^>]+>([^<]+)</[^>]+>", "$1") /* strip tags */, "<([^>]+)>([^<]+)</[^>]+>", "$1 - $2\n"); //Console.WriteLine("Fail to Upload: " + Info.Name + " Header - " + response.ToString()); Console.WriteLine("Fail to Upload: " + Info.Name + "\nResponse - " + reason); throw new Exception("FAILED TO UPLOAD: " + Info.Name); } }
/// <summary> /// Initializes a new instance of the <see cref="Pbkdf2"/> class. /// </summary> /// <param name="keyedHashAlgorithm">The class that will be used to perform key derivation.</param> /// <param name="salt">The salt that will be combined with the passord during key derivation.</param> /// <param name="iterationCount">The number of iterations that will be performed to derive a new key.</param> public static Pbkdf2 New(KeyedHashAlgorithm keyedHashAlgorithm, ReadOnlySpan <byte> salt, int iterationCount) => New(keyedHashAlgorithm, salt, checked ((uint)iterationCount));
internal static bool IsSymmetricSupportedAlgorithm(string algorithm, int keySize) { bool found = false; object algorithmObject = null; try { algorithmObject = CryptoAlgorithms.GetAlgorithmFromConfig(algorithm); } catch (InvalidOperationException) { algorithmObject = null; // We swallow the exception and continue. } if (algorithmObject != null) { SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm; KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm; if (symmetricAlgorithm != null || keyedHashAlgorithm != null) { found = true; } } switch (algorithm) { case SecurityAlgorithms.DsaSha1Signature: case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaOaepKeyWrap: case SecurityAlgorithms.RsaV15KeyWrap: return(false); case SecurityAlgorithms.HmacSha1Signature: case SecurityAlgorithms.HmacSha256Signature: case SecurityAlgorithms.Psha1KeyDerivation: case SecurityAlgorithms.Psha1KeyDerivationDec2005: return(true); case SecurityAlgorithms.Aes128Encryption: case SecurityAlgorithms.Aes128KeyWrap: return(keySize == 128); case SecurityAlgorithms.Aes192Encryption: case SecurityAlgorithms.Aes192KeyWrap: return(keySize == 192); case SecurityAlgorithms.Aes256Encryption: case SecurityAlgorithms.Aes256KeyWrap: return(keySize == 256); case SecurityAlgorithms.TripleDesEncryption: case SecurityAlgorithms.TripleDesKeyWrap: return(keySize == 128 || keySize == 192); default: if (found) { return(true); } return(false); } }
/** * Computes RFC 2104-compliant HMAC signature. */ private static String Sign(String data, String key, KeyedHashAlgorithm algorithm) { Encoding encoding = new UTF8Encoding(); algorithm.Key = encoding.GetBytes(key); return Convert.ToBase64String(algorithm.ComputeHash( encoding.GetBytes(data.ToCharArray()))); }
static CryptoAlgorithmType GetAlgorithmType(string algorithm) { object algorithmObject = null; try { algorithmObject = CryptoAlgorithms.GetAlgorithmFromConfig(algorithm); } catch (InvalidOperationException) { algorithmObject = null; // We swallow the exception and continue. } if (algorithmObject != null) { SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm; KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm; if (symmetricAlgorithm != null || keyedHashAlgorithm != null) { return(CryptoAlgorithmType.Symmetric); } // NOTE: A KeyedHashAlgorithm is symmetric in nature. AsymmetricAlgorithm asymmetricAlgorithm = algorithmObject as AsymmetricAlgorithm; SignatureDescription signatureDescription = algorithmObject as SignatureDescription; if (asymmetricAlgorithm != null || signatureDescription != null) { return(CryptoAlgorithmType.Asymmetric); } return(CryptoAlgorithmType.Unknown); } switch (algorithm) { case SecurityAlgorithms.DsaSha1Signature: case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaOaepKeyWrap: case SecurityAlgorithms.RsaV15KeyWrap: return(CryptoAlgorithmType.Asymmetric); case SecurityAlgorithms.HmacSha1Signature: case SecurityAlgorithms.HmacSha256Signature: case SecurityAlgorithms.Aes128Encryption: case SecurityAlgorithms.Aes192Encryption: case SecurityAlgorithms.Aes256Encryption: case SecurityAlgorithms.TripleDesEncryption: case SecurityAlgorithms.Aes128KeyWrap: case SecurityAlgorithms.Aes192KeyWrap: case SecurityAlgorithms.Aes256KeyWrap: case SecurityAlgorithms.TripleDesKeyWrap: case SecurityAlgorithms.Psha1KeyDerivation: case SecurityAlgorithms.Psha1KeyDerivationDec2005: return(CryptoAlgorithmType.Symmetric); default: return(CryptoAlgorithmType.Unknown); } }
public static byte[] Protect(byte[] clearData, string validationKey, string decryptionKey, string decryptionAlgorithmName, string validationAlgorithmName, string primaryPurpose, params string[] specificPurposes) { // The entire operation is wrapped in a 'checked' block because any overflows should be treated as failures. checked { // These SymmetricAlgorithm instances are single-use; we wrap it in a 'using' block. using (SymmetricAlgorithm encryptionAlgorithm = CryptoConfig.CreateFromName(decryptionAlgorithmName) as SymmetricAlgorithm) { // Initialize the algorithm with the specified key and an appropriate IV encryptionAlgorithm.Key = SP800_108.DeriveKey(HexToBinary(decryptionKey), primaryPurpose, specificPurposes); // If the caller didn't ask for a predictable IV, just let the algorithm itself choose one. encryptionAlgorithm.GenerateIV(); // IV retrieval byte[] iv = encryptionAlgorithm.IV; using (MemoryStream memStream = new MemoryStream()) { memStream.Write(iv, 0, iv.Length); // At this point: // memStream := IV // Write the encrypted payload to the memory stream. using (ICryptoTransform encryptor = encryptionAlgorithm.CreateEncryptor()) { using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(clearData, 0, clearData.Length); cryptoStream.FlushFinalBlock(); // At this point: // memStream := IV || Enc(Kenc, IV, clearData) // These KeyedHashAlgorithm instances are single-use; we wrap it in a 'using' block. using (KeyedHashAlgorithm signingAlgorithm = CryptoConfig.CreateFromName(validationAlgorithmName) as KeyedHashAlgorithm) { // Initialize the algorithm with the specified key signingAlgorithm.Key = SP800_108.DeriveKey(HexToBinary(validationKey), primaryPurpose, specificPurposes); // Compute the signature byte[] signature = signingAlgorithm.ComputeHash(memStream.GetBuffer(), 0, (int)memStream.Length); // At this point: // memStream := IV || Enc(Kenc, IV, clearData) // signature := Sign(Kval, IV || Enc(Kenc, IV, clearData)) // Append the signature to the encrypted payload memStream.Write(signature, 0, signature.Length); // At this point: // memStream := IV || Enc(Kenc, IV, clearData) || Sign(Kval, IV || Enc(Kenc, IV, clearData)) // Algorithm complete byte[] protectedData = memStream.ToArray(); return(protectedData); } } } } } } }
public bool CheckSignature(KeyedHashAlgorithm macAlg) { if (macAlg == null) { throw new ArgumentNullException("macAlg"); } pkEnumerator = null; // Is the signature (over SignedInfo) valid ? Stream s = SignedInfoTransformed(); if (s == null) { return(false); } byte[] actual = macAlg.ComputeHash(s); // HMAC signature may be partial and specified by <HMACOutputLength> if (m_signature.SignedInfo.SignatureLength != null) { int length = Int32.Parse(m_signature.SignedInfo.SignatureLength); // we only support signatures with a multiple of 8 bits // and the value must match the signature length if ((length & 7) != 0) { throw new CryptographicException("Signature length must be a multiple of 8 bits."); } // SignatureLength is in bits (and we works on bytes, only in multiple of 8 bits) // and both values must match for a signature to be valid length >>= 3; if (length != m_signature.SignatureValue.Length) { throw new CryptographicException("Invalid signature length."); } // is the length "big" enough to make the signature meaningful ? // we use a minimum of 80 bits (10 bytes) or half the HMAC normal output length // e.g. HMACMD5 output 128 bits but our minimum is 80 bits (not 64 bits) int minimum = Math.Max(10, actual.Length / 2); if (length < minimum) { throw new CryptographicException("HMAC signature is too small"); } if (length < actual.Length) { byte[] trunked = new byte [length]; Buffer.BlockCopy(actual, 0, trunked, 0, length); actual = trunked; } } if (Compare(m_signature.SignatureValue, actual)) { // some parts may need to be downloaded // so where doing it last return(CheckReferenceIntegrity(m_signature.SignedInfo.References)); } return(false); }
public static void GetAlgorithms(ProtectorAlgorithm algorithmId, out SymmetricAlgorithm encryptionAlgorithm, out KeyedHashAlgorithm signingAlgorithm, out int keyDerivationIterationCount) { switch (algorithmId) { case ProtectorAlgorithm.Aes256Hmac512: encryptionAlgorithm = Aes.Create(); encryptionAlgorithm.KeySize = 256; signingAlgorithm = new HMACSHA512(); keyDerivationIterationCount = 10000; break; default: throw new ArgumentOutOfRangeException(nameof(algorithmId)); } }
private SignType(string name, KeyedHashAlgorithm algorithm) { this.Name = name; this.Algorithm = algorithm; }
internal int Encode(bool addLengthPrefix, byte[] originalTsigMac, bool isSubSequentResponse, out byte[] messageData, out byte[] newTSigMac) { PrepareEncoding(); int offset = 0; int messageOffset = offset; int maxLength = addLengthPrefix ? 2 : 0; originalTsigMac = originalTsigMac ?? new byte[] { }; if (TSigOptions != null) { if (!IsQuery) { offset += 2 + originalTsigMac.Length; maxLength += 2 + originalTsigMac.Length; } maxLength += TSigOptions.MaximumLength; } #region Get Message Length maxLength += 12; maxLength += Questions.Sum(question => question.MaximumLength); maxLength += AnswerRecords.Sum(record => record.MaximumLength); maxLength += AuthorityRecords.Sum(record => record.MaximumLength); maxLength += _additionalRecords.Sum(record => record.MaximumLength); #endregion messageData = new byte[maxLength]; int currentPosition = offset; Dictionary <DomainName, ushort> domainNames = new Dictionary <DomainName, ushort>(); EncodeUShort(messageData, ref currentPosition, TransactionID); EncodeUShort(messageData, ref currentPosition, Flags); EncodeUShort(messageData, ref currentPosition, (ushort)Questions.Count); EncodeUShort(messageData, ref currentPosition, (ushort)AnswerRecords.Count); EncodeUShort(messageData, ref currentPosition, (ushort)AuthorityRecords.Count); EncodeUShort(messageData, ref currentPosition, (ushort)_additionalRecords.Count); foreach (DnsQuestion question in Questions) { question.Encode(messageData, offset, ref currentPosition, domainNames); } foreach (DnsRecordBase record in AnswerRecords) { record.Encode(messageData, offset, ref currentPosition, domainNames); } foreach (DnsRecordBase record in AuthorityRecords) { record.Encode(messageData, offset, ref currentPosition, domainNames); } foreach (DnsRecordBase record in _additionalRecords) { record.Encode(messageData, offset, ref currentPosition, domainNames); } if (TSigOptions == null) { newTSigMac = null; } else { if (!IsQuery) { EncodeUShort(messageData, messageOffset, (ushort)originalTsigMac.Length); Buffer.BlockCopy(originalTsigMac, 0, messageData, messageOffset + 2, originalTsigMac.Length); } EncodeUShort(messageData, offset, TSigOptions.OriginalID); int tsigVariablesPosition = currentPosition; if (isSubSequentResponse) { TSigRecord.EncodeDateTime(messageData, ref tsigVariablesPosition, TSigOptions.TimeSigned); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.Fudge.TotalSeconds); } else { EncodeDomainName(messageData, offset, ref tsigVariablesPosition, TSigOptions.Name, null, false); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.RecordClass); EncodeInt(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.TimeToLive); EncodeDomainName(messageData, offset, ref tsigVariablesPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), null, false); TSigRecord.EncodeDateTime(messageData, ref tsigVariablesPosition, TSigOptions.TimeSigned); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.Fudge.TotalSeconds); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.Error); EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.OtherData.Length); EncodeByteArray(messageData, ref tsigVariablesPosition, TSigOptions.OtherData); } KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm); if ((hashAlgorithm != null) && (TSigOptions.KeyData != null) && (TSigOptions.KeyData.Length > 0)) { hashAlgorithm.Key = TSigOptions.KeyData; newTSigMac = hashAlgorithm.ComputeHash(messageData, messageOffset, tsigVariablesPosition); } else { newTSigMac = new byte[] { }; } EncodeUShort(messageData, offset, TransactionID); EncodeUShort(messageData, offset + 10, (ushort)(_additionalRecords.Count + 1)); TSigOptions.Encode(messageData, offset, ref currentPosition, domainNames, newTSigMac); if (!IsQuery) { Buffer.BlockCopy(messageData, offset, messageData, messageOffset, (currentPosition - offset)); currentPosition -= (2 + originalTsigMac.Length); } } if (addLengthPrefix) { Buffer.BlockCopy(messageData, 0, messageData, 2, currentPosition); EncodeUShort(messageData, 0, (ushort)(currentPosition)); currentPosition += 2; } return(currentPosition); }
protected override ISignatureValueSecurityElement CompletePrimarySignatureCore( SendSecurityHeaderElement[] signatureConfirmations, SecurityToken[] signedEndorsingTokens, SecurityToken[] signedTokens, SendSecurityHeaderElement[] basicTokens, bool isPrimarySignature) { if (_signedXml == null) { return(null); } SecurityTimestamp timestamp = Timestamp; if (timestamp != null) { if (timestamp.Id == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.TimestampToSignHasNoId)); } var buffer = new byte[64]; var ms = new MemoryStream(); StandardsManager.WSUtilitySpecificationVersion.WriteTimestampCanonicalForm( ms, timestamp, buffer); ms.Position = 0; AddReference("#" + timestamp.Id, ms); var reference = new System.Security.Cryptography.Xml.Reference(ms); } if ((ShouldSignToHeader) && (_signingKey != null || _signedXml.SigningKey != null) && (Version.Addressing != AddressingVersion.None)) { if (_toHeaderStream != null) { AddReference("#" + _toHeaderId, _toHeaderStream); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.TransportSecurityRequireToHeader)); } } AddSignatureReference(signatureConfirmations); if (isPrimarySignature && ShouldProtectTokens) { AddPrimaryTokenSignatureReference(ElementContainer.SourceSigningToken, SigningTokenParameters); } if (RequireMessageProtection) { throw new PlatformNotSupportedException(nameof(RequireMessageProtection)); } if (_signedXml.SignedInfo.References.Count == 0) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.NoPartsOfMessageMatchedPartsToSign), Message); } try { if (_signingKey != null) { _signedXml.ComputeSignature(_signingKey); } else { _signedXml.ComputeSignature(); } return(new SignatureValue(_signedXml.Signature)); } finally { _hashStream = null; _signingKey = null; _signedXml = null; _effectiveSignatureParts = null; } }
public ShaPrfAlgorithm() { this.hashAlgorithm = new HMACSHA256(); }
private void GetSigningAlgorithm(SecurityKey signatureKey, string algorithmName, out KeyedHashAlgorithm symmetricAlgorithm, out AsymmetricAlgorithm asymmetricAlgorithm) { symmetricAlgorithm = null; asymmetricAlgorithm = null; SymmetricSecurityKey symmetricKey = signatureKey as SymmetricSecurityKey; if (symmetricKey != null) { _signingKey = symmetricKey.GetKeyedHashAlgorithm(algorithmName); if (_signingKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format("UnableToCreateKeyedHashAlgorithm", symmetricKey, algorithmName))); } } else { AsymmetricSecurityKey asymmetricKey = signatureKey as AsymmetricSecurityKey; if (asymmetricKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.UnknownICryptoType, _signingKey))); } asymmetricAlgorithm = asymmetricKey.GetAsymmetricAlgorithm(algorithmName, privateKey: true); if (asymmetricAlgorithm == null) { //TODO MUST before checkin search and replace SR.Format(" throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format("UnableToCreateHashAlgorithmFromAsymmetricCrypto", algorithmName, asymmetricKey))); } } }
internal static bool IsSymmetricSupportedAlgorithm(string algorithm, int keySize) { bool found = false; object algorithmObject = null; try { algorithmObject = GetAlgorithmFromConfig(algorithm); } catch (InvalidOperationException) { // We swallow the exception and continue. } if (algorithmObject != null) { SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm; KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm; if (symmetricAlgorithm != null || keyedHashAlgorithm != null) { found = true; } // The reason we do not return here even when the user has provided a custom algorithm to CryptoConfig // is because we need to check if the user has overwritten an existing standard URI. } switch (algorithm) { case SecurityAlgorithms.DsaSha1Signature: case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaOaepKeyWrap: case SecurityAlgorithms.RsaV15KeyWrap: return(false); case SecurityAlgorithms.HmacSha1Signature: case SecurityAlgorithms.HmacSha256Signature: case SecurityAlgorithms.Psha1KeyDerivation: case SecurityAlgorithms.Psha1KeyDerivationDec2005: return(true); case SecurityAlgorithms.Aes128Encryption: case SecurityAlgorithms.Aes128KeyWrap: return(keySize >= 128 && keySize <= 256); case SecurityAlgorithms.Aes192Encryption: case SecurityAlgorithms.Aes192KeyWrap: return(keySize >= 192 && keySize <= 256); case SecurityAlgorithms.Aes256Encryption: case SecurityAlgorithms.Aes256KeyWrap: return(keySize == 256); case SecurityAlgorithms.TripleDesEncryption: case SecurityAlgorithms.TripleDesKeyWrap: return(keySize == 128 || keySize == 192); default: if (found) { return(true); } return(false); // We do not expect the user to map the uri of an existing standrad algorithm with say key size 128 bit // to a custom algorithm with keySize 192 bits. If he does that, we anyways make sure that we return false. } }
public CRC(KeyedHashAlgorithm keyedHash) =>
/// <summary> /// Computes an AWS4 signature for a request, ready for inclusion as an /// 'Authorization' header. /// </summary> /// <param name="headers"> /// The request headers; 'Host' and 'X-Amz-Date' will be added to this set. /// </param> /// <param name="queryParameters"> /// Any query parameters that will be added to the endpoint. The parameters /// should be specified in canonical format. /// </param> /// <param name="bodyHash"> /// Precomputed SHA256 hash of the request body content; this value should also /// be set as the header 'X-Amz-Content-SHA256' for non-streaming uploads. /// </param> /// <param name="awsAccessKey"> /// The user's AWS Access Key. /// </param> /// <param name="awsSecretKey"> /// The user's AWS Secret Key. /// </param> /// <returns> /// The computed authorization string for the request. This value needs to be set as the /// header 'Authorization' on the subsequent HTTP request. /// </returns> public string ComputeSignature(IDictionary <string, string> headers, string queryParameters, string bodyHash, string awsAccessKey, string awsSecretKey) { // first get the date and time for the subsequent request, and convert to ISO 8601 format // for use in signature generation var requestDateTime = DateTime.UtcNow; var dateTimeStamp = requestDateTime.ToString(Iso8601BasicFormat, CultureInfo.InvariantCulture); // update the headers with required 'x-amz-date' and 'host' values headers.Add(X_Amz_Date, dateTimeStamp); var hostHeader = EndpointUri.Host; if (!EndpointUri.IsDefaultPort) { hostHeader += ":" + EndpointUri.Port; } headers.Add("Host", hostHeader); // canonicalize the headers; we need the set of header names as well as the // names and values to go into the signature process var canonicalizedHeaderNames = CanonicalizeHeaderNames(headers); var canonicalizedHeaders = CanonicalizeHeaders(headers); // if any query string parameters have been supplied, canonicalize them // (note this sample assumes any required url encoding has been done already) var canonicalizedQueryParameters = string.Empty; if (!string.IsNullOrEmpty(queryParameters)) { var paramDictionary = queryParameters.Split('&').Select(p => p.Split('=')) .ToDictionary(nameval => nameval[0], nameval => nameval.Length > 1 ? nameval[1] : ""); var sb = new StringBuilder(); var paramKeys = new List <string>(paramDictionary.Keys); paramKeys.Sort(StringComparer.Ordinal); foreach (var p in paramKeys) { if (sb.Length > 0) { sb.Append("&"); } sb.AppendFormat("{0}={1}", p, paramDictionary[p]); } canonicalizedQueryParameters = sb.ToString(); } // canonicalize the various components of the request var canonicalRequest = CanonicalizeRequest(EndpointUri, HttpMethod, canonicalizedQueryParameters, canonicalizedHeaderNames, canonicalizedHeaders, bodyHash); Console.WriteLine("\nCanonicalRequest:\n{0}", canonicalRequest); // generate a hash of the canonical request, to go into signature computation var canonicalRequestHashBytes = CanonicalRequestHashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest)); // construct the string to be signed var stringToSign = new StringBuilder(); var dateStamp = requestDateTime.ToString(DateStringFormat, CultureInfo.InvariantCulture); var scope = string.Format("{0}/{1}/{2}/{3}", dateStamp, Region, Service, Terminator); stringToSign.AppendFormat("{0}-{1}\n{2}\n{3}\n", Scheme, Algorithm, dateTimeStamp, scope); stringToSign.Append(ToHexString(canonicalRequestHashBytes, true)); Console.WriteLine("\nStringToSign:\n{0}", stringToSign); // compute the signing key var kha = KeyedHashAlgorithm.Create(HMACSHA256); kha.Key = DeriveSigningKey(HMACSHA256, awsSecretKey, Region, dateStamp, Service); // compute the AWS4 signature and return it var signature = kha.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString())); var signatureString = ToHexString(signature, true); Console.WriteLine("\nSignature:\n{0}", signatureString); var authString = new StringBuilder(); authString.AppendFormat("{0}-{1} ", Scheme, Algorithm); authString.AppendFormat("Credential={0}/{1}, ", awsAccessKey, scope); authString.AppendFormat("SignedHeaders={0}, ", canonicalizedHeaderNames); authString.AppendFormat("Signature={0}", signatureString); var authorization = authString.ToString(); Console.WriteLine("\nAuthorization:\n{0}", authorization); return(authorization); }
///<summary>Enables the SA if it has been properly setup.</summary> public void Enable() { // If both parties setup simultaneous SAs we could end up calling this // twice, once as a client and the other as server, this way we only // go through the whole process once. lock (_sync) { if (_called_enable == 1) { return; } else if (_closed == 1) { throw new Exception("Cannot enable a closed SA!"); } else if (_ldhe == null) { throw new Exception("Local DHE not set."); } else if (RDHE.Value == null) { throw new Exception("Remote DHE not set."); } else if (!_hash_verified) { throw new Exception("Hash is not verified!"); } else if (TimedOut) { throw new Exception("Timed out on this one!"); } _called_enable = 1; // Deriving the DHE exchange and determing the order of keys // Specifically, we need up to 4 keys for the sender/receiver encryption/ // authentication codes. So to determine the order, we say whomever has // the smallest gets the first set of keys. byte[] rdhe = (byte[])RDHE.Value; RDHE = null; byte[] key = _dh.DecryptKeyExchange(rdhe); _dh.Clear(); _dh = null; int i = 0; while (i < _ldhe.Length && _ldhe[i] == rdhe[i]) { i++; } bool same = i == _ldhe.Length; bool first = !same && (_ldhe[i] < rdhe[i]); _ldhe = null; // Gathering our security parameter objects SecurityPolicy sp = SecurityPolicy.GetPolicy(_spi); SymmetricAlgorithm in_sa = sp.CreateSymmetricAlgorithm(); HashAlgorithm in_ha = sp.CreateHashAlgorithm(); SymmetricAlgorithm out_sa = sp.CreateSymmetricAlgorithm(); HashAlgorithm out_ha = sp.CreateHashAlgorithm(); // Generating the total key length int key_length = key.Length + 2 + (in_sa.KeySize / 8 + in_sa.BlockSize / 8) * 2; KeyedHashAlgorithm in_kha = in_ha as KeyedHashAlgorithm; KeyedHashAlgorithm out_kha = out_ha as KeyedHashAlgorithm; if (in_kha != null) { key_length += (in_kha.HashSize / 8) * 2; } // Generating a key by repeatedly hashing the DHE value and the key so far SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); int usable_key_offset = key.Length; while (key.Length < key_length) { byte[] hash = sha1.ComputeHash(key); byte[] tmp_key = new byte[hash.Length + key.Length]; key.CopyTo(tmp_key, 0); hash.CopyTo(tmp_key, key.Length); key = tmp_key; } // Like a sub-session ID (see DTLS) short epoch = (short)((key[usable_key_offset] << 8) + key[usable_key_offset + 1]); usable_key_offset += 2; byte[] key0 = new byte[in_sa.KeySize / 8]; Array.Copy(key, usable_key_offset, key0, 0, key0.Length); usable_key_offset += key0.Length; byte[] key1 = new byte[in_sa.KeySize / 8]; Array.Copy(key, usable_key_offset, key1, 0, key1.Length); usable_key_offset += key1.Length; // Same may occur if we are forming a session with ourselves! if (same) { in_sa.Key = key0; out_sa.Key = key0; } else if (first) { in_sa.Key = key0; out_sa.Key = key1; } else { out_sa.Key = key0; in_sa.Key = key1; } if (in_kha != null) { byte[] hkey0 = new byte[in_kha.HashSize / 8]; Array.Copy(key, usable_key_offset, hkey0, 0, hkey0.Length); usable_key_offset += hkey0.Length; byte[] hkey1 = new byte[in_kha.HashSize / 8]; Array.Copy(key, usable_key_offset, hkey1, 0, hkey1.Length); usable_key_offset += hkey1.Length; if (same) { in_kha.Key = hkey0; out_kha.Key = hkey0; } else if (first) { in_kha.Key = hkey0; out_kha.Key = hkey1; } else { out_kha.Key = hkey0; in_kha.Key = hkey1; } } SecurityHandler sh = new SecurityHandler(in_sa, out_sa, in_ha, out_ha, epoch); sh.Update += UpdateSH; SecurityHandler to_close = _current_sh; if (to_close != null) { to_close.Close(); } _current_sh = sh; _last_epoch = _current_epoch; _current_epoch = epoch; } // All finished set the state (which will probably fire an event) State = SAState.Active; }
/// <summary> /// Log the computation of a signature value when signing with a keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key the signature is created with</param> /// <param name="hash">hash algorithm used to digest the output</param> /// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param> internal static void LogSigning(SignedXml signedXml, KeyedHashAlgorithm key) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_SigningHmac"), key.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } }
static void GetAssemblyNameAndHashes(KeyedHashAlgorithm kha, Assembly assembly, string resourceName, out string assemblyName, out string assemblyNameHash, out string resourceNameHash) { assemblyName = assembly == currAsm ? "s" : assembly.GetName().FullName; assemblyNameHash = GetStringHash(kha, assemblyName); resourceNameHash = GetStringHash(kha, resourceName); }
/// <summary> /// 密码加密 /// </summary> /// <param name="pass"></param> /// <param name="passwordFormat">枚举PasswordFormat</param> /// <param name="salt"></param> /// <returns></returns> public static string EncodePassword(string password, PasswordFormatOptions formatOptions, string salt) { if (formatOptions == PasswordFormatOptions.Clear) { return(password); } if (formatOptions == PasswordFormatOptions.Aes) { var aes = new AESEncrypt(); return(aes.Encrypt(password, salt)); } var hm = GetHashAlgorithm(formatOptions); //Hashed:不可逆,不能解密 if (formatOptions == PasswordFormatOptions.Hashed) { byte[] bIn = Encoding.Unicode.GetBytes(password); byte[] bSalt = Convert.FromBase64String(salt); byte[] bRet = null; if (hm is KeyedHashAlgorithm) { KeyedHashAlgorithm kha = (KeyedHashAlgorithm)hm; if (kha.Key.Length == bSalt.Length) { kha.Key = bSalt; } else if (kha.Key.Length < bSalt.Length) { byte[] bKey = new byte[kha.Key.Length]; Buffer.BlockCopy(bSalt, 0, bKey, 0, bKey.Length); kha.Key = bKey; } else { byte[] bKey = new byte[kha.Key.Length]; for (int iter = 0; iter < bKey.Length;) { int len = Math.Min(bSalt.Length, bKey.Length - iter); Buffer.BlockCopy(bSalt, 0, bKey, iter, len); iter += len; } kha.Key = bKey; } bRet = kha.ComputeHash(bIn); } else { byte[] bAll = new byte[bSalt.Length + bIn.Length]; Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length); Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length); bRet = hm.ComputeHash(bAll); } return(Convert.ToBase64String(bRet)); } else { return(Convert.ToBase64String(hm.ComputeHash(Encoding.UTF8.GetBytes(password)))); } }
static string GetResourceUrl(KeyedHashAlgorithm kha, Assembly assembly, string resourceName, bool notifyScriptLoaded) { string assemblyName; string assemblyNameHash; string resourceNameHash; GetAssemblyNameAndHashes(kha, assembly, resourceName, out assemblyName, out assemblyNameHash, out resourceNameHash); bool debug = false; string url; AssemblyEmbeddedResources entry; bool includeTimeStamp = true; try { _embeddedResourcesLock.EnterUpgradeableReadLock(); entry = GetAssemblyEmbeddedResource(kha, assembly, assemblyNameHash, assemblyName); 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; CheckIfResourceIsCompositeScript(resourceName, ref includeTimeStamp); #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, includeTimeStamp); } return(url); }
/////////////////////////////////////////////////////////////////////// #region IExecute Members public override ReturnCode Execute( Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Result result ) { if (interpreter == null) { result = "invalid interpreter"; return(ReturnCode.Error); } if (arguments == null) { result = "invalid argument list"; return(ReturnCode.Error); } if (arguments.Count < 2) { result = "wrong # args: should be \"hash option ?arg ...?\""; return(ReturnCode.Error); } ReturnCode code; string subCommand = arguments[1]; bool tried = false; code = ScriptOps.TryExecuteSubCommandFromEnsemble( interpreter, this, clientData, arguments, true, false, ref subCommand, ref tried, ref result); if ((code != ReturnCode.Ok) || tried) { return(code); } // // NOTE: These algorithms are known to be supported by the // framework. // // Normal: MD5, RIPEMD160, SHA, SHA1, SHA256, SHA384, SHA512 // // Keyed: MACTripleDES // // HMAC: HMACMD5, HMACRIPEMD160, HMACSHA1, HMACSHA256, // HMACSHA384, HMACSHA512 // switch (subCommand) { case "keyed": { if (arguments.Count >= 4) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */ new Option(null, OptionFlags.MustHaveEncodingValue, Index.Invalid, Index.Invalid, "-encoding", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions( options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) <= arguments.Count) && ((argumentIndex + 3) >= arguments.Count)) { Variant value = null; bool raw = false; if (options.IsPresent("-raw")) { raw = true; } bool isFileName = false; if (options.IsPresent("-filename", ref value)) { isFileName = true; } Encoding encoding = null; if (options.IsPresent("-encoding", ref value)) { encoding = (Encoding)value.Value; } if (code == ReturnCode.Ok) { try { using (KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create( arguments[argumentIndex])) { if (algorithm != null) { algorithm.Initialize(); if ((argumentIndex + 3) == arguments.Count) { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 2], EncodingType.Binary, ref bytes, ref result); if (code == ReturnCode.Ok) { algorithm.Key = bytes; } } if (code == ReturnCode.Ok) { if (isFileName) { Stream stream = null; try { code = RuntimeOps.NewStream( interpreter, arguments[argumentIndex + 1], FileMode.Open, FileAccess.Read, ref stream, ref result); if (code == ReturnCode.Ok) { if (raw) { result = new ByteList( algorithm.ComputeHash(stream)); } else { result = FormatOps.Hash( algorithm.ComputeHash(stream)); } } } finally { if (stream != null) { stream.Close(); stream = null; } } } else { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 1], EncodingType.Binary, ref bytes, ref result); if (raw) { result = new ByteList( algorithm.ComputeHash(bytes)); } else { result = FormatOps.Hash( algorithm.ComputeHash(bytes)); } } } } else { result = String.Format( "unsupported keyed hash algorithm \"{0}\"", arguments[argumentIndex]); code = ReturnCode.Error; } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); result = e; code = ReturnCode.Error; } } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption( options, arguments[argumentIndex]); } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"", this.Name, subCommand); } code = ReturnCode.Error; } } } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"", this.Name, subCommand); code = ReturnCode.Error; } break; } case "list": { if ((arguments.Count == 2) || (arguments.Count == 3)) { string type = null; if (arguments.Count == 3) { type = arguments[2]; } switch (type) { case null: case "all": { StringList list = new StringList(); lock (syncRoot) { if (defaultAlgorithms != null) { list.AddRange(defaultAlgorithms); } } if (keyedHashAlgorithmNames != null) { foreach (string hashAlgorithmName in keyedHashAlgorithmNames) { list.Add(StringList.MakeList("keyed", hashAlgorithmName)); } } if (macHashAlgorithmNames != null) { foreach (string hashAlgorithmName in macHashAlgorithmNames) { list.Add(StringList.MakeList("mac", hashAlgorithmName)); } } if (normalHashAlgorithmNames != null) { foreach (string hashAlgorithmName in normalHashAlgorithmNames) { list.Add(StringList.MakeList("normal", hashAlgorithmName)); } } result = list; break; } case "default": { lock (syncRoot) { result = (defaultAlgorithms != null) ? new StringList(defaultAlgorithms) : null; } break; } case "keyed": { result = (keyedHashAlgorithmNames != null) ? new StringList(keyedHashAlgorithmNames) : null; break; } case "mac": { result = (macHashAlgorithmNames != null) ? new StringList(macHashAlgorithmNames) : null; break; } case "normal": { result = (normalHashAlgorithmNames != null) ? new StringList(normalHashAlgorithmNames) : null; break; } default: { result = "unknown algorithm list, must be: all, default, keyed, mac, or normal"; code = ReturnCode.Error; break; } } } else { result = String.Format( "wrong # args: should be \"{0} {1} ?type?\"", this.Name, subCommand); code = ReturnCode.Error; } break; } case "mac": { if (arguments.Count >= 4) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */ new Option(null, OptionFlags.MustHaveEncodingValue, Index.Invalid, Index.Invalid, "-encoding", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions( options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) <= arguments.Count) && ((argumentIndex + 3) >= arguments.Count)) { Variant value = null; bool raw = false; if (options.IsPresent("-raw")) { raw = true; } bool isFileName = false; if (options.IsPresent("-filename", ref value)) { isFileName = true; } Encoding encoding = null; if (options.IsPresent("-encoding", ref value)) { encoding = (Encoding)value.Value; } if (code == ReturnCode.Ok) { try { using (HMAC algorithm = HMAC.Create( arguments[argumentIndex])) { if (algorithm != null) { algorithm.Initialize(); if ((argumentIndex + 3) == arguments.Count) { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 2], EncodingType.Binary, ref bytes, ref result); if (code == ReturnCode.Ok) { algorithm.Key = bytes; } } if (code == ReturnCode.Ok) { if (isFileName) { Stream stream = null; try { code = RuntimeOps.NewStream( interpreter, arguments[argumentIndex + 1], FileMode.Open, FileAccess.Read, ref stream, ref result); if (code == ReturnCode.Ok) { if (raw) { result = new ByteList( algorithm.ComputeHash(stream)); } else { result = FormatOps.Hash( algorithm.ComputeHash(stream)); } } } finally { if (stream != null) { stream.Close(); stream = null; } } } else { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 1], EncodingType.Binary, ref bytes, ref result); if (raw) { result = new ByteList( algorithm.ComputeHash(bytes)); } else { result = FormatOps.Hash( algorithm.ComputeHash(bytes)); } } } } else { result = String.Format( "unsupported hmac algorithm \"{0}\"", arguments[argumentIndex]); code = ReturnCode.Error; } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); result = e; code = ReturnCode.Error; } } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption( options, arguments[argumentIndex]); } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"", this.Name, subCommand); } code = ReturnCode.Error; } } } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"", this.Name, subCommand); code = ReturnCode.Error; } break; } case "normal": { if (arguments.Count >= 4) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */ new Option(null, OptionFlags.MustHaveEncodingValue, Index.Invalid, Index.Invalid, "-encoding", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions( options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) == arguments.Count)) { Variant value = null; bool raw = false; if (options.IsPresent("-raw")) { raw = true; } bool isFileName = false; if (options.IsPresent("-filename", ref value)) { isFileName = true; } Encoding encoding = null; if (options.IsPresent("-encoding", ref value)) { encoding = (Encoding)value.Value; } if (code == ReturnCode.Ok) { try { using (HashAlgorithm algorithm = HashAlgorithm.Create( arguments[argumentIndex])) { if (algorithm != null) { algorithm.Initialize(); if (isFileName) { Stream stream = null; try { code = RuntimeOps.NewStream( interpreter, arguments[argumentIndex + 1], FileMode.Open, FileAccess.Read, ref stream, ref result); if (code == ReturnCode.Ok) { if (raw) { result = new ByteList( algorithm.ComputeHash(stream)); } else { result = FormatOps.Hash( algorithm.ComputeHash(stream)); } } } finally { if (stream != null) { stream.Close(); stream = null; } } } else { byte[] bytes = null; code = StringOps.GetBytes( encoding, arguments[argumentIndex + 1], EncodingType.Binary, ref bytes, ref result); if (code == ReturnCode.Ok) { if (raw) { result = new ByteList( algorithm.ComputeHash(bytes)); } else { result = FormatOps.Hash( algorithm.ComputeHash(bytes)); } } } } else { result = String.Format( "unsupported hash algorithm \"{0}\"", arguments[argumentIndex]); code = ReturnCode.Error; } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); result = e; code = ReturnCode.Error; } } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption( options, arguments[argumentIndex]); } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string\"", this.Name, subCommand); } code = ReturnCode.Error; } } } else { result = String.Format( "wrong # args: should be \"{0} {1} ?options? algorithm string\"", this.Name, subCommand); code = ReturnCode.Error; } break; } default: { result = ScriptOps.BadSubCommand( interpreter, null, null, subCommand, this, null, null); code = ReturnCode.Error; break; } } return(code); }
private string EncodePassword(string pass, int passwordFormat, string salt) { byte[] buffer5; if (passwordFormat == 0) { return(pass); } byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] inArray = null; if (passwordFormat == 1) { HashAlgorithm hashAlgorithm = this.GetHashAlgorithm(); if (hashAlgorithm is KeyedHashAlgorithm) { KeyedHashAlgorithm algorithm2 = (KeyedHashAlgorithm)hashAlgorithm; if (algorithm2.Key.Length == src.Length) { algorithm2.Key = src; } else { byte[] buffer4; if (algorithm2.Key.Length < src.Length) { buffer4 = new byte[algorithm2.Key.Length]; Buffer.BlockCopy(src, 0, buffer4, 0, buffer4.Length); algorithm2.Key = buffer4; } else { int num2; buffer4 = new byte[algorithm2.Key.Length]; for (int i = 0; i < buffer4.Length; i += num2) { num2 = Math.Min(src.Length, buffer4.Length - i); Buffer.BlockCopy(src, 0, buffer4, i, num2); } algorithm2.Key = buffer4; } } inArray = algorithm2.ComputeHash(bytes); } else { buffer5 = new byte[src.Length + bytes.Length]; Buffer.BlockCopy(src, 0, buffer5, 0, src.Length); Buffer.BlockCopy(bytes, 0, buffer5, src.Length, bytes.Length); inArray = hashAlgorithm.ComputeHash(buffer5); } } //else //{ // buffer5 = new byte[src.Length + bytes.Length]; // Buffer.BlockCopy(src, 0, buffer5, 0, src.Length); // Buffer.BlockCopy(bytes, 0, buffer5, src.Length, bytes.Length); // inArray = this.EncryptPassword(buffer5); //} return(Convert.ToBase64String(inArray)); }
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); }
internal static string CreateSignature(string headerEncoded, string payloadEncoded, KeyedHashAlgorithm algorithm) { string data = headerEncoded + "." + payloadEncoded; byte[] encrypted = algorithm.ComputeHash(Encoding.UTF8.GetBytes(data)); return(Encoding.UTF8.GetString(encrypted)); }
private ReturnCode ValidateTSig(byte[] resultData, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac) { byte[] keyData; if ((TSigOptions.Algorithm == TSigAlgorithm.Unknown) || (tsigKeySelector == null) || ((keyData = tsigKeySelector(TSigOptions.Algorithm, TSigOptions.Name)) == null)) { return(ReturnCode.BadKey); } else if (((TSigOptions.TimeSigned - TSigOptions.Fudge) > DateTime.Now) || ((TSigOptions.TimeSigned + TSigOptions.Fudge) < DateTime.Now)) { return(ReturnCode.BadTime); } else if ((TSigOptions.Mac == null) || (TSigOptions.Mac.Length == 0)) { return(ReturnCode.BadSig); } else { TSigOptions.KeyData = keyData; // maxLength for the buffer to validate: Original (unsigned) dns message and encoded TSigOptions // because of compression of keyname, the size of the signed message can not be used int maxLength = TSigOptions.StartPosition + TSigOptions.MaximumLength; if (originalMac != null) { // add length of mac on responses. MacSize not neccessary, this field is allready included in the size of the tsig options maxLength += originalMac.Length; } byte[] validationBuffer = new byte[maxLength]; int currentPosition = 0; // original mac if neccessary if ((originalMac != null) && (originalMac.Length > 0)) { EncodeUShort(validationBuffer, ref currentPosition, (ushort)originalMac.Length); EncodeByteArray(validationBuffer, ref currentPosition, originalMac); } // original unsiged buffer Buffer.BlockCopy(resultData, 0, validationBuffer, currentPosition, TSigOptions.StartPosition); // update original transaction id and ar count in message EncodeUShort(validationBuffer, currentPosition, TSigOptions.OriginalID); EncodeUShort(validationBuffer, currentPosition + 10, (ushort)_additionalRecords.Count); currentPosition += TSigOptions.StartPosition; // TSig Variables EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigOptions.Name, null, false); EncodeUShort(validationBuffer, ref currentPosition, (ushort)TSigOptions.RecordClass); EncodeInt(validationBuffer, ref currentPosition, (ushort)TSigOptions.TimeToLive); EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), null, false); TSigRecord.EncodeDateTime(validationBuffer, ref currentPosition, TSigOptions.TimeSigned); EncodeUShort(validationBuffer, ref currentPosition, (ushort)TSigOptions.Fudge.TotalSeconds); EncodeUShort(validationBuffer, ref currentPosition, (ushort)TSigOptions.Error); EncodeUShort(validationBuffer, ref currentPosition, (ushort)TSigOptions.OtherData.Length); EncodeByteArray(validationBuffer, ref currentPosition, TSigOptions.OtherData); // Validate MAC KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm); hashAlgorithm.Key = keyData; return((hashAlgorithm.ComputeHash(validationBuffer, 0, currentPosition).SequenceEqual(TSigOptions.Mac)) ? ReturnCode.NoError : ReturnCode.BadSig); } }
internal static JWTToken isValid <TPayload>(string token, KeyedHashAlgorithm algorithm, JWTAcceptedValues values) where TPayload : JWTPayload { List <string> tokenParts = new List <string>(); try { tokenParts = token.Split('.').ToList(); } catch { throw new JWTExceptions.JWTSplitException("Token split exception"); } if (tokenParts.Count != 3) { throw new JWTExceptions.JWTSplitException("Token doesnot have 3 parts"); } string currentSignature = ""; try { currentSignature = JWTTokenHelpers.CreateSignature(tokenParts[0], tokenParts[1], algorithm); currentSignature = GetBase64URLEncoded(currentSignature); string oldSignature = tokenParts[2]; if (oldSignature == null || !oldSignature.Equals(currentSignature)) { throw new JWTExceptions.JWTSignatureException("Signature invalid"); } } catch { throw new JWTExceptions.JWTSignatureException("Signature invalid"); } try { for (int i = 0; i < 2; i++) { tokenParts[i] = GetBase64URLDecoded(tokenParts[i]); } } catch { throw new JWTExceptions.JWTDecodingExceptions("Token parts are not decodable"); } JWTHeader header = new JWTHeader(); TPayload payload; try { header = JSONDesialize <JWTHeader>(tokenParts[0]); payload = JSONDesialize <TPayload>(tokenParts[1]); } catch { throw new JWTExceptions.JWTDeserializeException("Data not parsable"); } if (payload != null) { if (payload.ExpiryTime.Subtract(DateTime.Now) > values.ExpiryDuration) { throw new JWTExceptions.JWTExpiredException("JWT expired"); } else if (payload.IpAddress == null || !payload.IpAddress.Equals(values.IpAddress)) { throw new JWTExceptions.JWTIpAddressException("IP Address mismatch"); } else if (payload.Audience == null || !payload.Audience.Equals(values.Audience)) { throw new JWTExceptions.JWTIncorrectAudienceException("Audience incorrect"); } else if (payload.Issuer == null || !payload.Issuer.Equals(values.Issuer)) { throw new JWTExceptions.JWTIssuerIncorrectException("Issuer mismatch"); } else { return(new JWTToken() { Header = header, Payload = payload, Token = token }); } } else { throw new JWTExceptions.JWTPayloadEmptyException("Payload null"); } }
private void createDecryptionCipher() { // Create and configure the symmetric algorithm switch (this.cipherAlgorithmType) { case CipherAlgorithmType.Des: this.decryptionAlgorithm = DES.Create(); break; case CipherAlgorithmType.Rc2: this.decryptionAlgorithm = RC2.Create(); break; case CipherAlgorithmType.Rc4: this.decryptionAlgorithm = new ARC4Managed(); break; case CipherAlgorithmType.TripleDes: this.decryptionAlgorithm = TripleDES.Create(); break; case CipherAlgorithmType.Rijndael: this.decryptionAlgorithm = Rijndael.Create(); break; } // If it's a block cipher if (this.cipherMode == CipherMode.CBC) { // Configure encrypt algorithm this.decryptionAlgorithm.Mode = this.cipherMode; this.decryptionAlgorithm.Padding = PaddingMode.None; this.decryptionAlgorithm.KeySize = this.expandedKeyMaterialSize * 8; this.decryptionAlgorithm.BlockSize = this.blockSize * 8; } // Set the key and IV for the algorithm if (this.context is ClientContext) { this.decryptionAlgorithm.Key = this.context.ServerWriteKey; this.decryptionAlgorithm.IV = this.context.ServerWriteIV; } else { this.decryptionAlgorithm.Key = this.context.ClientWriteKey; this.decryptionAlgorithm.IV = this.context.ClientWriteIV; } // Create decryption cipher this.decryptionCipher = this.decryptionAlgorithm.CreateDecryptor(); // Create the HMAC if (this.context is ClientContext) { this.serverHMAC = new M.HMAC( this.HashAlgorithmName, this.context.Negotiating.ServerWriteMAC); } else { this.clientHMAC = new M.HMAC( this.HashAlgorithmName, this.context.Negotiating.ClientWriteMAC); } }
private SignType(int versionID, KeyedHashAlgorithm algorithm) { this.VersionID = versionID; this.Algorithm = algorithm; }