public static string GenerateHMACSHA256Hash(string Password, string QueueId, string UrlToHash) { ValidateInput(QueueId, "QueueId"); ValidateInput(Password, "Password"); ValidateInput(UrlToHash, "UrlToHash"); // Create a random key using a random number generator. This would be the // secret key shared by sender and receiver. byte[] secretkey = new Byte[64]; Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(QueueId)); secretkey = deriveBytes.GetBytes(64); // Initialize the keyed hash object. HMACSHA256 myhmacsha256 = new HMACSHA256(secretkey); byte[] byteStringToHash = Encoding.UTF8.GetBytes(UrlToHash); byte[] hashValue = myhmacsha256.ComputeHash(byteStringToHash); myhmacsha256.Clear(); string hashStr = Encoding.ASCII.GetString(hashValue); string UrlEncodeHashString = HttpUtility.UrlEncode(hashStr); //not all special characters like = and / are encoded on first UrlEncoding //UrlEncoding once more fixes the problem...... UrlEncodeHashString = HttpUtility.UrlEncode(UrlEncodeHashString); return(UrlEncodeHashString); }
// Computes a keyed hash for a source file, creates a target file with the keyed hash // prepended to the contents of the source file, then decrypts the file and compares // the source and the decrypted files. public static void EncodeFile(byte[] key, String sourceFile, String destFile) { // Initialize the keyed hash object. HMACSHA256 myhmacsha256 = new HMACSHA256(key); FileStream inStream = new FileStream(sourceFile, FileMode.Open); FileStream outStream = new FileStream(destFile, FileMode.Create); // Compute the hash of the input file. byte[] hashValue = myhmacsha256.ComputeHash(inStream); // Reset inStream to the beginning of the file. inStream.Position = 0; // Write the computed hash value to the output file. outStream.Write(hashValue, 0, hashValue.Length); // Copy the contents of the sourceFile to the destFile. int bytesRead; // read 1K at a time byte[] buffer = new byte[1024]; do { // Read from the wrapping CryptoStream. bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); myhmacsha256.Clear(); // Close the streams inStream.Close(); outStream.Close(); return; } // end EncodeFile
/// <summary> /// Computes the hash. /// </summary> /// <param name="version">The version.</param> /// <param name="header">The header.</param> /// <param name="parameters">The parameters.</param> /// <param name="data">The scope bytes.</param> /// <param name="privacy">The privacy provider.</param> /// <param name="length">The length bytes.</param> /// <returns></returns> public OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData data, IPrivacyProvider privacy, byte[] length) { if (header == null) { throw new ArgumentNullException(nameof(header)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } if (privacy == null) { throw new ArgumentNullException(nameof(privacy)); } var key = PasswordToKey(_password, parameters.EngineId.GetRaw()); using (var sha256 = new HMACSHA256(key)) { var hash = sha256.ComputeHash(ByteTool.PackMessage(length, version, header, parameters, data).ToBytes()); #if NET471 sha256.Clear(); #endif var result = new byte[DigestLength]; Buffer.BlockCopy(hash, 0, result, 0, result.Length); return(new OctetString(result)); } }
//static ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public static bool IsMatchSignature(string signature, string reqestBody, string channelSecret) { ////doSignatureがfalseの場合は署名チェックを行わない //if (!Settings.Default.doSignature) //{ // logger.Info("IsMatchSignature No Check"); // return true; //} if (string.IsNullOrEmpty(signature)) { //logger.Info("ChannelSignature is Null or Empty"); //署名が未設定 return(false); } #region 署名による判定 //秘密キーをハッシュ化 HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(channelSecret)); //ハッシュ値を計算 byte[] bs = hmac.ComputeHash(Encoding.UTF8.GetBytes(reqestBody)); //リソースを解放する hmac.Clear(); //byte型配列をBASE64エンコードする string base64String = Convert.ToBase64String(bs); //logger.Info("IsMatchSignature Data\r\n" + "signature[" + signature + "]\r\n" + "base64String[" + base64String + "]\r\n" + "reqestBody[" + reqestBody + "]\r\n"); #endregion return(signature.Equals(base64String)); }
public static string EncryptSHA256(string plainText, string password) { HMACSHA256 hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(password)); byte[] cipherData = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(plainText)); string cipherText = Convert.ToBase64String(cipherData); hmacsha256.Clear(); return(cipherText); }
// Hashing a value using HMAC-256 private void HMACHash() { ASCIIEncoding encode = new ASCIIEncoding(); HMACSHA256 hmac256 = new HMACSHA256(key); byte[] uniqueAsByte = encode.GetBytes(unique); byte[] hashedUnique = hmac256.ComputeHash(uniqueAsByte); unique = null; unique = ByteToString(hashedUnique); hmac256.Clear(); }
public static string DecryptSHA256(string cipherText, string password) { HMACSHA256 hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(password)); byte[] plainData = hmacsha256.ComputeHash(Convert.FromBase64String(cipherText)); string plainText = Encoding.UTF8.GetString(plainData, 0, plainData.Length); hmacsha256.Clear(); return(plainText); }
public static string HMACSHA256(string sourceText, string key) { var keyByte = Encoding.UTF8.GetBytes(key); var sourceBytes = Encoding.UTF8.GetBytes(sourceText); using (var hmacSha256 = new HMACSHA256(keyByte)) { var bytes = hmacSha256.ComputeHash(sourceBytes); hmacSha256.Clear(); return(BitConverter.ToString(bytes).Replace("-", "").ToLower()); } }
public static byte[] Hmacsha256String(this string value, string secret) { byte[] messageBytes = Encoding.UTF8.GetBytes(value); byte[] keyByte = Encoding.UTF8.GetBytes(secret); byte[] hashmessage; using (var hmacsha256 = new HMACSHA256(keyByte)) { hashmessage = hmacsha256.ComputeHash(messageBytes); hmacsha256.Clear(); } return(hashmessage); }
/// <summary> /// 加密 /// </summary> /// <param name="apiSecretIsKey"></param> /// <param name="buider"></param> /// <returns></returns> private static string HMACSha256(string apiSecretIsKey, string buider) { byte[] bytes = Encoding.UTF8.GetBytes(apiSecretIsKey); using (HMACSHA256 hMACSHA256 = new HMACSHA256(bytes)) { byte[] date = Encoding.UTF8.GetBytes(buider); date = hMACSHA256.ComputeHash(date); hMACSHA256.Clear(); return(System.Convert.ToBase64String(date)); } }
/// <summary> /// Encrypts an string using AES /// </summary> /// <param name="data">The string to encrypt.</param> /// <param name="password">The password to use.</param> public static byte[] EncryptString(string data, string password) { byte[] output = null; using (SymmetricAlgorithm encryptator = Aes.Create()) using (KeyedHashAlgorithm signer = new HMACSHA256()) { encryptator.KeySize = 256; // Key size of 256 bits // Get the data bytes byte[] plainText = Encoding.UTF8.GetBytes(data); byte[] cipherText; // Create a buffer to store the cipher data byte[] salt = GetRandomSalt(); // Get random salt // Get key and IV encryptator.Key = KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA512, KeyDerivationIterationCount, encryptator.KeySize / 8); encryptator.IV = KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA512, KeyDerivationIterationCount, encryptator.BlockSize / 8); // Encrypt using (var ms = new MemoryStream()) using (var crypto = new CryptoStream(ms, encryptator.CreateEncryptor(), CryptoStreamMode.Write)) { // Write to the crypto stream crypto.Write(plainText, 0, plainText.Length); crypto.FlushFinalBlock(); // Get encrypted data with IV cipherText = encryptator.IV.CombineWith(ms.ToArray()); } // Sign the data so we can detect tampering byte[] signature = SignData(password, cipherText, salt, encryptator, signer); // Add the signature to the cipher text output = signature.CombineWith(cipherText); // Write salt to the output output = salt.CombineWith(output); // Clear everything up encryptator.Clear(); signer.Clear(); // Clear unused arrays Array.Clear(plainText, 0, plainText.Length); Array.Clear(salt, 0, salt.Length); Array.Clear(cipherText, 0, cipherText.Length); Array.Clear(signature, 0, signature.Length); } return(output); }
private static string GetSignature(string args, string privatekey) { var encoding = new System.Text.ASCIIEncoding(); byte[] key = encoding.GetBytes(privatekey); var myhmacsha256 = new HMACSHA256(key); byte[] hashValue = myhmacsha256.ComputeHash(encoding.GetBytes(args)); string hmac64 = Convert.ToBase64String(hashValue); myhmacsha256.Clear(); return(hmac64); }
/// <summary> /// リクエストの署名をチェック /// </summary> /// <returns></returns> private bool CheckSignature(RequestInfoFromLine info) { string channelSercret = CommonSettings.ChannelSercret; byte[] key = Encoding.UTF8.GetBytes(channelSercret); HMACSHA256 hmac = new HMACSHA256(key); byte[] bs = hmac.ComputeHash(info.RequestBodyBytes); hmac.Clear(); string signature = Convert.ToBase64String(bs); return(signature == Request.Headers["X-Line-Signature"]); }
public static string ToHMAC_SHA256(this string toHash, string key) { byte[] keyByte = Encoding.Default.GetBytes(key); var sha256 = new HMACSHA256(keyByte); //sha256.Initialize(); Byte[] originalByte = Encoding.Default.GetBytes(toHash); Byte[] encodedByte = sha256.ComputeHash(originalByte); sha256.Clear(); string hash = BitConverter.ToString(encodedByte).Replace("-", "").ToLower(); return(hash); }
/// <summary> /// 站内应用使用SignedRequest获取AccessToken /// </summary> /// <param name="signedRequest">SignedRequest</param> /// <returns></returns> public AccessToken GetAccessTokenBySignedRequest(string signedRequest) { var parameters = signedRequest.Split('.'); if (parameters.Length < 2) { throw new Exception("SignedRequest格式错误。"); } var encodedSig = parameters[0]; var payload = parameters[1]; var sha256 = new HMACSHA256(Encoding.UTF8.GetBytes(AppSecret)); var expectedSig = Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(payload))); sha256.Clear(); encodedSig = parameters[0].Length % 4 == 0 ? parameters[0] : parameters[0].PadRight(parameters[0].Length + (4 - parameters[0].Length % 4), '=') .Replace("-", "+") .Replace("_", "/"); payload = parameters[1].Length % 4 == 0 ? parameters[1] : parameters[1].PadRight(parameters[1].Length + (4 - parameters[1].Length % 4), '=') .Replace("-", "+") .Replace("_", "/"); if (encodedSig != expectedSig) { throw new WeiboException("SignedRequest签名验证失败。"); } var result = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(payload))); if (result["oauth_token"] == null) { return(null); //throw new WeiboException("没有获取到授权信息,请先进行授权。"); } var token = new AccessToken(); AccessToken = token.Token = result["oauth_token"].ToString(); token.UID = result["user_id"].ToString(); token.ExpiresIn = Convert.ToInt32(result["expires"].ToString()); return(token); }
public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName) { if (String.IsNullOrEmpty(key)) { throw new ArgumentNullException("key", "Please specify a Secret Signing Key."); } if (data == null || data.Length == 0) { throw new ArgumentNullException("data", "Please specify data to sign."); } KeyedHashAlgorithm algorithm = null; switch (algorithmName) { case SigningAlgorithm.HmacSHA1: algorithm = new HMACSHA1(); break; case SigningAlgorithm.HmacSHA256: algorithm = new HMACSHA256(); break; default: break; } //KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture)); if (null == algorithm) { throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use."); } try { algorithm.Key = Encoding.UTF8.GetBytes(key); byte[] bytes = algorithm.ComputeHash(data); return(Convert.ToBase64String(bytes)); } finally { algorithm.Clear(); } }
static void Main(string[] args) { // generate a key; 32 bytes * 8 bits/byte = 256 bits // should be a pre-generated value with high entropy var key = GenerateKey(); // calculate HMAC byte[] hash; using (var hmac = new HMACSHA256(key)) { var messageBytes = Encoding.Unicode.GetBytes(message); hash = hmac.ComputeHash(messageBytes); hmac.Clear(); } Console.WriteLine(Convert.ToBase64String(hash)); // SAMPLE OUTPUT: qNW++z2JXsuydyhNm+SKg7XvNv9sAZILXcK2Azp9Bco= Console.ReadKey(); }
} //compute hash from arguments and return hash value as string private static string GetHMACSHA256Hash(string text) { //create variables for computing hash and making it a string UnicodeEncoding UniCode = new UnicodeEncoding(); byte[] HashResult; byte[] msg = UniCode.GetBytes(text); HMACSHA256 hashString = new HMACSHA256(); string Str = ""; //compute hash with HMACSHA256 module and format output as string //convert bytes in HashResult to string values HashResult = hashString.ComputeHash(msg); foreach (byte x in HashResult) { Str += String.Format("{0:x2}", x); } //clear excess resource usage hashString.Clear(); return(Str); } //compute hash from arguments and return hash value as string
private void VerifySignatureInfo() { int ikid = 0; if (!int.TryParse(_Envelope.kid, out ikid)) { throw new ArgumentOutOfRangeException("Key ID should be a number more than 0, PassedVal:" + _Envelope.kid); } if (ikid > ConfigProvider.ConfigurationStore.LiveAuthKeyCount) { throw new ArgumentOutOfRangeException(string.Format("Key ID: {0}, is not configured properly or not loaded.", ikid)); } _CurrentSecretKey = ConfigProvider.ConfigurationStore.LiveAuthKeys[ikid]; byte[] bKey = SOSCodecs.UTF8Encoder.GetBytes(_CurrentSecretKey + "JWTSig"); SHA256Managed SHAprovider = SecurityCodecs.SHA256CryptoProvider; byte[] bCryptKey = SHAprovider.ComputeHash(bKey); byte[] bCombined = SOSCodecs.UTF8Encoder.GetBytes(_RawToken.Envelope + "." + _RawToken.Claims); SecurityCodecs codec = new SecurityCodecs(); HMACSHA256 HMACHACryptoProvider = codec.HMACSHA256Provider(bCryptKey); _IsTokenValid = SOSCodecs.UrlEncode(HMACHACryptoProvider.ComputeHash(bCombined)) == _RawToken.Signature; codec.Dispose(); SHAprovider.Clear(); SHAprovider.Dispose(); HMACHACryptoProvider.Clear(); HMACHACryptoProvider.Dispose(); }
protected virtual void Dispose( bool disposing) { if (disposing) { if (_stream != null) { _stream.Close(); _stream = null; } if (_decryptor != null) { _decryptor.Dispose(); _decryptor = null; } if (_hmac != null) { _hmac.Clear(); } } }
private byte[] Synthesis(XfyunTTSSettings settings, string text) { var apiSecret = settings.ApiSecret; var apiKey = settings.ApiKey; var appId = settings.AppId; if (string.IsNullOrEmpty(apiKey) || string.IsNullOrEmpty(apiSecret) || string.IsNullOrEmpty(appId)) { Logger.Error(strings.msgErrorEmptyApiSecretKey); _settingsControl.NotifyEmptyApiKey(); return(null); } var base64Text = Convert.ToBase64String(Encoding.UTF8.GetBytes(text)); if (base64Text.Length > 8000) { Logger.Error("Convert string too long. No more than 2000 chinese characters."); return(null); } using (var ws = SystemClientWebSocket.CreateClientWebSocket()) { // Connect var date = DateTime.UtcNow.ToString("R"); var sign = $"host: tts-api.xfyun.cn\ndate: {date}\nGET /v2/tts HTTP/1.1"; string sha; using (var hash = new HMACSHA256(Encoding.UTF8.GetBytes(apiSecret))) { sha = Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(sign))); hash.Clear(); } var authorization = $"api_key=\"{apiKey}\"," + $" algorithm=\"hmac-sha256\"," + $" headers=\"host date request-line\"," + $" signature=\"{sha}\""; var url = $"wss://tts-api.xfyun.cn/v2/tts?host=tts-api.xfyun.cn" + $"&date={WebUtility.UrlEncode(date).Replace("+", "%20")}" + $"&authorization={Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization))}"; try { ws.ConnectAsync(new Uri(url), _wsCancellationSource.Token).Wait(); } catch (AggregateException e) { var inner = e.InnerExceptions.First().GetBaseException(); if (inner is WebException webException) { var resp = (HttpWebResponse)webException.Response; string body = null; using (var stream = resp.GetResponseStream()) { if (stream != null) { var reader = new StreamReader(stream, string.IsNullOrEmpty(resp.CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(resp.CharacterSet)); body = reader.ReadToEnd(); } } Logger.Error($"Unable to connect to server: {body}"); switch (resp.StatusCode) { case HttpStatusCode.Unauthorized: case HttpStatusCode.Forbidden: Logger.Error(strings.msgErrorXfyunAuthFail); return(null); } } throw; } // Send request var request = new TTSRequest { Common = new TTSRequest.CommonParam { AppId = settings.AppId, }, Business = new TTSRequest.BusinessParam { Voice = settings.Voice, Pitch = settings.Pitch * 10, Speed = settings.Speed * 10, Volume = settings.Volume * 10, }, Data = new TTSRequest.DataParam { Status = 2, Text = base64Text, } }; ws.SendText(JsonConvert.SerializeObject(request), _wsCancellationSource); // Start receiving var buffer = new MemoryStream(); var session = new WebSocketHelper.Session(ws); while (true) { var message = WebSocketHelper.ReceiveNextMessage(session, _wsCancellationSource); Logger.Debug($"Received WS message\n{message}"); if (message.Type == WebSocketMessageType.Text) { var resp = JsonConvert.DeserializeObject <TTSResponse>(message.MessageStr); if (resp.Code == 0) { // Success! if (resp.Data != null) { var data = Convert.FromBase64String(resp.Data.Audio); buffer.Write(data, 0, data.Length); if (resp.Data.Status == 2) { // Complete! return(buffer.ToArray()); } } } else { Logger.Error($"Unexpected response code received: {resp.Code}: {resp.Message}"); switch (resp.Code) { case 10005: case 10313: Logger.Error(strings.msgErrorXfyunWrongAppId); break; case 11200: case 11201: Logger.Error(strings.msgErrorXfyunInsufficientApiQuota); break; } return(null); } } else if (message.Type == WebSocketMessageType.Binary) { throw new IOException("Unexpected binary message received"); } else if (message.Type == WebSocketMessageType.Close) { throw new IOException("Unexpected closing of connection"); } else { throw new ArgumentOutOfRangeException(); } } } }
public void Clear() { _algo.Clear(); }
/// <summary> /// Decrypts an string using AES /// </summary> /// <param name="data">The data to decrypt.</param> /// <param name="password">The password to use.</param> public static string DecryptString(byte[] data, string password) { byte[] plainText; // Read the salt from the array byte[] salt = new byte[32]; Buffer.BlockCopy(data, 0, salt, 0, salt.Length); // Create algorithms using (SymmetricAlgorithm encryptator = Aes.Create()) using (KeyedHashAlgorithm signer = new HMACSHA256()) { // Extract the signature byte[] signature = new byte[signer.HashSize / 8]; Buffer.BlockCopy(data, 32, signature, 0, signer.HashSize / 8); // Grab the rest of the data int payloadLength = data.Length - 32 - signature.Length; byte[] payload = new byte[payloadLength]; Buffer.BlockCopy(data, 32 + signature.Length, payload, 0, payloadLength); // Check the signature before anything else is done to detect tampering and avoid oracles byte[] computedSignature = SignData(password, payload, salt, encryptator, signer); if (!computedSignature.IsEqualsTo(signature)) { throw new CryptographicException("Invalid signature."); } // Clear the signer algorithm signer.Clear(); // Extract IV int ivLength = encryptator.BlockSize / 8; byte[] iv = new byte[ivLength]; byte[] cipherText = new byte[payload.Length - ivLength]; // Extract the data Buffer.BlockCopy(payload, 0, iv, 0, ivLength); Buffer.BlockCopy(payload, ivLength, cipherText, 0, payload.Length - ivLength); // Set encryptation key and IV encryptator.Key = KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA512, KeyDerivationIterationCount, encryptator.KeySize / 8); encryptator.IV = iv; // Decrypt the data using (var ms = new MemoryStream()) using (var crypto = new CryptoStream(ms, encryptator.CreateDecryptor(), CryptoStreamMode.Write)) { // Write to the stream crypto.Write(cipherText, 0, cipherText.Length); crypto.FlushFinalBlock(); // Get plain text plainText = ms.ToArray(); } // Clear algorithms encryptator.Clear(); } // Return the decrypted data return(Encoding.UTF8.GetString(plainText)); }