public void Test_Pbkdf2() { byte[] password = new byte[256]; byte[] salt = new byte[256]; _random.NextBytes(password); _random.NextBytes(salt); using (var hmac = new System.Security.Cryptography.HMACSHA1()) { Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024); System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 1024); Assert.IsTrue(CollectionUtilities.Equals(pbkdf2.GetBytes(1024), rfc2898DeriveBytes.GetBytes(1024)), "Pbkdf2 #1"); } //_random.NextBytes(password); //_random.NextBytes(salt); //using (var hmac = new System.Security.Cryptography.HMACSHA256()) //{ // CryptoConfig.AddAlgorithm(typeof(SHA256Cng), // "SHA256", // "SHA256Cng", // "System.Security.Cryptography.SHA256", // "System.Security.Cryptography.SHA256Cng"); // hmac.HashName = "System.Security.Cryptography.SHA256"; // Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024); // var h = pbkdf2.GetBytes(10); //} }
/** * Generate a one-time password * * @param integer $input : number used to seed the hmac hash function. * This number is usually a counter (HOTP) or calculated based on the current * timestamp (see TOTP class). * @return integer the one-time password */ public int GenerateOTP(Int64 input) { Byte[] secretBytes = Guid.Parse(this.secret).ToByteArray(); HMAC hashgenerator = new HMACSHA1(secretBytes); hashgenerator.ComputeHash(IntToByteString(input)); string hash = ""; foreach (byte b in hashgenerator.Hash) { hash += b.ToString("x2"); } List<int> hmac = new List<int>(); foreach (string s in hash.Split(2)) { hmac.Add(Int32.Parse(s, System.Globalization.NumberStyles.HexNumber)); } // The offset is the last nibble of the hash int offset = hmac[19] & 0xf; // Code is 4 bytes starting at the offset int code = (hmac[offset + 0] & 0x7F) << 24 | (hmac[offset + 1] & 0xFF) << 16 | (hmac[offset + 2] & 0xFF) << 8 | (hmac[offset + 3] & 0xFF); return code % (int)Math.Pow((double)10, (double)this.digits); }
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { Salt = salt; IterationCount = iterations; m_password = password; m_hmacsha1 = new HMACSHA1(password); Initialize(); }
internal static string GetOAuthHeader(Dictionary<string, string> parameters, string url, string comsumeSercret, string tokenSecret) { parameters = parameters.OrderBy(x => x.Key).ToDictionary(v => v.Key, v => v.Value); string concat = string.Empty; string OAuthHeader = "OAuth "; foreach (var key in parameters.Keys) { concat += key + "=" + parameters[key] + "&"; OAuthHeader += key + "=" + "\"" + parameters[key] + "\","; } concat = concat.Remove(concat.Length - 1, 1); concat = EncodeToUpper(concat); concat = "POST&" + EncodeToUpper(url) + "&" + concat; byte[] content = Encoding.UTF8.GetBytes(concat); HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(comsumeSercret + "&" + tokenSecret)); hmac.ComputeHash(content); string hash = Convert.ToBase64String(hmac.Hash); hash = hash.Replace("-", ""); OAuthHeader += "oauth_signature=\"" + EncodeToUpper(hash) + "\""; return OAuthHeader; }
public async Task<bool> GetData(string msisdn) { try { Tools.Tools.SetProgressIndicator(true); SystemTray.ProgressIndicator.Text = "fetching data"; var client = new VikingsApi(); OAuthUtility.ComputeHash = (key, buffer) => { using (var hmac = new HMACSHA1(key)) { return hmac.ComputeHash(buffer); } }; string json = await client.GetInfo(new AccessToken((string) IsolatedStorageSettings.ApplicationSettings["tokenKey"], (string) IsolatedStorageSettings.ApplicationSettings["tokenSecret"]), client.Balance, new KeyValuePair {name = "msisdn", content = msisdn}); if (Error.HandleError(json, "there seems to be no connection")) return false; Tools.Tools.SetProgressIndicator(false); Balance = new UserBalance(json); return true; } catch (Exception) { Message.ShowToast("Could not load bundle info, please try again later"); return false; } }
protected void Application_Start() { OAuthUtility.ComputeHash = (key, buffer) => { using (var hmac = new HMACSHA1(key)) { return hmac.ComputeHash(buffer); } }; AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); }
/// <summary> /// Generates a signature using the specified signatureType /// </summary> /// <param name="httpMethod">The http method used</param> /// <param name="url">The full url to be signed</param> /// <param name="parametersIn">The collection of parameters to sign</param> /// <param name="consumerSecret">The OAuth consumer secret used to generate the signature</param> /// <returns>A base64 string of the hash value</returns> public static string GenerateSignature(string httpMethod, Uri url, NameValueCollection parametersIn, string consumerSecret) { // Work with a copy of the parameters so the caller's data is not changed var parameters = new NameValueCollection(parametersIn); // https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 // The query component is parsed into a list of name/value pairs by treating it as an // "application/x-www-form-urlencoded" string, separating the names and values and // decoding them as defined by [W3C.REC - html40 - 19980424], Section 17.13.4. // // Unescape the query so that it is not doubly escaped by UrlEncodingParser. var querystring = new UrlEncodingParser(Uri.UnescapeDataString(url.Query)); parameters.Add(querystring); var signatureBase = GenerateSignatureBase(httpMethod, url, parameters); // Note that in LTI, the TokenSecret (second part of the key) is blank var hmacsha1 = new HMACSHA1 { Key = Encoding.ASCII.GetBytes($"{consumerSecret.ToRfc3986EncodedString()}&") }; var dataBuffer = Encoding.ASCII.GetBytes(signatureBase); var hashBytes = hmacsha1.ComputeHash(dataBuffer); return Convert.ToBase64String(hashBytes); }
public override void SetAuth(HttpWebRequest request, Stream body) { byte[] secretKey = Encoding.ASCII.GetBytes(Config.SECRET_KEY); using (HMACSHA1 hmac = new HMACSHA1(secretKey)) { string pathAndQuery = request.Address.PathAndQuery; byte[] pathAndQueryBytes = Encoding.ASCII.GetBytes(pathAndQuery); using (MemoryStream buffer = new MemoryStream()) { buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length); buffer.WriteByte((byte)'\n'); if (request.ContentType == "application/x-www-form-urlencoded" && body != null) { if (!body.CanSeek) { throw new Exception("stream can not seek"); } StreamUtil.Copy(body, buffer); body.Seek(0, SeekOrigin.Begin); } byte[] digest = hmac.ComputeHash(buffer.ToArray()); string digestBase64 = Base64UrlSafe.Encode(digest); string authHead = "QBox " + Config.ACCESS_KEY + ":" + digestBase64; request.Headers.Add("Authorization", authHead); } } }
public string GenerateValidationKey() { using (var validObj = new HMACSHA1()) { return BinaryToHex(validObj.Key); } }
public static string HOTP2(byte[] key, ulong counter, int digits = 6) { // compute SHA-1 HMAC of the key System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true); // convert the counter to bytes, check if the system is little endian and reverse if necessary byte[] counter_bytes = BitConverter.IsLittleEndian ? BitConverter.GetBytes(counter).Reverse().ToArray() : BitConverter.GetBytes(counter); // compute the hash using the counter value byte[] hmac_result = hmac.ComputeHash(counter_bytes); // get the last 4 bits of the HMAC Result to determine the offset int offset = hmac_result[hmac_result.Length - 1] & 0xf; // get the value of 4 bytes of the HMAC Result starting at the offset position int bin_code = (hmac_result[offset] & 0x7f) << 24 | (hmac_result[offset + 1] & 0xff) << 16 | (hmac_result[offset + 2] & 0xff) << 8 | (hmac_result[offset + 3] & 0xff); // HOTP = bin_code modulo 10^(digits) int hotp = bin_code % (int)Math.Pow(10, digits); // truncate the string to the number of significant digits return(hotp.ToString(String.Empty.PadRight(digits, '0'))); }
protected override string CreateSignature(string tokenSecret, string method, Uri uri, Dictionary<string, string> parameter) { //パラメタをソート済みディクショナリに詰替(OAuthの仕様) SortedDictionary<string, string> sorted = new SortedDictionary<string, string>(parameter); //URLエンコード済みのクエリ形式文字列に変換 string paramString = CreateQueryString(sorted); //アクセス先URLの整形 string url = string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath); //本来のアクセス先URLに再設定(api.twitter.com固定) if (!string.IsNullOrEmpty(_proxyHost) && url.StartsWith(uri.Scheme + "://" + _proxyHost)) url = url.Replace(uri.Scheme + "://" + _proxyHost, uri.Scheme + "://" + _apiHost); //署名のベース文字列生成(&区切り)。クエリ形式文字列は再エンコードする string signatureBase = String.Format("{0}&{1}&{2}", method, UrlEncode(url), UrlEncode(paramString)); //署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成(&区切り。アクセストークン秘密鍵なくても&残すこと) string key = UrlEncode(consumerSecret) + "&"; if (!string.IsNullOrEmpty(tokenSecret)) key += UrlEncode(tokenSecret); //鍵生成&署名生成 using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key))) { byte[] hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase)); return Convert.ToBase64String(hash); } }
//--- Extension Methods --- /// <summary> /// Add a Plug Pre-Handler to attach the appropriate auth header. /// </summary> /// <param name="plug">Plug instance to base operation on.</param> /// <param name="privateKey">Amazon S3 private key.</param> /// <param name="publicKey">Amazon S3 public key.</param> /// <returns>New Plug instance with pre-handler.</returns> public static Plug WithS3Authentication(this Plug plug, string privateKey, string publicKey) { return plug.WithPreHandler((verb, uri, normalizedUri, message) => { // add amazon date header (NOTE: this must be the real wall-time) var date = DateTime.UtcNow.ToString("r"); message.Headers[AWS_DATE] = date; // add authorization header var authString = new StringBuilder() .Append(verb) .Append("\n") .Append(message.Headers[DreamHeaders.CONTENT_MD5]) .Append("\n") .Append(message.ContentType.ToString()) .Append("\n") .Append("\n"); foreach(var header in message.Headers.OrderBy(x => x.Key.ToLowerInvariant(), StringComparer.Ordinal)) { if(!header.Key.StartsWithInvariantIgnoreCase("x-amz-")) { continue; } authString.AppendFormat("{0}:{1}\n", header.Key.ToLowerInvariant(), header.Value); } authString.Append(normalizedUri.Path); var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(privateKey)); var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(authString.ToString()))); message.Headers.Authorization = string.Format("AWS {0}:{1}", publicKey, signature); message.Headers.ContentType = message.ContentType; return message; }); }
public static byte[] ComputeCombinedKey(byte[] requestorEntropy, byte[] issuerEntropy, int keySizeInBits) { if (requestorEntropy == null) { throw new ArgumentNullException("requestorEntropy"); } if (issuerEntropy == null) { throw new ArgumentNullException("issuerEntropy"); } int num = ValidateKeySizeInBytes(keySizeInBits); byte[] array = new byte[num]; using (KeyedHashAlgorithm algorithm = new HMACSHA1()) { algorithm.Key = requestorEntropy; byte[] buffer = issuerEntropy; byte[] buffer3 = new byte[(algorithm.HashSize / 8) + buffer.Length]; byte[] buffer4 = null; try { try { int num2 = 0; while (num2 < num) { algorithm.Initialize(); buffer = algorithm.ComputeHash(buffer); buffer.CopyTo(buffer3, 0); issuerEntropy.CopyTo(buffer3, buffer.Length); algorithm.Initialize(); buffer4 = algorithm.ComputeHash(buffer3); for (int i = 0; i < buffer4.Length; i++) { if (num2 >= num) { continue; } array[num2++] = buffer4[i]; } } } catch { Array.Clear(array, 0, array.Length); throw; } return array; } finally { if (buffer4 != null) { Array.Clear(buffer4, 0, buffer4.Length); } Array.Clear(buffer3, 0, buffer3.Length); algorithm.Clear(); } } }
private string AuthorizationHeader(string status) { var oauth_token = UserToken; var oauth_token_secret = UserSecret; var oauth_consumer_key = AppToken; var oauth_consumer_secret = AppSecret; var oauth_version = "1.0"; var oauth_signature_method = "HMAC-SHA1"; var oauth_nonce = Convert.ToBase64String( new ASCIIEncoding().GetBytes( DateTime.Now.Ticks.ToString())); var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString(); var resource_url = "https://api.twitter.com/1.1/statuses/update.json"; var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}"; var baseString = string.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version, Uri.EscapeDataString(status) ); baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString)); var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret)); string oauth_signature; using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))) { oauth_signature = Convert.ToBase64String( hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString))); } var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + "oauth_token=\"{4}\", oauth_signature=\"{5}\", " + "oauth_version=\"{6}\""; var authHeader = string.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version) ); return authHeader; }
protected void decode(ref List <byte> buffer, int stanzaSize) { int size = stanzaSize; byte[] data = new byte[size]; byte[] dataReal = null; Buffer.BlockCopy(buffer.ToArray(), 0, data, 0, size); byte[] packet = new byte[size - 4]; byte[] hashServerByte = new byte[4]; Buffer.BlockCopy(data, 0, hashServerByte, 0, 4); Buffer.BlockCopy(data, 4, packet, 0, size - 4); System.Security.Cryptography.HMACSHA1 h = new System.Security.Cryptography.HMACSHA1(this.Encryptionkey); byte[] hashByte = new byte[4]; Buffer.BlockCopy(h.ComputeHash(packet, 0, packet.Length), 0, hashByte, 0, 4); // 20121107 not sure why the packet is indicated an ecrypted but the hmcash1 is incorrect if (hashServerByte.SequenceEqual(hashByte)) { this.buffer.RemoveRange(0, 4); dataReal = Encryption.WhatsappDecrypt(this.Encryptionkey, packet); for (int i = 0; i < size - 4; i++) { this.buffer[i] = dataReal[i]; } } else { throw new Exception("Hash doesnt match"); } }
/// <summary> /// Generates a pin by hashing a key and counter. /// </summary> static string GeneratePin(byte[] key, long counter) { const int SizeOfInt32 = 4; var CounterBytes = BitConverter.GetBytes(counter); if (BitConverter.IsLittleEndian) { //spec requires bytes in big-endian order Array.Reverse(CounterBytes); } var Hash = new HMACSHA1(key).ComputeHash(CounterBytes); var Offset = Hash[Hash.Length - 1] & 0xF; var SelectedBytes = new byte[SizeOfInt32]; Buffer.BlockCopy(Hash, Offset, SelectedBytes, 0, SizeOfInt32); if (BitConverter.IsLittleEndian) { //spec interprets bytes in big-endian order Array.Reverse(SelectedBytes); } var SelectedInteger = BitConverter.ToInt32(SelectedBytes, 0); //remove the most significant bit for interoperability per spec var TruncatedHash = SelectedInteger & 0x7FFFFFFF; //generate number of digits for given pin length var Pin = TruncatedHash % PinModulo; return Pin.ToString(CultureInfo.InvariantCulture).PadLeft(PinLength, '0'); }
public virtual string HmacHash(string key, string message) { var hmac = new HMACSHA1(Sha1Bytes(key)); byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(message)); return BitConverter.ToString(hashBytes).Replace("-", ""); }
protected internal Uri Sign(Uri _uri) { if (_uri == null) throw new ArgumentNullException("_uri"); if (string.IsNullOrWhiteSpace(this.Key)) throw new ArgumentException("Invalid signing key."); if (this.ClientId == null) throw new NullReferenceException("ClientID"); if (!this.ClientId.StartsWith("gme-")) throw new ArgumentException("A user ID must start with 'gme-'."); var _urlSegmentToSign = _uri.LocalPath + _uri.Query + "&client=" + this.ClientId; var _privateKey = SignableRequest.FromBase64UrlString(this.Key); byte[] _signature; using (var _algorithm = new HMACSHA1(_privateKey)) { _signature = _algorithm.ComputeHash(Encoding.ASCII.GetBytes(_urlSegmentToSign)); } return new Uri(_uri.Scheme + "://" + _uri.Host + _urlSegmentToSign + "&signature=" + SignableRequest.ToBase64UrlString(_signature)); }
public static Digest /*!*/ Initialize(Digest /*!*/ self, [NotNull] MutableString /*!*/ algorithmName) { Crypto.HMAC algorithm; #if SILVERLIGHT switch (algorithmName.ToString()) { case "SHA1": algorithm = new Crypto.HMACSHA1(); break; case "SHA256": algorithm = new Crypto.HMACSHA256(); break; default: algorithm = null; break; } #else algorithm = Crypto.HMAC.Create("HMAC" + algorithmName.ConvertToString()); #endif if (algorithm == null) { throw RubyExceptions.CreateRuntimeError("Unsupported digest algorithm ({0}).", algorithmName); } self._algorithm = algorithm; return(self); }
private static string Sign(string url, string appSid, string appKey) { // Add AppSid parameter. UriBuilder uriBuilder = new UriBuilder(url); if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) uriBuilder.Query = uriBuilder.Query.Substring(1) + "&appSID=" + appSid; else uriBuilder.Query = "appSID=" + appSid; // Remove final slash here as it can be added automatically. uriBuilder.Path = uriBuilder.Path.TrimEnd('/'); // Compute the hash. byte[] privateKey = Encoding.UTF8.GetBytes(appKey); HMACSHA1 algorithm = new HMACSHA1(privateKey); byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri); byte[] hash = algorithm.ComputeHash(sequence); string signature = Convert.ToBase64String(hash); // Remove invalid symbols. signature = signature.TrimEnd('='); signature = HttpUtility.UrlEncode(signature); // Convert codes to upper case as they can be updated automatically. signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper()); // Add the signature to query string. return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature); }
public static string HMACSHA1(string key, string message) { using (var hasher = new crypto.HMACSHA1(Encoding.UTF8.GetBytes(key))) { return(hasher.ComputeHash(Encoding.UTF8.GetBytes(message)).ToHexString()); } }
private static string EncodePassword(string password) { HMACSHA1 hash = new HMACSHA1 {Key = HexToByte(key)}; string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); return encodedPassword; }
public void SetupCrypto(BigInteger key) { byte[] ServerDecryptionKey = { 0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE }; byte[] ServerEncryptionKey = { 0xCC, 0x98, 0xAE, 0x04, 0xE8, 0x97, 0xEA, 0xCA, 0x12, 0xDD, 0xC0, 0x93, 0x42, 0x91, 0x53, 0x57 }; HMACSHA1 decryptHMAC = new HMACSHA1(ServerDecryptionKey); HMACSHA1 encryptHMAC = new HMACSHA1(ServerEncryptionKey); var decryptHash = decryptHMAC.ComputeHash(key.GetBytes()); var encryptHash = encryptHMAC.ComputeHash(key.GetBytes()); const int dropN = 1024; //1000 before WoTLK, 1024 now var buf = new byte[dropN]; ClientConnection.Decrypt = new ARC4(decryptHash); ClientConnection.Encrypt = new ARC4(encryptHash); ClientConnection.Decrypt.Process(buf, 0, buf.Length); ClientConnection.Encrypt.Process(buf, 0, buf.Length); }
/// <summary> /// The original code at /// http://www.codeproject.com/Articles/403355/Implementing-Two-Factor-Authentication-in-ASP-NET /// by Rick Bassham, http://www.codeproject.com/script/Membership/View.aspx?mid=4294419 /// under MIT License, http://opensource.org/licenses/mit-license.php /// /// Modified by HouYu Li <*****@*****.**> /// </summary> /// <param name="secret"></param> /// <param name="iterationNumber"></param> /// <param name="digits"></param> /// <returns></returns> public static string GeneratePassword(string secret, long iterationNumber, int digits = 6) { byte[] counter = BitConverter.GetBytes(iterationNumber); if (BitConverter.IsLittleEndian) Array.Reverse(counter); byte[] key = Base32Decode.Decode(secret); HMACSHA1 hmac = new HMACSHA1(key, true); byte[] hash = hmac.ComputeHash(counter); int offset = hash[hash.Length - 1] & 0xf; int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); int password = binary % (int)Math.Pow(10, digits); return password.ToString(new string('0', digits)); }
/// <summary> /// Generates the OAUTH1 signature. /// </summary> /// <returns> /// The signature string. /// </returns> /// <param name='usingProtocol'> /// Should be POST. /// </param> /// <param name='forUrl'> /// The target URL for the authentication. /// </param> /// <param name='withParameters'> /// The source HTTP headers, including oauth_* headers. /// </param> string GenerateSignature(string usingProtocol, string forUrl, Dictionary <string, string> withParameters) { // Create the base string. System.Text.StringBuilder signatureBaseString = new System.Text.StringBuilder(); signatureBaseString.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0}&{1}&", usingProtocol, UrlEncode(new System.Uri(forUrl).ToString())); foreach (KeyValuePair <string, string> aPair in withParameters) { signatureBaseString.AppendFormat(@"{0}%3D{1}%26", aPair.Key, UrlEncode(aPair.Value)); } // Remove the trailing %26 signatureBaseString.Remove(signatureBaseString.Length - 3, 3); // Create the hash key. string requestSecret = ""; if (!string.IsNullOrEmpty(m_secretAccessToken)) { requestSecret = m_secretAccessToken; } else if (!string.IsNullOrEmpty(m_secretRequest)) { requestSecret = m_secretRequest; } string key = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}&{1}", m_secretConsumer, UrlEncode(requestSecret)); System.Security.Cryptography.HMACSHA1 hash = new System.Security.Cryptography.HMACSHA1(System.Text.Encoding.ASCII.GetBytes(key)); byte[] signatureBytes = hash.ComputeHash( System.Text.Encoding.ASCII.GetBytes(signatureBaseString.ToString())); return(System.Convert.ToBase64String(signatureBytes)); }
//EncodePassword:Encrypts, Hashes, or leaves the password clear based on the PasswordFormat. public string EncodePassword(string password) { var encodedPassword = password; var hash = new HMACSHA1 { Key = HexToByte(_machineKey.ValidationKey) }; encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); return encodedPassword; }
public async Task<bool> GetSimInfo() { Tools.Tools.SetProgressIndicator(true); try { Tools.Tools.SetProgressIndicator(true); SystemTray.ProgressIndicator.Text = "loading sims"; var client = new VikingsApi(); OAuthUtility.ComputeHash = (key, buffer) => { using (var hmac = new HMACSHA1(key)) { return hmac.ComputeHash(buffer); } }; string json = await client.GetInfo(new AccessToken((string) IsolatedStorageSettings.ApplicationSettings["tokenKey"], (string) IsolatedStorageSettings.ApplicationSettings["tokenSecret"]), client.Sim, new KeyValuePair {content = "1", name = "alias"}); Sims = JsonConvert.DeserializeObject<Sim[]>(json); Tools.Tools.SetProgressIndicator(false); return true; } catch (Exception) { Message.ShowToast("Could not load sim information, please try again later"); return false; } }
private static bool IsValidRequest(HttpActionContext context, string authToken, string urlOverride = null) { var value = new StringBuilder(); // Take the host URL from the request, or use the URL override if there is one var fullUrl = string.IsNullOrEmpty(urlOverride) ? context.Request.RequestUri.ToString() : urlOverride; value.Append(fullUrl); var request = HttpContext.Current.Request; // If POST request, concatenate the key-value pairs in the request if (context.Request.Method == HttpMethod.Post) { var sortedKeys = request.Form.AllKeys.OrderBy(k => k, StringComparer.Ordinal).ToList(); foreach (var key in sortedKeys) { value.Append(key); value.Append(request.Form[key]); } } // Create signature using AuthToken as key var sha1 = new HMACSHA1(Encoding.UTF8.GetBytes(authToken)); var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(value.ToString())); var encoded = Convert.ToBase64String(hash); var sig = request.Headers["X-Twilio-Signature"]; // Compare our signatures return sig == encoded; }
/// <summary> /// Generates a pin by hashing a key and counter. /// </summary> private static string GeneratePin(byte[] key, long counter) { //Get counter bytes (in big endian order) var counterBytes = BitConverter.GetBytes(counter); if (BitConverter.IsLittleEndian) Array.Reverse(counterBytes); byte[] hash; using (var hmac = new HMACSHA1(key)) hash = hmac.ComputeHash(counterBytes); var offset = hash[hash.Length - 1] & 0xF; var selectedBytes = new byte[sizeof(int)]; Buffer.BlockCopy(hash, offset, selectedBytes, 0, sizeof(int)); //spec interprets bytes in big-endian order if (BitConverter.IsLittleEndian) Array.Reverse(selectedBytes); var selectedInteger = BitConverter.ToInt32(selectedBytes, 0); //remove the most significant bit for interoperability per spec var truncatedHash = selectedInteger & 0x7FFFFFFF; //generate number of digits for given pin length var pin = truncatedHash % _pinModulo; return pin.ToString(CultureInfo.InvariantCulture).PadLeft(PIN_LENGTH, '0'); }
protected string GetCodeInternal(string secret, ulong challengeValue) { ulong chlg = challengeValue; byte[] challenge = new byte[8]; for (int j = 7; j >= 0; j--) { challenge[j] = (byte)((int)chlg & 0xff); chlg >>= 8; } var key = Base32Encoding.ToBytes(secret); for (int i = secret.Length; i < key.Length; i++) { key[i] = 0; } HMACSHA1 mac = new HMACSHA1(key); var hash = mac.ComputeHash(challenge); int offset = hash[hash.Length - 1] & 0xf; int truncatedHash = 0; for (int j = 0; j < 4; j++) { truncatedHash <<= 8; truncatedHash |= hash[offset + j]; } truncatedHash &= 0x7FFFFFFF; truncatedHash %= 1000000; string code = truncatedHash.ToString(); return code.PadLeft(6, '0'); }
private static dynamic ConstructRequestBody(string publickey, string privatekey, dynamic data) { Dictionary<string, dynamic> query = new Dictionary<string, dynamic>(); query.Add("key", publickey); query.Add("nonce", new Random(1000).Next().ToString()); query.Add("timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:ssZ")); var signingValue = new StringBuilder(); var signedValue = string.Empty; foreach (var s in query.Values.ToArray().OrderBy(s => s)) signingValue.Append(s); Logger.Debug(string.Format("signed value:{0}", signingValue.ToString())); using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(privatekey))) { var hashValue = hmac.ComputeHash(Encoding.ASCII.GetBytes(signingValue.ToString())); signedValue = Convert.ToBase64String(hashValue); } query.Add("sign", signedValue); query.Add("data",data); return new { key = query["key"], nonce = int.Parse(query["nonce"]), timestamp = query["timestamp"], sign = query["sign"], data = query["data"] }; }
public string GetSignature() { var policy64 = GetPolicyInBase64(); byte[] b64Key = Encoding.ASCII.GetBytes(CManager.Settings.AWSSecretAccessKey); var hmacSha1 = new HMACSHA1(b64Key); return Convert.ToBase64String(hmacSha1.ComputeHash(Encoding.ASCII.GetBytes(policy64))); }
public static string ComputeHash(string qs) { byte[] textBytes = Encoding.UTF8.GetBytes(qs); HMACSHA1 hashAlgorithm = new HMACSHA1(Security.HexToByteArray(_hashKey)); byte[] hash = hashAlgorithm.ComputeHash(textBytes); return Security.ByteArrayToHex(hash); }
public static string Generate(byte[] pbSecret, ulong uFactor, uint uCodeDigits, bool bAddChecksum, int iTruncationOffset) { byte[] pbText = MemUtil.UInt64ToBytes(uFactor); Array.Reverse(pbText); // Big-Endian HMACSHA1 hsha1 = new HMACSHA1(pbSecret); byte[] pbHash = hsha1.ComputeHash(pbText); uint uOffset = (uint)(pbHash[pbHash.Length - 1] & 0xF); if((iTruncationOffset >= 0) && (iTruncationOffset < (pbHash.Length - 4))) uOffset = (uint)iTruncationOffset; uint uBinary = (uint)(((pbHash[uOffset] & 0x7F) << 24) | ((pbHash[uOffset + 1] & 0xFF) << 16) | ((pbHash[uOffset + 2] & 0xFF) << 8) | (pbHash[uOffset + 3] & 0xFF)); uint uOtp = (uBinary % vDigitsPower[uCodeDigits]); if(bAddChecksum) uOtp = ((uOtp * 10) + CalculateChecksum(uOtp, uCodeDigits)); uint uDigits = (bAddChecksum ? (uCodeDigits + 1) : uCodeDigits); return uOtp.ToString().PadLeft((int)uDigits, '0'); }
public static string GetAuthorizationHeader(string macKeyIdentifier, string macKey, string macAlgorithm, string method, Uri uri) { TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); string timestamp = ((int)t.TotalSeconds).ToString(); string nonce = new Random().Next().ToString(); string normalizedString = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n\n", timestamp, nonce, method, uri.PathAndQuery, uri.Host, uri.Port); HashAlgorithm hashGenerator = null; if (macAlgorithm == "hmac-sha-256") { hashGenerator = new HMACSHA256(Encoding.ASCII.GetBytes(macKey)); } else if (macAlgorithm == "hmac-sha-1") { hashGenerator = new HMACSHA1(Encoding.ASCII.GetBytes(macKey)); } else { throw new InvalidOperationException("Unsupported MAC algorithm"); } string hash = System.Convert.ToBase64String(hashGenerator.ComputeHash(Encoding.ASCII.GetBytes(normalizedString))); StringBuilder authorizationHeader = new StringBuilder(); authorizationHeader.AppendFormat(@"id=""{0}"",ts=""{1}"",nonce=""{2}"",mac=""{3}""", macKeyIdentifier, timestamp, nonce, hash); return authorizationHeader.ToString(); }
protected static byte[] HMAC(byte[] data, string key) { using (var hmac = new HMACSHA1(data, true)) { return hmac.ComputeHash(Encoding.UTF8.GetBytes(key)); } }
public static string GeneratePassword(string secret, long iterationNumber, int digits = 6) { byte[] counter = BitConverter.GetBytes(iterationNumber); if (BitConverter.IsLittleEndian) { Array.Reverse(counter); } byte[] key = Encoding.ASCII.GetBytes(secret); System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true); byte[] hash = hmac.ComputeHash(counter); int offset = hash[hash.Length - 1] & 0xf; int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); int password = binary % (int)Math.Pow(10, digits); // 6 digits return(password.ToString(new string('0', digits))); }
/// <summary> /// Generate salt from password. /// </summary> /// <param name="password">Password string.</param> /// <returns>Salt bytes.</returns> private byte[] SaltFromPassword(string password) { byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password); System.Security.Cryptography.HMACSHA1 hmac; hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes); byte[] salt = hmac.ComputeHash(passwordBytes); return(salt); }
public static byte[] HMACSHA1(byte[] Data, byte[] Key, int Offset, int Length) { byte[] destinationArray = new byte[Data.Length]; Array.Copy(Data, Offset, destinationArray, 0, Data.Length); byte[] array = new System.Security.Cryptography.HMACSHA1(Key).ComputeHash(destinationArray); Array.Resize <byte>(ref array, 0x10); return(array); }
private void CreatePasswordHash(string password, out byte[] passHash, out byte[] passSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA1()) { passSalt = hmac.Key; passHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); } }
/// <summary> /// Computes the "Hi()"-formula which is part of the client's response /// to the server challenge. /// </summary> /// <param name="password">The supplied password to use.</param> /// <param name="salt">The salt received from the server.</param> /// <param name="count">The iteration count.</param> /// <returns>An array of bytes containing the result of the /// computation of the "Hi()"-formula.</returns> /// <remarks>Hi is, essentially, PBKDF2 with HMAC as the /// pseudorandom function (PRF) and with dkLen == output length of /// HMAC() == output length of H(). (Refer to RFC 5802, p.6)</remarks> private byte[] Hi(string password, string salt, int count) { byte[] passwordBytes = Encoding.ASCII.GetBytes(password); // The salt is sent by the server as a base64-encoded string. byte[] saltBytes = Convert.FromBase64String(salt); HMAC hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes); return(PBKDF2(20, passwordBytes, saltBytes, count, hmac)); }
/// <summary> /// 加密 /// </summary> /// <param name="content"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] Encrypt(byte[] content, byte[] key) { //HMACSHA1加密 System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(); hmacsha1.Key = key; byte[] dataBuffer = content; byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer); return(hashBytes); }
/// <summary> /// 加密 /// </summary> /// <param name="content"></param> /// <param name="key"></param> /// <param name="encoding"></param> /// <returns></returns> public static byte[] Encrypt(string content, string key, Encoding encoding) { //HMACSHA1加密 System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(); hmacsha1.Key = encoding.GetBytes(key); byte[] dataBuffer = encoding.GetBytes(content); byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer); return(hashBytes); }
/// <summary> /// HMACSHA1 加密 /// </summary> /// <param name="plainText"></param> /// <returns></returns> public static string ToHMACSHA1(string secret, string mk) { var hmacsha1 = new System.Security.Cryptography.HMACSHA1(); hmacsha1.Key = Encoding.UTF8.GetBytes(secret); byte[] dataBuffer = Encoding.UTF8.GetBytes(mk); byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer); return(Convert.ToBase64String(hashBytes)); }
private string GetHashString(string sPassword, string salt) { HashAlgorithm hash = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(salt)); byte[] hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(sPassword)); hash.Clear(); return(BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLower()); }
public String CreaHash(String cadena, String llave) { System.Text.UTF8Encoding sEncoding = new System.Text.UTF8Encoding(); Byte[] key = sEncoding.GetBytes(llave); Byte[] Text = sEncoding.GetBytes(cadena); System.Security.Cryptography.HMACSHA1 sHMACSHA1 = new System.Security.Cryptography.HMACSHA1(key); Byte[] HashCode = sHMACSHA1.ComputeHash(Text); String hash = BitConverter.ToString(HashCode).Replace("-", "").ToUpper(); return(hash); }
// hmacSHA1加密方法 public static string HmacSha1Sign(string text, string key) { byte[] byteData = Encoding.UTF8.GetBytes(text); byte[] byteKey = Encoding.UTF8.GetBytes(key); System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(byteKey); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(Stream.Null, hmac, System.Security.Cryptography.CryptoStreamMode.Write); cs.Write(byteData, 0, byteData.Length); cs.Close(); return(Convert.ToBase64String(hmac.Hash)); }
private bool Verify(int version, string privateMac, string privateHash, string passphrase, string keyTypeName, string encryptionName, string comment, byte[] publicBlob, byte[] privateBlob) { byte[] macData; using (MemoryStream macDataBuff = new MemoryStream()) { if (version == 1) { WriteMacData(macDataBuff, privateBlob); } else { WriteMacData(macDataBuff, keyTypeName); WriteMacData(macDataBuff, encryptionName); WriteMacData(macDataBuff, comment); WriteMacData(macDataBuff, publicBlob); WriteMacData(macDataBuff, privateBlob); } macDataBuff.Close(); macData = macDataBuff.ToArray(); } if (privateMac != null) { SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] a = Encoding.ASCII.GetBytes("putty-private-key-file-mac-key"); sha1.TransformBlock(a, 0, a.Length, null, 0); byte[] b = Encoding.UTF8.GetBytes(passphrase); sha1.TransformFinalBlock(b, 0, b.Length); byte[] key = sha1.Hash; sha1.Clear(); System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(key); byte[] hash = hmacsha1.ComputeHash(macData); hmacsha1.Clear(); string mac = BinToHex(hash); return(mac == privateMac); } else if (privateHash != null) { SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(macData); sha1.Clear(); string mac = BinToHex(hash); return(mac == privateHash); } else { return(true); } }
public void init(byte[] key) { if (key.Length > bsize) { byte[] tmp = new byte[bsize]; Array.Copy(key, 0, tmp, 0, bsize); key = tmp; } // SecretKeySpec skey=new SecretKeySpec(key, "HmacSHA1"); // mac=Mac.getInstance("HmacSHA1"); // mac.init(skey); mentalis_mac = new System.Security.Cryptography.HMACSHA1(key); cs = new System.Security.Cryptography.CryptoStream(System.IO.Stream.Null, mentalis_mac, System.Security.Cryptography.CryptoStreamMode.Write); }
/// <summary> /// Get the Cart Signature used in the "signature" /// form field that is posted to Google Checkout. /// </summary> /// <param name="cart">The Cart Xml returned from the /// <see cref="GCheckout.Checkout.CheckoutShoppingCartRequest.GetXml"/> /// method.</param> /// <param name="merchantKey">Your Google Merchant Key</param> /// <returns>A Base64 encoded string of the cart signature</returns> public static string GetCartSignature(byte[] cart, string merchantKey) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] key = encoding.GetBytes(merchantKey); using (System.Security.Cryptography.HMACSHA1 cryptobj = new System.Security.Cryptography.HMACSHA1(key)) { string retVal = System.Convert.ToBase64String(cryptobj.ComputeHash(cart)); cryptobj.Clear(); return(retVal); } }
private static string GetSignature(string url, string method, string nonce, string timestamp, string token, string tokenSecret, Dictionary <string, object> parameters) { var dict = new Dictionary <string, object>(); dict.Add("oauth_consumer_key", TumblrConsumerKey); dict.Add("oauth_nonce", nonce.ToString()); dict.Add("oauth_signature_method", "HMAC-SHA1"); dict.Add("oauth_timestamp", timestamp); dict.Add("oauth_token", token); dict.Add("oauth_version", "1.0"); var sigBase = new StringBuilder(); var first = true; foreach (var d in (parameters == null ? dict : dict.Union(parameters)).OrderBy(p => p.Key)) { if (!first) { sigBase.Append("&"); } first = false; if (d.Key.StartsWith("data")) { sigBase.Append(d.Key); } else { UrlEncode(sigBase, d.Key); } sigBase.Append("="); if (d.Value is byte[]) { EncodeSigStream(sigBase, (byte[])d.Value); } else { UrlEncode(sigBase, d.Value.ToString()); } } String SigBaseString = method.ToUpper() + "&"; SigBaseString += UrlEncode(url) + "&" + UrlEncode(sigBase.ToString(), false); var keyMaterial = Encoding.UTF8.GetBytes(TumblrConsumerSecret + "&" + tokenSecret); var HmacSha1Provider = new System.Security.Cryptography.HMACSHA1 { Key = keyMaterial }; return(Convert.ToBase64String(HmacSha1Provider.ComputeHash(Encoding.UTF8.GetBytes(SigBaseString)))); }
private bool VerifyPassHash(string password, byte[] passwordHash, byte[] passwordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA1(passwordSalt)) { var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); for (int i = 0; i < computedHash.Length; i++) { if (computedHash[i] != passwordHash[i]) { return(false); } } return(true); } }
private static string HMACSHA1(string secret, string data) { System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.Default.GetBytes(secret)); byte [] dataHMAC = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(data)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < dataHMAC.Length; i++) { sBuilder.Append(dataHMAC[i].ToString("x2")); } return(sBuilder.ToString()); }
//原型HmacSha1 public static string HmacSha1(string szString, string szKey) { System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(); hmacsha1.Key = Encoding.UTF8.GetBytes(szKey); byte[] dataBuffer = Encoding.UTF8.GetBytes(szString); byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer); StringBuilder ret = new StringBuilder(); foreach (byte b in hashBytes) { ret.AppendFormat("{0:X2}", b); } return(ret.ToString().ToLower()); }
protected void Page_Load(object sender, EventArgs e) { //Need to replace the last part of URL("your-vanityUrlPart") with your Testing/Live URL //formPostUrl = "/comingsoon"; //formPostUrl = "https://sandbox.citruspay.com/sslperf/jaslokhospital"; formPostUrl = "https://www.citruspay.com/jaslokhospital"; //Need to change with your Secret Key // string secret_key = "66fc8c3cca181b8954338bb5d5bd0cbb18b99b6d"; string secret_key = "ed70df7a017654499542ff0a5515812824b74142"; //Need to change with your Vanity URL Key from the citrus panel vanityUrl = "jaslokhospital"; //Should be unique for every transaction merchantTxnId = System.DateTime.Now.ToString("yyyyMMddHHmmssffff"); if (Request.QueryString["reg"] != null) { objDAEntities.FacilityName = "PermenantRegistration"; objDAEntities.BookinDateTime = Convert.ToDateTime(DateTime.Now.ToString()); Session["permenantRegistration"] = objDAEntities; Session["Amount"] = 100; } orderAmount = Session["Amount"].ToString(); //Need to change with your Order Amount // orderAmount = "10.00";// Request.QueryString["Amount"]; currency = "INR"; string data = vanityUrl + orderAmount + merchantTxnId + currency; System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key)); System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data)); securitySignature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower(); UserInfo user = UserController.Instance.GetCurrentUserInfo(); UserName = user.Username; //Session["Amount"] = null; returnUrl = "http://" + Request.ServerVariables["SERVER_NAME"] + "/PaymentResponse.aspx"; notifyUrl = returnUrl; //Response.Redirect("/PaymentResponse.aspx"); //Response.Write("txm:" + merchantTxnId + " " + securitySignature); }
public bool trySolvingHashedHost(string host) { if (this.host != null) { return(this.host.Equals(host)); } using (var hmac = new HMACSHA1(hostHashSalt)) { if (hmac.ComputeHash(Encoding.ASCII.GetBytes(host)).SequenceEqual(hostHash)) { this.host = host; this.listViewItem.SubItems[0].Text = host; return(true); } } return(false); }
public void ExampleScript() { // Turn input string into a byte array. var input = System.Text.Encoding.Unicode.GetBytes("Plain Text"); // Create an instance of the Rijndael class. System.Security.Cryptography.RijndaelManaged cipher; cipher = new System.Security.Cryptography.RijndaelManaged(); // Calculate salt bytes to make it harder to guess key by using a dictionary attack. var password = System.Text.Encoding.UTF8.GetBytes("password"); var hmac = new System.Security.Cryptography.HMACSHA1(password); var salt = hmac.ComputeHash(password); // Generate Secret Key from the password and salt. // Note: Set number of iterations to 10 in order for JavaScript example to work faster. var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10); // Create a encryptor from the existing SecretKey bytes by using // 32 bytes (256 bits) for the secret key and // 16 bytes (128 bits) for the initialization vector (IV). var key = secretKey.GetBytes(32); var iv = secretKey.GetBytes(16); var cryptor = cipher.CreateEncryptor(key, iv); // Create new Input. var inputBuffer = new System.Byte[input.Length]; // Copy data bytes to input buffer. System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length); // Create a MemoryStream to hold the output bytes. var stream = new System.IO.MemoryStream(); // Create a CryptoStream through which we are going to be processing our data. var mode = System.Security.Cryptography.CryptoStreamMode.Write; var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode); // Start the crypting process. cryptoStream.Write(inputBuffer, 0, inputBuffer.Length); // Finish crypting. cryptoStream.FlushFinalBlock(); // Convert data from a memoryStream into a byte array. var outputBuffer = stream.ToArray(); // Close both streams. stream.Close(); //cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. var base64String = System.Convert.ToBase64String(outputBuffer); // base64String = laFf3eKu9tzB2XksJjd8EVM3PA9O30wz0Y+X3nyelW4= }
public static bool ChangePassword(string userName, string userPassword = "", string newPassword = "", bool forceChange = false) { if (string.IsNullOrWhiteSpace(newPassword)) { return(false); } if (forceChange == false && string.IsNullOrWhiteSpace(userPassword)) { return(false); } var accounts = ReadAccountCSV(); var user = accounts.FirstOrDefault(x => x.UserName == userName.Trim()); if (user == null) { return(false); } var validPassword = !forceChange?VerifyPasswordHash(userPassword, user.PasswordSalt, user.PasswordHash) : true; if (validPassword) { // Overwrite with new PasswordHash using (var hmac = new System.Security.Cryptography.HMACSHA1()) // HMACSHA512 { user.PasswordSalt = hmac.Key; user.PasswordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(newPassword)); } accounts.Where(x => x.UserName == userName).ToList().ForEach(x => { x.PasswordSalt = user.PasswordSalt; x.PasswordHash = user.PasswordHash; }); WriteAccountCSV(accounts); return(true); } else { return(false); } }
byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt, bool fips) { /// <summary>Encrypt by using AES-256 algorithm.</summary> // Create an instance of the Rijndael class. var cipher = fips ? new System.Security.Cryptography.AesCryptoServiceProvider() as SymmetricAlgorithm : new System.Security.Cryptography.RijndaelManaged(); // Calculate salt to make it harder to guess key by using a dictionary attack. var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes); var salt = hmac.ComputeHash(passwordBytes); // Generate Secret Key from the password and salt. // Note: Set number of iterations to 10 in order for JavaScript example to work faster. var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10); // Create a encryptor from the existing SecretKey bytes by using // 32 bytes (256 bits) for the secret key and // 16 bytes (128 bits) for the initialization vector (IV). var key = secretKey.GetBytes(32); var iv = secretKey.GetBytes(16); // Get cryptor as System.Security.Cryptography.ICryptoTransform class. var cryptor = encrypt ? cipher.CreateEncryptor(key, iv) : cipher.CreateDecryptor(key, iv); // Create new Input. var inputBuffer = new byte[dataBytes.Length]; // Copy data bytes to input buffer. System.Buffer.BlockCopy(dataBytes, 0, inputBuffer, 0, inputBuffer.Length); // Create a MemoryStream to hold the output bytes. var stream = new System.IO.MemoryStream(); // Create a CryptoStream through which we are going to be processing our data. var mode = System.Security.Cryptography.CryptoStreamMode.Write; var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode); // Start the crypting process. cryptoStream.Write(inputBuffer, 0, inputBuffer.Length); // Finish crypting. cryptoStream.FlushFinalBlock(); // Convert data from a memoryStream into a byte array. var outputBuffer = stream.ToArray(); // Close both streams. stream.Close(); cryptoStream.Close(); return(outputBuffer); }
private void Initialize(byte[] secret, byte[] label, byte[] seed) { int s_half = (secret.Length + 1) / 2; byte[] s1 = new byte[s_half]; byte[] s2 = new byte[s_half]; System.Buffer.BlockCopy(secret, 0, s1, 0, s_half); System.Buffer.BlockCopy(secret, secret.Length - s_half, s2, 0, s_half); m_s1 = s1; m_s2 = s2; m_ls = new byte[label.Length + seed.Length]; System.Buffer.BlockCopy(label, 0, m_ls, 0, label.Length); System.Buffer.BlockCopy(seed, 0, m_ls, label.Length, seed.Length); m_md5 = new SslSharp.Security.Cryptography.HMACMD5(s1); m_sha1 = new HMACSHA1(s2); }