static string calcHmac( string data ) { byte[] key = Encoding.ASCII.GetBytes(AUTH_TOKEN); HMACSHA256 myhmacsha256 = new HMACSHA256(key); byte[] byteArray = Encoding.ASCII.GetBytes(data); MemoryStream stream = new MemoryStream(byteArray); string result = myhmacsha256.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}",e), s => s ); Console.WriteLine(result); return result; }
static void Main() { var data = "testtesttest"; var secretKey = "secretkey"; // Initialize the keyed hash object using the secret key as the key HMACSHA256 hashObject = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey)); // Computes the signature by hashing the salt with the secret key as the key var signature = hashObject.ComputeHash(Encoding.UTF8.GetBytes(data)); // Base 64 Encode var encodedSignature = Convert.ToBase64String(signature); // URLEncode // encodedSignature = System.Web.HttpUtility.UrlEncode(encodedSignature); Console.WriteLine("Voila! A signature: " + encodedSignature); Console.ReadKey(); }
public static string HMACSHA256Encode(string input, string key) { byte[] k = Encoding.ASCII.GetBytes (key); HMACSHA256 myhmacsha256 = new HMACSHA256 (k); byte[] byteArray = Encoding.ASCII.GetBytes (input); using (MemoryStream stream = new MemoryStream (byteArray)){ return byteToHex(myhmacsha256.ComputeHash (stream)); } }
string container = "ogp"; //Storage container created on azure portal called "test" #endregion Fields #region Methods private static String SignThis(String StringToSign, string Key, string Account) { String signature = string.Empty; byte[] unicodeKey = Convert.FromBase64String(Key); using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey)) { Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(StringToSign); signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac)); } String authorizationHeader = String.Format( CultureInfo.InvariantCulture, "{0} {1}:{2}", "SharedKeyLite", Account, signature); return authorizationHeader; }
public static string getHashSha256(string text, string mail) { byte[] key = Encoding.UTF8.GetBytes(mail); byte[] bytes = Encoding.UTF8.GetBytes(text); HMACSHA256 hashstring = new HMACSHA256(key); byte[] hash = hashstring.ComputeHash(bytes); string hashString = string.Empty; foreach (byte x in hash) { hashString += String.Format("{0:x2}", x); } return hashString; }
/// <summary> /// Code for generating of SAS token for authorization with Service Bus /// </summary> /// <param name="resourceUri"></param> /// <param name="keyName"></param> /// <param name="key"></param> /// <returns></returns> private static string createToken(string resourceUri, string keyName, string key) { TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1); var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 3600); //EXPIRES in 1h string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry; HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)); var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign))); var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName); return sasToken; }
public byte[] Decrypt(byte[] payload) { byte[] payloadToSign = _ByteSlice(payload, 0, payload.Length - _hashLength); byte[] serverHmac = _ByteSlice(payload, payload.Length - _hashLength, payload.Length); HMACSHA256 hashAlgorithm = new HMACSHA256(_macKey); byte[] clientHmac = hashAlgorithm.ComputeHash(payloadToSign); if (!ByteEqual(serverHmac, clientHmac)) { throw new System.ArgumentException("Bad Signature"); } byte[] eBytes = _ByteSlice(payload, SEQ_LEN, payload.Length - _hashLength); byte[] dBytes = new byte[eBytes.Length]; // seq is always 0 from server uint seq = 0; _Ctr(seq, eBytes, dBytes, 0); return dBytes; }
/// <summary> /// Computes the Client Assertion portion of the JWT /// </summary> /// <param name="header">The JSON Web Token header</param> /// <param name="claimSet">The JSON Web Token claim set</param> /// <param name="clientSecret">The client's secret</param> /// <returns>The assertion</returns> public string BuildAssertion(JWTHeader header, JWTClaimSet claimSet, string clientSecret) { // Serialize the header and claimSet string serializedHeader = JsonConvert.SerializeObject(header); string serializedClaimSet = JsonConvert.SerializeObject(claimSet); // Base64Encode the header and claimSet string encodedHeader = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(serializedHeader)); string encodedClaimSet = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(serializedClaimSet)); // Concatenate the header and the claims separated with a '.': [header].[claims] string message = string.Join(".", encodedHeader, encodedClaimSet); // Apply an HMAC/SHA-256 hash* to the concatenated content using the Client Secret as the key HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(clientSecret)); byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message)); // Base64Encode the result of the hash string signature = Convert.ToBase64String(hash); // Combine the encoded elements as follows [header].[claims].[hash] string assertion = string.Join(".", encodedHeader, encodedClaimSet, signature); return assertion; }
public string GetSignature(string secretAccessKey, string host = "ecs.amazonaws.jp", string path = "/onca/xml") { var queryStr = this.ToQueryString(); var strToSign = string.Format("GET\n{0}\n{1}\n{2}", host, path, queryStr); var toSign = Encoding.UTF8.GetBytes(strToSign); var signer = new HMACSHA256(Encoding.UTF8.GetBytes(secretAccessKey)); var sigBytes = signer.ComputeHash(toSign); var signature = CustomUrlEncode(Convert.ToBase64String(sigBytes)); return signature; }
/// <summary> /// Singature mapping which corresponds to php's 'hash_hmac' /// </summary> /// <param name="message"></param> /// <returns></returns> private string GetSignature(string message) { var secretKeyBytes = encoding.GetBytes(ApiSecret); //using the bytemap using (var hmacsha256 = new HMACSHA256(secretKeyBytes)) { hmacsha256.ComputeHash(encoding.GetBytes(message)); //Return the corresponding string for the signature request. return hmacsha256.Hash.Aggregate(string.Empty, (current, b) => current + b.ToString("X2")).ToLower(); } }
public byte[] Encrypt(byte[] payload) { _sequence++; byte[] seqBytes = BitConverter.GetBytes(IPAddress.NetworkToHostOrder((int)_sequence)); byte[] cipherBytes = new byte[payload.Length]; byte[] outpacket = new byte[cipherBytes.Length + SEQ_LEN + _hashLength]; _Ctr(_sequence, payload, cipherBytes, 0); Buffer.BlockCopy(seqBytes, 0, outpacket, 0, SEQ_LEN); Buffer.BlockCopy(cipherBytes, 0, outpacket, SEQ_LEN, cipherBytes.Length); byte[] payloadToSign = _ByteSlice(outpacket, 0, outpacket.Length - _hashLength); HMACSHA256 hashAlgorithm = new HMACSHA256(_macKey); byte[] hmac = hashAlgorithm.ComputeHash(payloadToSign); Buffer.BlockCopy(hmac, 0, outpacket, outpacket.Length - _hashLength, _hashLength); byte[] epacket = new byte[_sessionId.Length + SEQ_LEN + outpacket.Length]; Buffer.BlockCopy(_sessionId, 0, epacket, 0, _sessionId.Length); Buffer.BlockCopy(seqBytes, 0, epacket, _sessionId.Length, SEQ_LEN); Buffer.BlockCopy(outpacket, 0, epacket, _sessionId.Length + SEQ_LEN, outpacket.Length); return epacket; }
public static byte[] GetHmacSignatureInBytes(byte[] data, byte[] sharedSecret) { HMACSHA256 hash = new HMACSHA256(); hash.Key = sharedSecret; byte[] hashedValue = hash.ComputeHash(data); return hashedValue; }
private SimpleWebToken CreateToken(ClaimCollection claims, string issuerName, string appliesTo) { appliesTo = appliesTo.ToLower(); var sKey = ConfigurationManager.AppSettings[appliesTo]; if (String.IsNullOrEmpty(sKey)) { //check if appliesTo failed to find the key because it's missing a trailing slash, //or because it has a trailing slash which shouldn't be there //and act accordingly (and try again): if (!appliesTo.EndsWith("/")) appliesTo += "/"; else appliesTo = VirtualPathUtility.RemoveTrailingSlash(appliesTo); sKey = ConfigurationManager.AppSettings[appliesTo]; if (String.IsNullOrEmpty(sKey)) throw new ConfigurationException(String.Format("Missing symmetric key for \"{0}\".", appliesTo)); } var key = this.HexToByte(sKey); var sb = new StringBuilder(); foreach (var c in claims) sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(c.ClaimType), HttpUtility.UrlEncode(c.Value)); double lifeTimeInSeconds = 3600; sb .AppendFormat("TokenId={0}&", HttpUtility.UrlEncode(Guid.NewGuid().ToString())) .AppendFormat("Issuer={0}&", HttpUtility.UrlEncode(issuerName)) .AppendFormat("Audience={0}&", HttpUtility.UrlEncode(appliesTo)) .AppendFormat("ExpiresOn={0:0}", (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds + lifeTimeInSeconds); var unsignedToken = sb.ToString(); var hmac = new HMACSHA256(key); var sig = hmac.ComputeHash(Encoding.ASCII.GetBytes(unsignedToken)); string signedToken = String.Format("{0}&HMACSHA256={1}", unsignedToken, HttpUtility.UrlEncode(Convert.ToBase64String(sig))); return new SimpleWebToken(signedToken); }
/// <inheritdoc /> public sealed override async Task <InputFormatterResult> ReadRequestBodyAsync( InputFormatterContext context, Encoding encoding) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } var httpContext = context.HttpContext; var inputStream = httpContext.Request.Body; ApplicationPayload?model; try { using var inputStreamReader = new StreamReader(inputStream); var inputJsonString = await inputStreamReader.ReadToEndAsync(); // Determine options name to use (in case multiple are registered) var options = httpContext.Request.RouteValues.TryGetValue(RouteKeyConstants.OptionsName, out object optionsName) ? _options.Get(optionsName.ToString()) : _options.CurrentValue; // Verify signature if (options.ValidatePayloadSignature) { if (!string.IsNullOrEmpty(options.EndpointSigningKey)) { var secret = Encoding.ASCII.GetBytes(options.EndpointSigningKey); var signatureBytes = Encoding.UTF8.GetBytes(context.HttpContext.Request.Headers[HeaderSpaceTimestamp] + ":" + inputJsonString); using var hmSha1 = new HMACSHA256(secret); var signatureHash = hmSha1.ComputeHash(signatureBytes); var signatureString = ToHexString(signatureHash); if (!signatureString.Equals(context.HttpContext.Request.Headers[HeaderSpaceSignature])) { throw new InvalidOperationException("The webhook signature does not match the webhook payload. Make sure the endpoint signing key is configured correctly in your Space organization, and the current application."); } } else { _logger.LogWarning(nameof(SpaceWebHookOptions.ValidatePayloadSignature) + " is enabled, but no " + nameof(SpaceWebHookOptions.EndpointSigningKey) + " is configured. Skipping payload signature validation."); } } // Deserialize model model = JsonSerializer.Deserialize(inputJsonString, context.ModelType, _jsonSerializerOptions) as ApplicationPayload; if (model != null) { PropagatePropertyAccessPathHelper.SetAccessPathForValue(string.Empty, false, model); } // Verify payload if (options.ValidatePayloadVerificationToken) { var payloadVerificationTokenValue = GetPayloadVerificationTokenValue(model); if (!string.IsNullOrEmpty(payloadVerificationTokenValue)) { if (payloadVerificationTokenValue != options.EndpointVerificationToken) { throw new InvalidOperationException( "The webhook verification token does not your configured verification token. Make sure the endpoint verification token is configured correctly in your Space organization, and the current application."); } } else { _logger.LogWarning(nameof(SpaceWebHookOptions.ValidatePayloadVerificationToken) + " is enabled, but no " + nameof(SpaceWebHookOptions.EndpointVerificationToken) + " is configured. Skipping verification token validation."); } } } catch (JsonException jsonException) { var path = jsonException.Path; var formatterException = new InputFormatterException(jsonException.Message, jsonException); context.ModelState.TryAddModelError(path, formatterException, context.Metadata); Log.JsonInputException(_logger, jsonException); return(await InputFormatterResult.FailureAsync()); } catch (Exception exception) when(exception is FormatException || exception is OverflowException) { context.ModelState.TryAddModelError(string.Empty, exception, context.Metadata); Log.JsonInputException(_logger, exception); return(await InputFormatterResult.FailureAsync()); } if (model == null && !context.TreatEmptyInputAsDefaultValue) { return(await InputFormatterResult.NoValueAsync()); } Log.JsonInputSuccess(_logger, context.ModelType); return(await InputFormatterResult.SuccessAsync(model)); }
public static byte[] SignHMACSHA256(String key, byte[] data) { HMACSHA256 hashMaker = new HMACSHA256(Encoding.ASCII.GetBytes(key)); return(hashMaker.ComputeHash(data)); }
private byte[] sign(byte[] key, string data) { var hashAlgorithm = new HMACSHA256(key); return(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(data))); }
static JsonWebToken() { HashAlgorithms = new Dictionary <JwtHashAlgorithm, Func <byte[], byte[], byte[]> > { { JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return(sha.ComputeHash(value)); } } }, { JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return(sha.ComputeHash(value)); } } }, { JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return(sha.ComputeHash(value)); } } } }; }
public static TokenInfo ParseToken(string token, bool validateHmac = true) { TokenInfo ti = new TokenInfo(); var parts = token.Split('.'); var headerBase64 = parts[0]; var bodyBase64 = parts[1]; var signature = parts[2]; // parse the header and body into objects var headerJson = Encoding.UTF8.GetString(JwtUtil.Base64UrlDecode(headerBase64)); var headerData = JObject.Parse(headerJson); var bodyJson = Encoding.UTF8.GetString(JwtUtil.Base64UrlDecode(bodyBase64)); var bodyData = JObject.Parse(bodyJson); // verify algorithm var algorithm = (string)headerData["alg"]; if (algorithm != "HS256") { throw new NotSupportedException("Only HS256 is supported for this algorithm."); } if (validateHmac) { // verify signature byte[] bytesToSign = GetBytes(string.Join(".", headerBase64, bodyBase64)); var alg = new HMACSHA256(Convert.FromBase64String(HmacSecret)); var hash = alg.ComputeHash(bytesToSign); var computedSig = JwtUtil.Base64UrlEncode(hash); if (computedSig != signature) { throw new AuthenticationException("Invalid JWT signature"); } } // verify expiration var expirationUtc = JwtUtil.ConvertFromUnixTimestamp((long)bodyData["exp"]); if (DateTime.UtcNow > expirationUtc) { throw new AuthenticationException("Token has expired"); } // verify audience var jwtAudience = (string)bodyData["aud"]; if (jwtAudience != JwtManager.AceAudience) { throw new AuthenticationException($"Invalid audience '{jwtAudience}'. Expected '{JwtManager.AceAudience}'."); } ti.Name = (string)bodyData[ClaimTypes.Name] ?? (string)bodyData["unique_name"]; var roles = bodyData[ClaimTypes.Role] ?? bodyData["role"]; if (roles != null) { if (roles.HasValues) { ti.Roles = roles.Select(r => (string)r).ToList(); } else { ti.Roles = new List <string>() { (string)roles } }; } string accountGuid = (string)bodyData[ClaimTypes.NameIdentifier] ?? (string)bodyData["nameid"]; ti.AccountGuid = Guid.Parse(accountGuid); ti.AccountId = uint.Parse((string)bodyData["account_id"]); ti.IssuingServer = (string)bodyData["issuing_server"]; return(ti); }
/// <summary> /// This method is used to encrypt the specified plain data /// </summary> /// <param name="plainData">Contains the plain text data to encrypt.</param> /// <param name="cryptKey">Contains the crypto key data.</param> /// <param name="authKey">Contains the authorize key data.</param> /// <param name="nonSecretPayload">Contains additional salt non-secret payload data.</param> /// <returns>Returns a byte array containing the encrypted data stream.</returns> public static byte[] Encrypt(this byte[] plainData, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { // if no crypt key or the length is invalid if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.CryptoKeyLengthErrorText, KeyBitSize), nameof(cryptKey)); } if (authKey == null || authKey.Length != KeyBitSize / 8) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.CryptoAuthKeyLengthErrorText, KeyBitSize), nameof(authKey)); } if (plainData == null || plainData.Length == 0) { throw new ArgumentNullException(nameof(plainData), Resources.CryptoMustSpecifyTextToEncryptErrorText); } // non-secret payload nonSecretPayload = nonSecretPayload ?? Array.Empty <byte>(); byte[] cipherText; byte[] iv; byte[] results; using (var aes = new AesCryptoServiceProvider { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { // Use a random IV aes.GenerateIV(); iv = aes.IV; // create a new AES encryption engine... using (ICryptoTransform crypto = aes.CreateEncryptor(cryptKey, iv)) { // create a new memory stream to write output to... using (var cipherStream = new MemoryStream()) { // create a new crypto stream for encryption using (var cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write)) { // create a new binary writer... using (var binaryWriter = new BinaryWriter(cryptoStream)) { // Encrypt Data binaryWriter.Write(plainData); } } // return encrypted results from stream cipherText = cipherStream.ToArray(); } } } // Assemble encrypted message and add authentication using (var hmac = new HMACSHA256(authKey)) { // create a new memory stream... using (var encryptedStream = new MemoryStream()) { // create a new binary writer... using (var binaryWriter = new BinaryWriter(encryptedStream)) { // Prefix non-secret payload if any binaryWriter.Write(nonSecretPayload); // Prefix IV binaryWriter.Write(iv); // Write encrypted data binaryWriter.Write(cipherText); binaryWriter.Flush(); // Authenticate all data var hashTag = hmac.ComputeHash(encryptedStream.ToArray()); // Append hashed tag binaryWriter.Write(hashTag); } // the final format is as follows: [nonSecretPayload:{crypt-salt}{auth-salt}][IV][CipherText][HMAC-256] results = encryptedStream.ToArray(); } } return(results); }
public static byte[] HashStringToBytes(string str_to_hash) { HMACSHA256 hs256 = new HMACSHA256(Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["UserSalt"])); return hs256.ComputeHash(StringToBytes(str_to_hash)); }
/* * * URL=https://api.bitso.com/v3/balance/ * API_KEY="BITSO_KEY" * API_SECRET="BITSO_SECRET" * DNONCE=$(date +%s) * HTTPmethod=GET * JSONPayload="" * RequestPath="/v3/balance/" * SIGNATURE=$(echo -n $DNONCE$HTTPmethod$RequestPath$JSONPayload | openssl dgst -hex -sha256 -hmac $API_SECRET ) * AUTH_HEADER="Bitso $API_KEY:$DNONCE:$SIGNATURE" * http GET $URL Authorization:"$AUTH_HEADER" */ public bool bitsoLogin() { bool bRegresa = false; string sQuery = string.Empty; string SIGNATURE = string.Empty; string AUTH_HEADER = string.Empty; string MESSAGE = string.Empty; cb.RequestPath = "/v3/balance/"; cb.url = "https://api.bitso.com/v3/balance/"; //cb.url = "https://bitso.com/v3/balance/"; //Dataos obtenido de una clase que al momento de la instancia se pasan los parametros. MESSAGE = cb.dnoce + cb.HTTPmethod + cb.RequestPath + cb.JSONPayload; ASCIIEncoding encoder = new ASCIIEncoding(); //Byte[] code = encoder.GetBytes(cb.api_secret); // se obtiene de los parametros de la clase. HMACSHA256 hmSha256 = new HMACSHA256(encoder.GetBytes(cb.api_secret)); //---code //Byte[] hashMe = encoder.GetBytes(MESSAGE);// byte[] hm256Byte = hmSha256.ComputeHash(encoder.GetBytes(MESSAGE)); //--hashMe SIGNATURE = ToHexString(hm256Byte); //Aqui tengo mi sospecha que no se este generando como se deben. // SIGNATURE = "c96a3973409a5c122d0eb00ca27679edbe4faafb460564b626b76c5431f74150"; AUTH_HEADER = "Bitso " + cb.api_key + ":" + cb.dnoce + ":" + SIGNATURE; CLoadMoney balanceItem = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(cb.url); //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(" https://api.bitso.com/v3/account_status/"); request.Method = cb.HTTPmethod; request.Headers.Add("Authorization", AUTH_HEADER); request.ContentType = "application/json"; //request.ContentType = "application/x-www-form-urlencoded"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); balanceItem = JsonConvert.DeserializeObject <CLoadMoney>(json); //List<CBalance> lBalance =balanceItem.payload.balances.FindAll(delegate(CBalance bk) //{ // return bk.currency.ToString() != ""; //}); foreach (CBalance item in balanceItem.payload.balances) { lBalances.Add(item); } bRegresa = true; //bitsoUserData(); } } catch (Exception ex) { MessageBox.Show("Ocurrio un error: " + ex.Message); } return(bRegresa); }
/// <summary> /// Create a cryptographic key of length <paramref name="cbOut" /> /// (in bytes) from <paramref name="pbIn" />. /// </summary> public static byte[] ResizeKey(byte[] pbIn, int iInOffset, int cbIn, int cbOut) { if (pbIn == null) { throw new ArgumentNullException("pbIn"); } if (cbOut < 0) { throw new ArgumentOutOfRangeException("cbOut"); } if (cbOut == 0) { return(MemUtil.EmptyByteArray); } byte[] pbHash; if (cbOut <= 32) { pbHash = HashSha256(pbIn, iInOffset, cbIn); } else { using (SHA512Managed h = new SHA512Managed()) { pbHash = h.ComputeHash(pbIn, iInOffset, cbIn); } } if (cbOut == pbHash.Length) { return(pbHash); } byte[] pbRet = new byte[cbOut]; if (cbOut < pbHash.Length) { Array.Copy(pbHash, pbRet, cbOut); } else { int iPos = 0; ulong r = 0; while (iPos < cbOut) { Debug.Assert(pbHash.Length == 64); using (HMACSHA256 h = new HMACSHA256(pbHash)) { byte[] pbR = MemUtil.UInt64ToBytes(r); byte[] pbPart = h.ComputeHash(pbR); int cbCopy = Math.Min(cbOut - iPos, pbPart.Length); Debug.Assert(cbCopy > 0); Array.Copy(pbPart, 0, pbRet, iPos, cbCopy); iPos += cbCopy; ++r; MemUtil.ZeroByteArray(pbPart); } } Debug.Assert(iPos == cbOut); } #if DEBUG byte[] pbZero = new byte[pbHash.Length]; Debug.Assert(!MemUtil.ArraysEqual(pbHash, pbZero)); #endif MemUtil.ZeroByteArray(pbHash); return(pbRet); }
public override Dictionary <string, object> AddAuthenticationToParameters(string uri, HttpMethod method, Dictionary <string, object> parameters, bool signed) { if (!signed && !signPublicRequests) { return(parameters); } if (Credentials.Key == null) { throw new ArgumentException("ApiKey/secret not provided"); } var uriObj = new Uri(uri); var signParameters = new Dictionary <string, object> { { "AccessKeyId", Credentials.Key.GetString() }, { "SignatureMethod", "HmacSHA256" }, { "SignatureVersion", 2 } }; if (!parameters.ContainsKey("Timestamp") || method != HttpMethod.Get) { signParameters.Add("Timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss")); } if (method == HttpMethod.Get) { foreach (var kvp in parameters) { signParameters.Add(kvp.Key, kvp.Value); } } signParameters = signParameters.OrderBy(kv => Encoding.UTF8.GetBytes(WebUtility.UrlEncode(kv.Key)), new ByteOrderComparer()).ToDictionary(k => k.Key, k => k.Value); var paramString = signParameters.CreateParamString(true, ArrayParametersSerialization.MultipleValues); signParameters = signParameters.OrderBy(kv => kv.Key).ToDictionary(k => k.Key, k => k.Value); var absolutePath = uriObj.AbsolutePath; if (absolutePath.StartsWith("/api")) { // Russian api has /api prefix which shouldn't be part of the signature absolutePath = absolutePath.Substring(4); } var signData = method + "\n"; signData += uriObj.Host + "\n"; signData += absolutePath + "\n"; signData += paramString; byte[] signBytes; lock (encryptLock) signBytes = encryptor.ComputeHash(Encoding.UTF8.GetBytes(signData)); signParameters.Add("Signature", Convert.ToBase64String(signBytes)); if (method != HttpMethod.Get) { foreach (var kvp in parameters) { signParameters.Add(kvp.Key, kvp.Value); } } return(signParameters); }
static void Main(string[] args) { string oauth_verifier = ""; // Use the oauth_verifier in the previous step string oauth_token = ""; // Use the oauth_token in the previous step string oauth_consumer_key = ""; // Use your own oauth_consumer_key string oauth_nonce = "6"; // Use your own oauth_nonce string oauth_signature = ""; // Leave this blank for now string oauth_signature_method = ""; // "HMAC-SHA1" or "HMAC-SHA256" string oauth_timestamp = ""; // Use your own oauth_timestamp string oauth_version = ""; // "1.0" or "1" string oauth_consumer_secret = ""; // Use your own oauth_consumer_secret string oauth_token_secret = ""; // Use your own oauth_token_secret you got from the pervious stage string method = "POST"; string uri = "https://apisandbox.openbankproject.com/oauth/token"; // Create a list of OAuth parameters List <KeyValuePair <string, string> > oauthparameters = new List <KeyValuePair <string, string> >(); oauthparameters.Add(new KeyValuePair <string, string>("oauth_verifier", oauth_verifier)); oauthparameters.Add(new KeyValuePair <string, string>("oauth_token", oauth_token)); oauthparameters.Add(new KeyValuePair <string, string>("oauth_consumer_key", oauth_consumer_key)); oauthparameters.Add(new KeyValuePair <string, string>("oauth_nonce", oauth_nonce)); oauthparameters.Add(new KeyValuePair <string, string> ("oauth_signature_method", oauth_signature_method)); oauthparameters.Add(new KeyValuePair <string, string>("oauth_timestamp", oauth_timestamp)); oauthparameters.Add(new KeyValuePair <string, string>("oauth_version", oauth_version)); // Sort the OAuth parameters on the key oauthparameters.Sort((x, y) => x.Key.CompareTo(y.Key)); // Construct the Base String string basestring = method.ToUpper() + "&" + UrlEncodeCapitalized(uri) + "&"; foreach (KeyValuePair <string, string> pair in oauthparameters) { if (pair.Key == oauthparameters[oauthparameters.Count - 1].Key) { basestring += pair.Key + "%3D" + UrlEncodeCapitalized(pair.Value); } else { basestring += pair.Key + "%3D" + UrlEncodeCapitalized(pair.Value) + "%26"; } } // Encrypt with either SHA1 or SHA256, creating the Signature var enc = Encoding.ASCII; if (oauth_signature_method == "HMAC-SHA1") { HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(oauth_consumer_secret + "&" + oauth_token_secret)); hmac.Initialize(); byte[] buffer = enc.GetBytes(basestring); string hmacsha1 = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower(); byte[] resultantArray = new byte[hmacsha1.Length / 2]; for (int i = 0; i < resultantArray.Length; i++) { resultantArray[i] = Convert.ToByte(hmacsha1.Substring(i * 2, 2), 16); } string base64 = Convert.ToBase64String(resultantArray); oauth_signature = UrlEncodeCapitalized(base64); } else if (oauth_signature_method == "HMAC-SHA256") { HMACSHA256 hmac = new HMACSHA256(enc.GetBytes(oauth_consumer_secret + "&" + oauth_token_secret)); hmac.Initialize(); byte[] buffer = enc.GetBytes(basestring); string hmacsha256 = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "") .ToLower(); byte[] resultantArray = new byte[hmacsha256.Length / 2]; for (int i = 0; i < resultantArray.Length; i++) { resultantArray[i] = Convert.ToByte(hmacsha256.Substring(i * 2, 2), 16); } string base64 = Convert.ToBase64String(resultantArray); oauth_signature = UrlEncodeCapitalized(base64); } // Create the Authorization string for the WebRequest header string authorizationstring = ""; foreach (KeyValuePair <string, string> pair in oauthparameters) { authorizationstring += pair.Key; authorizationstring += "="; authorizationstring += pair.Value; authorizationstring += ","; } authorizationstring += "oauth_signature=" + oauth_signature; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = method; request.Headers.Add("Authorization", "OAuth " + authorizationstring); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); Console.ReadLine(); //Pause }
public override string Sign(string toSign) { return(ByteArrayToString(encryptor.ComputeHash(Encoding.UTF8.GetBytes(toSign)))); }
/// <summary> /// This method is used to decrypt the specified encrypted data. /// </summary> /// <param name="cryptoData">Contains the encrypted data to decrypt.</param> /// <param name="cryptKey">Contains the crypto key data.</param> /// <param name="authKey">Contains the authorize key data.</param> /// <param name="nonSecretPayloadLength">Contains the length of the additional payload used in encryption.</param> /// <returns>Returns the original decrypted text.</returns> public static byte[] Decrypt(this byte[] cryptoData, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0) { byte[] result = Array.Empty <byte>(); // if no crypt key or the length is invalid if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.CryptoKeyLengthErrorText, KeyBitSize), nameof(cryptKey)); } if (authKey == null || authKey.Length != KeyBitSize / 8) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.CryptoAuthKeyLengthErrorText, KeyBitSize), nameof(authKey)); } if (cryptoData == null || cryptoData.Length == 0) { throw new ArgumentNullException(nameof(cryptoData), Resources.CryptoMustSpecifyCryptoTextToDecryptErrorText); } // generate a hash first to check validation using (var hmac = new HMACSHA256(authKey)) { byte[] sentTag = new byte[hmac.HashSize / 8]; // Calculate Tag sans the hash tag suffix var calcTag = hmac.ComputeHash(cryptoData, 0, cryptoData.Length - sentTag.Length); var vectorLength = BlockBitSize / 8; // if message length is to small just return null if (cryptoData.Length >= sentTag.Length + nonSecretPayloadLength + vectorLength) { // Grab Sent hash Tag Array.Copy(cryptoData, cryptoData.Length - sentTag.Length, sentTag, 0, sentTag.Length); // Compare Tag with constant time comparison var compare = 0; for (var i = 0; i < sentTag.Length; i++) { compare |= sentTag[i] ^ calcTag[i]; } // if hash authenticated OK, continue... if (compare == 0) { // create a new AES crypto engine... using (var aes = new AesCryptoServiceProvider { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { // Grab IV from message var iv = new byte[vectorLength]; Array.Copy(cryptoData, nonSecretPayloadLength, iv, 0, iv.Length); // create a new decryption engine... using (var crypto = aes.CreateDecryptor(cryptKey, iv)) using (MemoryStream plainTextStream = new MemoryStream()) { // create a new crypto stream... using (var cryptoStream = new CryptoStream(plainTextStream, crypto, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(cryptoStream)) { // Decrypt Cipher Text from Message binaryWriter.Write(cryptoData, nonSecretPayloadLength + iv.Length, cryptoData.Length - nonSecretPayloadLength - iv.Length - sentTag.Length); } // Return Plain Text as secure string result = plainTextStream.ToArray(); } } } } } return(result); }
public JsonWebToken(SerializerType serializerType) { switch (serializerType) { case SerializerType.DefaultSerializer: JsonSerializer = new DefaultJsonSerializer(); break; case SerializerType.NewtonsoftJsonSerializer: JsonSerializer = new NewtonsoftJsonSerializer(); break; case SerializerType.ServiceStackJsonSerializer: JsonSerializer = new ServiceStackJsonSerializer(); break; default: JsonSerializer = new DefaultJsonSerializer(); break; } HashAlgorithms = new Dictionary <JwtHashAlgorithm, Func <byte[], byte[], byte[]> > { { JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return(sha.ComputeHash(value)); } } }, { JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return(sha.ComputeHash(value)); } } }, { JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return(sha.ComputeHash(value)); } } } }; }
public bool bitsoUserData() { bool bRegresa = false; string SIGNATURE = string.Empty; string AUTH_HEADER = string.Empty; string MESSAGE = string.Empty; string REQUESTPATH = "/v3/account_status/"; string sURL = @"https://api.bitso.com/v3/account_status/"; //string sNONCE = (CurrentUnixTimeMillis()).ToString(); string sNONCE = Convert.ToInt64(new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds).ToString(); //Dataos obtenido de una clase que al momento de la instancia se pasan los parametros. //MESSAGE = cb.dnoce + "GET" + REQUESTPATH + cb.JSONPayload; MESSAGE = sNONCE + "GET" + REQUESTPATH + cb.JSONPayload; ASCIIEncoding encoder = new ASCIIEncoding(); HMACSHA256 hmSha256 = new HMACSHA256(encoder.GetBytes(cb.api_secret)); byte[] hm256Byte = hmSha256.ComputeHash(encoder.GetBytes(MESSAGE)); SIGNATURE = ToHexString(hm256Byte); AUTH_HEADER = "Bitso " + cb.api_key + ":" + sNONCE + ":" + SIGNATURE; CLoadStatusBitso statusBitso = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL); request.Method = "GET"; request.Headers.Add("Authorization", AUTH_HEADER); request.ContentType = "application/json"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); statusBitso = JsonConvert.DeserializeObject <CLoadStatusBitso>(json); /*foreach (CBalance item in statusBitso.payload) * { * lBalances.Add(item); * } */ bRegresa = true; } } catch (WebException wx) { using (WebResponse response = wx.Response) { HttpWebResponse httpResponse = (HttpWebResponse)response; //Console.WriteLine("Error code: {0}", httpResponse.StatusCode); using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data)) { string text = reader.ReadToEnd(); MessageBox.Show(text + " : " + httpResponse.StatusCode); } } } catch (Exception ex) { MessageBox.Show("Ocurrio un error: " + ex.Message); } return(bRegresa); }
private void DeleteMultipleBlobs(List <string> blobs) { // TODO: RavenDB-16264 // Multi-Delete isn't supported when using a SAS token // https://issues.hibernatingrhinos.com/issue/RavenDB-14936 // https://github.com/Azure/azure-sdk-for-net/issues/11762 const string xMsDate = "x-ms-date"; const string xMsClientRequestId = "x-ms-client-request-id"; const string xMsReturnClientRequestId = "x-ms-return-client-request-id"; var now = SystemTime.UtcNow.ToString("R"); var url = GetUrl(_serverUrlForAccountName, "comp=batch"); var requestMessage = new HttpRequestMessage(HttpMethods.Post, url) { Headers = { { xMsDate, now }, { "x-ms-version", AzureStorageVersion } } }; var batchContent = new MultipartContent("mixed", $"batch_{Guid.NewGuid()}"); requestMessage.Content = batchContent; var blobsWithIds = new Dictionary <string, string>(); for (var i = 0; i < blobs.Count; i++) { using var ms = new MemoryStream(); using var writer = new StreamWriter(ms); var clientRequestId = Guid.NewGuid().ToString(); blobsWithIds[clientRequestId] = blobs[i]; writer.WriteLine($"{HttpMethods.Delete} /{_containerName}/{blobs[i]} HTTP/1.1"); writer.WriteLine($"{xMsDate}: {now}"); writer.WriteLine($"{xMsClientRequestId}: {clientRequestId}"); writer.WriteLine($"{xMsReturnClientRequestId}: true"); using (var hash = new HMACSHA256(_accountKey)) { var uri = new Uri($"{_serverUrlForContainer}/{blobs[i]}", UriKind.Absolute); var hashStr = $"{HttpMethods.Delete}\n\n\n\n\n\n\n\n\n\n\n\n{xMsClientRequestId}:{clientRequestId}\n{xMsDate}:{now}\n{xMsReturnClientRequestId}:true\n/{_accountName}{uri.AbsolutePath}"; writer.WriteLine($"Authorization: SharedKey {_accountName}:{Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(hashStr)))}"); } writer.WriteLine("Content-Length: 0"); writer.Flush(); batchContent.Add(new ByteArrayContent(ms.ToArray()) { Headers = { { "Content-Type", "application/http" }, { "Content-Transfer-Encoding", "binary" }, { "Content-ID", $"{i}" } } }); } var client = GetClient(); if (batchContent.Headers.ContentLength.HasValue == false) { // we need the ContentLength to CalculateAuthorizationHeaderValue // the ContentLength is calculated on the fly, it gets added to Headers only when we try to access it. throw new ArgumentException($"{nameof(MultipartContent)} should have content length"); } SetAuthorizationHeader(client, HttpMethods.Post, url, requestMessage.Headers, batchContent.Headers); var response = client.SendAsync(requestMessage).Result; if (response.IsSuccessStatusCode == false) { throw StorageException.FromResponseMessage(response); } using var stream = response.Content.ReadAsStreamAsync().Result; using var reader = new StreamReader(stream); const string statusCode = "StatusCode"; const string status = "Status"; var responseBoundary = $"--{response.Content.Headers.ContentType.Parameters.First().Value}"; var result = new Dictionary <string, Dictionary <string, string> >(); while (reader.Peek() >= 0) { var line = reader.ReadLine(); // read batch response if (line != responseBoundary && line != $"{responseBoundary}--") { throw new InvalidDataException("Got invalid response from server."); } while (string.IsNullOrEmpty(line) == false) { line = reader.ReadLine(); } line = reader.ReadLine(); // read sub-response block if (string.IsNullOrEmpty(line)) { break; } string[] res = line.Split(" "); var responseDictionary = new Dictionary <string, string> { { statusCode, res[1] }, { status, res[1] == "202" ? res[res.Length - 1] : string.Join(" ", res, 2, res.Length - 2) } }; line = reader.ReadLine(); while (string.IsNullOrEmpty(line) == false) { var r = line.Split(": "); responseDictionary[r.First()] = r.Last(); line = reader.ReadLine(); } result[blobsWithIds[responseDictionary["x-ms-client-request-id"]]] = responseDictionary; if (responseDictionary.TryGetValue("x-ms-error-code", out _)) { // read the error message body line = reader.ReadLine(); if (line.StartsWith("<?xml")) { while (line.EndsWith("</Error>") == false) { line = reader.ReadLine(); } } else { while (string.IsNullOrEmpty(line) == false) { line = reader.ReadLine(); } } } } var errors = result.Keys.Where(key => result[key][status] != "Accepted").ToDictionary(key => key, key => result[key][status]); var canLog = _logger != null && _logger.IsInfoEnabled; if (errors.Count == 0) { if (canLog) { _logger.Info($"Successfully deleted {result.Count} blob{Pluralize(result.Count)} from container: {_containerName}."); } return; } var reasons = errors.Values.Distinct().ToArray(); var failedToDeleteReasons = reasons.Aggregate(string.Empty, (current, r) => current + $"Reason: {r} Blobs ({errors.Count(x => x.Value == r)}): {string.Join(", ", errors.Where(x => x.Value == r).Select(y => y.Key))}. "); var message = $"Failed to delete {errors.Count} blob{Pluralize(errors.Count)} from container: {_containerName}. Successfully deleted {result.Count - errors.Count} blob{Pluralize(result.Count - errors.Count)}. {failedToDeleteReasons}"; if (canLog) { _logger.Info(message); } string Pluralize(int num) { return(num == 0 || num > 1 ? "s" : string.Empty); } throw new InvalidOperationException(message); }
/// <summary> /// Computes a keyed hash for a source file based on key provided and the HMAC algorithm selected by the user /// Defaults to HMACSHA1 /// </summary> /// <param name="file">file to get the HMAC of</param> /// <param name="hmacAlgo">HMAC algorithm to use</param> /// <param name="hmacKey">Key supplied by the user</param> public string CalculateHMAC(string file, string hmacAlgo, byte[] hmacKey) { string resultHmac = ""; byte[] hashOfInputFile; try { switch (hmacAlgo) { case "HMACMD5": using (HMACMD5 hmacSha1 = new HMACMD5(hmacKey)) { using (FileStream objFS = new FileStream(file, FileMode.Open)) { // Computing the hash of the input file hashOfInputFile = hmacSha1.ComputeHash(objFS); } } break; case "HMACSHA256": using (HMACSHA256 hmacSha1 = new HMACSHA256(hmacKey)) { using (FileStream objFS = new FileStream(file, FileMode.Open)) { // Computing the hash of the input file hashOfInputFile = hmacSha1.ComputeHash(objFS); } } break; case "HMACSHA384": using (HMACSHA384 hmacSha1 = new HMACSHA384(hmacKey)) { using (FileStream objFS = new FileStream(file, FileMode.Open)) { // Computing the hash of the input file hashOfInputFile = hmacSha1.ComputeHash(objFS); } } break; case "HMACSHA512": using (HMACSHA512 hmacSha1 = new HMACSHA512(hmacKey)) { using (FileStream objFS = new FileStream(file, FileMode.Open)) { // Computing the hash of the input file hashOfInputFile = hmacSha1.ComputeHash(objFS); } } break; case "HMACRIPEMD160": using (HMACRIPEMD160 hmacSha1 = new HMACRIPEMD160(hmacKey)) { using (FileStream objFS = new FileStream(file, FileMode.Open)) { // Computing the hash of the input file hashOfInputFile = hmacSha1.ComputeHash(objFS); } } break; default: // "HMACSHA1": using (HMACSHA1 hmacSha1 = new HMACSHA1(hmacKey)) { using (FileStream objFS = new FileStream(file, FileMode.Open)) { // Computing the hash of the input file hashOfInputFile = hmacSha1.ComputeHash(objFS); } } break; } resultHmac = BitConverter.ToString(hashOfInputFile).Replace("-", String.Empty).ToLower(); return(resultHmac); } catch { resultHmac = HMAC_ERROR; return(resultHmac); } finally { } }
public static byte[] GetHmac(byte[] key, string message) { using var hmac = new HMACSHA256(key); return(hmac.ComputeHash(StringEncode(message))); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // get configuration var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json"); var config = builder.Build(); // set up console logging // TODO it would be nice to also have a text file logger if (config["LogType"] == "console" | config["LogType"] == "both") { if (config["DebugLog"] == "true") { loggerFactory.AddConsole(LogLevel.Debug); } else { loggerFactory.AddConsole(LogLevel.Information); } } // initiate logging var logger = loggerFactory.CreateLogger("Tug"); logger.LogInformation("Tug begins."); // set development option if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // begin registering routes for incoming requests var routeBuilder = new RouteBuilder(app); // Default route welcome message routeBuilder.MapGet("", context => { return(context.Response.WriteAsync(@" <h1>Welcome to Tug!</h1> <li><a href=""/version"">Version Info</a></li> ")); }); // Server version info routeBuilder.MapGet("version", context => { var version = GetType().GetTypeInfo().Assembly.GetName().Version; return(context.Response.WriteAsync($"{{{version}}}")); }); // Node registration routeBuilder.MapPut("Nodes(AgentId={AgentId})", context => { /* * * Authorization HTTP header must match the HTTP body, * passed through a SHA-256 digest hash, * encoded in Base64. * That then gets a newline, * the x-ms-date HTTP header from the request, * and is then run through a * SHA-256 digest hash that uses a known RegistrationKey as an HMAC, * with the result Base64 encoded. * * This essentially is a digital signature and proof that the node knows a shared secret registration key. * * So the received header is Authorization: Shared xxxxxxx\r\n * */ logger.LogInformation("\n\n\nPUT: Node registration"); string AgentId = context.GetRouteData().Values["AgentId"].ToString(); string Body = new StreamReader(context.Request.Body).ReadToEnd(); var Headers = context.Request.Headers; logger.LogDebug("AgentId {AgentId}, Request Body {Body}, Headers {Headers}", AgentId, Body, Headers); // get needed headers // TODO: should check for these existing rather than assuming, fail if they don't string xmsdate = context.Request.Headers["x-ms-date"]; string authorization = context.Request.Headers["Authorization"]; logger.LogDebug("x-ms-date {date}, Authorization {auth}", xmsdate, authorization); // create signature, part 1 // this is the request body, hashed, then combined with the x-ms-date header string contentHash = ""; using (var sha256 = SHA256.Create()) { var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(Body)); contentHash = Convert.ToBase64String(hashedBytes); //contentHash = BitConverter.ToString(hashedBytes).Replace("-",""); } logger.LogDebug("Created content hash {hash}", contentHash); string stringToSign = String.Format("{0}\n{1}", contentHash, xmsdate); logger.LogDebug("String to sign is {sign}", stringToSign); // HACK - we need to run a command to get the allowed registration keys // and then compare each one string[] registrationKeys = { "91E51A37-B59F-11E5-9C04-14109FD663AE" }; string result = Runner.Run("Get-Process"); logger.LogDebug(result); // go through valid registration keys and create a final signature // we do this because we might have multiple registration keys, so we // have to try them all until we find one that matches bool Valid = false; foreach (string key in registrationKeys) { logger.LogDebug("Trying registration key {key}", key); // convert string key to Base64 byte[] byt = Encoding.UTF8.GetBytes(key); string base64key = Convert.ToBase64String(byt); // create HMAC signature using this registration key var secretKeyBase64ByteArray = Convert.FromBase64String(base64key); string signature = ""; using (HMACSHA256 hmac = new HMACSHA256(secretKeyBase64ByteArray)) { byte[] authenticationKeyBytes = Encoding.UTF8.GetBytes(stringToSign); byte[] authenticationHash = hmac.ComputeHash(authenticationKeyBytes); signature = Convert.ToBase64String(authenticationHash); } // compare what node sent to what we made string AuthToMatch = authorization.Replace("Shared ", ""); logger.LogDebug("Comparing keys:\nRcvd {0} \nMade {1}", AuthToMatch, signature); if (AuthToMatch == signature) { logger.LogDebug("Node is authorized"); Valid = true; break; } } // Because this is a PUT, we're only expected to return an HTTP status code // TODO we also need to call Set-TugNodeRegistration if the node was valid if (Valid) { // TODO return HTTP 200 return(context.Response.WriteAsync($"Registering node {AgentId}")); } else { // TODO return HTTP 404(? check spec) return(context.Response.WriteAsync($"Registering node {AgentId}")); } } ); // DSC Action routeBuilder.MapPost("Nodes(AgentId={AgentId})/DscAction", context => { logger.LogInformation("\n\n\nPOST: DSC action request"); string AgentId = context.GetRouteData().Values["AgentId"].ToString(); string Body = new StreamReader(context.Request.Body).ReadToEnd(); var Headers = context.Request.Headers; logger.LogDebug("AgentId {AgentId}, Request Body {Body}, Headers {Headers}", AgentId, Body, Headers); return(context.Response.WriteAsync($"DSC action for node {AgentId}")); } ); // Asking for a MOF routeBuilder.MapPost("Nodes(AgentId={AgentId})/Configurations(ConfigurationName={ConfigurationName})/ConfigurationContent", context => { logger.LogInformation("\n\n\nPOST: MOF request"); string AgentId = context.GetRouteData().Values["AgentId"].ToString(); string ConfigurationName = context.GetRouteData().Values["ConfigurationName"].ToString(); string Body = new StreamReader(context.Request.Body).ReadToEnd(); var Headers = context.Request.Headers; logger.LogDebug("AgentId {AgentId}, Configuration {Config}, Request Body {Body}, Headers {Headers}", AgentId, ConfigurationName, Body, Headers); return(context.Response.WriteAsync($"Request from node {AgentId} for configuration {ConfigurationName}")); } ); // Asking for a module routeBuilder.MapPost("Modules(ModuleName={ModuleName},ModuleVersion={ModuleVersion})/ModuleContent", context => { logger.LogInformation("\n\n\nPOST: Module request"); string ModuleName = context.GetRouteData().Values["ModuleName"].ToString(); string ModuleVersion = context.GetRouteData().Values["ModuleVersion"].ToString(); string Body = new StreamReader(context.Request.Body).ReadToEnd(); var Headers = context.Request.Headers; logger.LogDebug("Module name {ModuleName}, Version {Version}, Request Body {Body}, Headers {Headers}", ModuleName, ModuleVersion, Body, Headers); return(context.Response.WriteAsync($"Module request for {ModuleName} version {ModuleVersion}")); } ); // Sending a report routeBuilder.MapPost("Nodes(AgentId={AgentId})/SendReport", context => { logger.LogInformation("\n\n\nPOST: Report delivery"); string AgentId = context.GetRouteData().Values["AgentId"].ToString(); string Body = new StreamReader(context.Request.Body).ReadToEnd(); var Headers = context.Request.Headers; logger.LogDebug("AgentId {AgentId}, Request Body {Body}, Headers {Headers}", AgentId, Body, Headers); return(context.Response.WriteAsync($"Report from node {AgentId}")); } ); // with everything defined, kick it off var routes = routeBuilder.Build(); app.UseRouter(routes); }
public static string HashString(string str_to_hash) { HMACSHA256 hs256 = new HMACSHA256(Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["UserSalt"])); return BytesToHexString(hs256.ComputeHash(StringToBytes(str_to_hash))).Replace("-", ""); }