Exemplo n.º 1
0
        private void ComputeNextBlock(HMac hash)
        {
            BigEndian.CopyBytes(m_blockNumber, m_saltWithBlock, m_saltWithBlock.Length - 4);

            byte[] final = new byte[hash.GetMacSize()];
            byte[] tmp   = new byte[hash.GetMacSize()];

            //InitialPass: U1 = PRF(Password, Salt || INT_32_BE(i))
            hash.Reset();
            hash.BlockUpdate(m_saltWithBlock, 0, m_saltWithBlock.Length);
            hash.DoFinal(final, 0);

            final.CopyTo(tmp, 0);

            for (int iteration = 1; iteration < m_iterations; iteration++)
            {
                //U2 = PRF(Password, U1)
                //hash.Reset();
                hash.BlockUpdate(tmp, 0, tmp.Length);
                hash.DoFinal(tmp, 0);
                for (int x = 0; x < tmp.Length; x++)
                {
                    final[x] ^= tmp[x];
                }
            }

            m_blockNumber++;
            foreach (var b in final)
            {
                m_results.Enqueue(b);
            }
        }
Exemplo n.º 2
0
        private Byte[] P_hash(Byte[] secret, Byte[] seed, Int32 size, IDigest digest)
        {
            var needed = size;

            var md  = new HMac(digest);
            var key = new KeyParameter(secret);

            md.Init(key);

            // A_0 is initialized with seed
            var a0 = new Byte[seed.Length];

            Array.Copy(seed, 0, a0, 0, a0.Length);

            // A_i is HMAC of previous A
            var aI = new Byte[md.GetMacSize()];

            md.BlockUpdate(a0, 0, a0.Length);
            md.DoFinal(aI, 0);
            md.Reset();
            var ret = new Byte[needed];

            var outBuff = new Byte[md.GetMacSize()];

            while (needed > 0)
            {
                md.Init(key);
                // Add to return value
                md.BlockUpdate(aI, 0, aI.Length);
                md.BlockUpdate(seed, 0, seed.Length);
                md.DoFinal(outBuff, 0);
                md.Reset();

                var lenToCopy = needed < md.GetMacSize()? needed : md.GetMacSize();
                Array.Copy(outBuff, 0, ret, size - needed, lenToCopy);

                // Update new A
                md.Init(key);
                md.BlockUpdate(aI, 0, aI.Length);
                md.DoFinal(aI, 0);
                md.Reset();

                // Update needed field
                needed -= md.GetMacSize();
            }

            return(ret);
        }
Exemplo n.º 3
0
        public Packet ChannelDecrypt(ICipherSetRemoteInfo channelInfo, Packet outer)
        {
            // We gotta have the primary components and something to decrypt
            if (outer.Body.Length < 25)
            {
                return(null);
            }

            var ci = (CS1ARemoteInfo)channelInfo;

            // Rip apart our packet
            byte[] token         = outer.Body.Take(16).ToArray();
            byte[] iv            = outer.Body.Skip(16).Take(4).ToArray();
            byte[] encryptedData = outer.Body.Skip(20).Take(outer.Body.Length - 24).ToArray();
            byte[] dataMac       = outer.Body.Skip(outer.Body.Length - 4).Take(4).ToArray();

            // Make sure we're on the right channel
            if (!token.SequenceEqual(ci.Token))
            {
                return(null);
            }

            // Validate us some hmac
            byte[] hmacKey = new byte[20];
            Buffer.BlockCopy(ci.DecryptionKey, 0, hmacKey, 0, 16);
            Buffer.BlockCopy(iv, 0, hmacKey, 16, 4);

            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(hmacKey));
            hmac.BlockUpdate(encryptedData, 0, encryptedData.Length);
            byte[] mac = new byte[hmac.GetMacSize()];
            hmac.DoFinal(mac, 0);
            var foldedMac = Helpers.Fold(mac, 3);

            if (!foldedMac.SequenceEqual(dataMac))
            {
                // Get out of here with your bad data
                return(null);
            }

            // Everything seems ok.  Get it decrypted
            byte[] aesIV = new byte[16];
            Buffer.BlockCopy(iv, 0, aesIV, 0, 4);
            Array.Clear(aesIV, 4, 12);

            var cipher     = new SicBlockCipher(new AesFastEngine());
            var parameters = new ParametersWithIV(new KeyParameter(ci.DecryptionKey), aesIV);

            cipher.Init(false, parameters);

            var decryptedData = new byte[encryptedData.Length];
            BufferedBlockCipher bufferCipher = new BufferedBlockCipher(cipher);
            var offset = bufferCipher.ProcessBytes(encryptedData, decryptedData, 0);

            bufferCipher.DoFinal(decryptedData, offset);

            // Build a packet and ship it off
            return(Packet.DecodePacket(decryptedData));
        }
Exemplo n.º 4
0
        /// <summary>
        /// See <see cref="IRequest.GetUri()"/>.
        /// </summary>
        /// <returns>The <see cref="Uri"/>.</returns>
        public virtual Uri GetUri()
        {
            var scheme      = this.IsSsl ? "https://" : "http://";
            var queryString = string.Join("&", this.GetQueryStringParameters().Select(x =>
                                                                                      x.Value == null
                    ? Uri.EscapeDataString(x.Key)
                    : Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value)));
            var uri = new Uri(scheme + this.BaseUrl + "?" + queryString);

            if (this.ClientId == null)
            {
                return(uri);
            }

            var url        = uri.LocalPath + uri.Query + "&client=" + this.ClientId;
            var bytes      = Encoding.UTF8.GetBytes(url);
            var privateKey = Convert.FromBase64String(this.Key.Replace("-", "+").Replace("_", "/"));

            var hmac = new HMac(new Sha1Digest());

            hmac.Init(new KeyParameter(privateKey));

            var signature = new byte[hmac.GetMacSize()];

            hmac.BlockUpdate(bytes, 0, bytes.Length);
            hmac.DoFinal(signature, 0);

            var base64Signature = Convert.ToBase64String(signature).Replace("+", "-").Replace("/", "_");

            return(new Uri(uri.Scheme + "://" + uri.Host + url + "&signature=" + base64Signature));
        }
Exemplo n.º 5
0
        public static byte[] ComputeHmac(byte[] data, byte[] key, int bitLength)
        {
            IDigest digest;

            if (bitLength == 256)
            {
                digest = new Sha256Digest();
            }
            else if (bitLength == 512)
            {
                digest = new Sha512Digest();
            }
            else
            {
                throw new ArgumentException("SHA digest restricted to one of [256, 512]");
            }

            HMac hmac = new HMac(digest);

            hmac.Init(new KeyParameter(key));

            byte[] buffer = new byte[hmac.GetMacSize()];
            hmac.BlockUpdate(data, 0, data.Length);
            hmac.DoFinal(buffer, 0);
            return(buffer);
        }
Exemplo n.º 6
0
        /// <summary>
        /// See <see cref="IRequest.GetUri()"/>.
        /// </summary>
        /// <returns>The <see cref="Uri"/>.</returns>
        public virtual Uri GetUri()
        {
            const string SCHEME = "https://";

            var queryStringParameters = this.GetQueryStringParameters()
                                        .Select(x =>
                                                x.Value == null
                        ? Uri.EscapeDataString(x.Key)
                        : Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value));
            var queryString = string.Join("&", queryStringParameters);
            var uri         = new Uri($"{SCHEME}{this.BaseUrl}?{queryString}");

            if (this.ClientId == null)
            {
                return(uri);
            }

            var url        = $"{uri.LocalPath}{uri.Query}&client={this.ClientId}";
            var bytes      = Encoding.UTF8.GetBytes(url);
            var privateKey = Convert.FromBase64String(this.Key.Replace("-", "+").Replace("_", "/"));

            var hmac = new HMac(new Sha1Digest());

            hmac.Init(new KeyParameter(privateKey));

            var hmacSize  = hmac.GetMacSize();
            var signature = new byte[hmacSize];

            hmac.BlockUpdate(bytes, 0, bytes.Length);
            hmac.DoFinal(signature, 0);

            var base64Signature = Convert.ToBase64String(signature).Replace("+", "-").Replace("/", "_");

            return(new Uri($"{uri.Scheme}://{uri.Host}{url}&signature={base64Signature}"));
        }
Exemplo n.º 7
0
        internal static byte[] SignatureMethod(string secret, string source, string signatureAlgorithm)
        {
            if (signatureAlgorithm == "ACS3-HMAC-SHA256")
            {
                byte[] signData;
                using (KeyedHashAlgorithm algorithm = CryptoConfig.CreateFromName("HMACSHA256") as KeyedHashAlgorithm)
                {
                    algorithm.Key = Encoding.UTF8.GetBytes(secret);
                    signData      = algorithm.ComputeHash(Encoding.UTF8.GetBytes(source.ToSafeString().ToCharArray()));
                }
                return(signData);
            }
            else if (signatureAlgorithm == "ACS3-HMAC-SM3")
            {
                byte[] signData;
                HMac   hmacInstance = new HMac(new SM3Digest());
                hmacInstance.Init(new KeyParameter(Encoding.UTF8.GetBytes(secret)));
                signData = new byte[hmacInstance.GetMacSize()];
                var raw = Encoding.UTF8.GetBytes(source);
                hmacInstance.BlockUpdate(raw, 0, raw.Length);
                hmacInstance.DoFinal(signData, 0);

                return(signData);
            }
            else if (signatureAlgorithm == "ACS3-RSA-SHA256")
            {
                return(RSASign(source, secret));
            }
            return(null);
        }
Exemplo n.º 8
0
        public static byte[] PBKDF2(byte[] password, byte[] salt, int iterCount, int cOctets, IDigest digest)
        {
            //  PRF = HMAC- SHA (256, 384, 512)
            //  P = passsword
            //  S = salt
            //  c = iteration count
            //  dkLen = cbits in octets

            //  l = CIEL(dkLen / hLen)
            //  r = dkLen - (l - 1)*hLen

            // T_n = F ( P, S, c, n)  (iterate n=1 to l)

            // F ( P, S, c, i) = U_1 ^ U_2 ^ ... ^ U_c

            // U_1 = PRF( P, S || INT (i))
            // U_2 = PRF( P, U_1 )
            // U_c = PRF( P, U_{c-1})
            //  INT = int32- big-ending

            HMac hmac           = new HMac(digest);
            ICipherParameters k = new KeyParameter(password);

            hmac.Init(k);
            int hLen = hmac.GetMacSize();
            int l    = (cOctets + hLen - 1) / hLen;

            byte[] rgbStart = new byte[salt.Length + 4];
            Array.Copy(salt, 0, rgbStart, 0, salt.Length);
            byte[] rgbOutput = new byte[l * hLen];

            for (int i = 1; i <= l; i++)
            {
                byte[] rgbT = new byte[hLen];
                byte[] rgbH = new byte[hLen];

                hmac.Reset();
                rgbStart[rgbStart.Length - 1] = (byte)i;
                hmac.BlockUpdate(rgbStart, 0, rgbStart.Length);
                hmac.DoFinal(rgbH, 0);
                Array.Copy(rgbH, rgbT, rgbH.Length);

                for (int j = 1; j < iterCount; j++)
                {
                    hmac.Reset();
                    hmac.BlockUpdate(rgbH, 0, rgbH.Length);
                    hmac.DoFinal(rgbH, 0);
                    for (int k1 = 0; k1 < rgbH.Length; k1++)
                    {
                        rgbT[k1] ^= rgbH[k1];
                    }
                }

                Array.Copy(rgbT, hLen * (i - 1), rgbOutput, 0, rgbT.Length);
            }

            byte[] rgbOut = new Byte[cOctets];
            Array.Copy(rgbOutput, rgbOut, cOctets);
            return(rgbOut);
        }
Exemplo n.º 9
0
        public ITestResult Perform()
        {
            HMac hmac = new HMac(new RipeMD128Digest());

            byte[] resBuf = new byte[hmac.GetMacSize()];

            for (int i = 0; i < messages.Length; i++)
            {
                byte[] m = Encoding.ASCII.GetBytes(messages[i]);
                if (messages[i].StartsWith("0x"))
                {
                    m = Hex.Decode(messages[i].Substring(2));
                }
                hmac.Init(new KeyParameter(Hex.Decode(keys[i])));
                hmac.BlockUpdate(m, 0, m.Length);
                hmac.DoFinal(resBuf, 0);

                if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[i])))
                {
                    return(new SimpleTestResult(false, Name + ": Vector " + i + " failed"));
                }
            }

            return(new SimpleTestResult(true, Name + ": Okay"));
        }
Exemplo n.º 10
0
 /**
  * Calculate the mac for some given data.
  * <p/>
  * TlsMac will keep track of the sequence number internally.
  *
  * @param type    The message type of the message.
  * @param message A byte-buffer containing the message.
  * @param offset  The number of bytes to skip, before the message starts.
  * @param len     The length of the message.
  * @return A new byte-buffer containing the mac value.
  */
 internal byte[] CalculateMac(
     short type,
     byte[]  message,
     int offset,
     int len)
 {
     try
     {
         MemoryStream bosMac = new MemoryStream(13 + len);
         TlsUtilities.WriteUint64(seqNo++, bosMac);
         TlsUtilities.WriteUint8(type, bosMac);
         TlsUtilities.WriteVersion(bosMac);
         TlsUtilities.WriteUint16(len, bosMac);
         bosMac.Write(message, offset, len);
         byte[] macData = bosMac.ToArray();
         mac.BlockUpdate(macData, 0, macData.Length);
         byte[] result = new byte[mac.GetMacSize()];
         mac.DoFinal(result, 0);
         mac.Reset();
         return(result);
     }
     catch (IOException)
     {
         // This should never happen
         throw new InvalidOperationException("Internal error during mac calculation");
     }
 }
Exemplo n.º 11
0
        public byte[] ComputeHash(byte[] value)
        {
            byte[] resBuf = new byte[_hmac.GetMacSize()];
            _hmac.BlockUpdate(value, 0, value.Length);
            _hmac.DoFinal(resBuf, 0);

            return(resBuf);
        }
        public bool Verify(byte[] data, string tag)
        {
            byte[] output = new byte[_hmac.GetMacSize()];
            _hmac.Reset();
            _hmac.BlockUpdate(data, 0, data.Length);
            _hmac.DoFinal(output, 0);

            return(output.SequenceEqual(Base64.Decode(tag)));
        }
Exemplo n.º 13
0
        byte[] HashFinal()
        {
            var value = new byte[hash.GetMacSize()];

            hash.DoFinal(value, 0);
            hash.Reset();

            return(value);
        }
Exemplo n.º 14
0
 public byte[] HmacSha256(byte[] data, byte[] key)
 {
     var hmac = new HMac(new Sha256Digest());
     hmac.Init(new KeyParameter(key));
     var result = new byte[hmac.GetMacSize()];
     hmac.BlockUpdate(data, 0, data.Length);
     hmac.DoFinal(result, 0);
     return result;
 }
Exemplo n.º 15
0
            /// <summary>
            /// Create a new PBKDF2 object
            /// </summary>
            public PBKDF2(byte[] password, byte[] salt, int iterations)
            {
                m_password   = password;
                m_salt       = salt;
                m_iterations = iterations;

                m_mac  = new HMac(new Sha1Digest());
                m_hlen = m_mac.GetMacSize();
            }
Exemplo n.º 16
0
        public static string CalculateRequestHash(HMac mac, byte[] data)
        {
            mac.Init(new KeyParameter(Encoding.UTF8.GetBytes(PagarMeService.DefaultApiKey)));
            mac.BlockUpdate(data, 0, data.Length);
            byte[] result = new byte[mac.GetMacSize()];
            mac.DoFinal(result, 0);
            string hex = BitConverter.ToString(result).Replace("-", "").ToLower();

            return(hex);
        }
Exemplo n.º 17
0
 private byte[] ComputeServerSignature(byte[] authMessage)
 {
     byte[] result = new byte[m_serverSignature.GetMacSize()];
     lock (m_serverSignature)
     {
         m_serverSignature.BlockUpdate(authMessage, 0, authMessage.Length);
         m_serverSignature.DoFinal(result, 0);
     }
     return(result);
 }
Exemplo n.º 18
0
        /// <summary>
        /// HMAC-SHA256 hash
        /// </summary>
        public static byte[] HmacSha256(byte[] data, byte[] key)
        {
            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(key));
            byte[] hash = new byte[hmac.GetMacSize()];
            hmac.BlockUpdate(data, 0, data.Length);
            hmac.DoFinal(hash, 0);
            return(hash);
        }
Exemplo n.º 19
0
        internal static byte[] ComputeSHA256HMac(byte[] msg, byte[] password)
        {
            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(password));
            byte[] result = new byte[hmac.GetMacSize()];
            hmac.BlockUpdate(msg, 0, msg.Length);
            hmac.DoFinal(result, 0);
            return(result);
        }
Exemplo n.º 20
0
        public static string GenerateHMACBC(byte[] data, byte[] EK)
        {
            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(EK));
            byte[] hashMessage = new byte[hmac.GetMacSize()];
            hmac.BlockUpdate(data, 0, data.Length);
            hmac.DoFinal(hashMessage, 0);
            return(Convert.ToBase64String(hashMessage));
        }
Exemplo n.º 21
0
        /// <summary>
        ///     Calculate the current code for the authenticator.
        /// </summary>
        /// <param name="resyncTime">flag to resync time</param>
        /// <returns>authenticator code</returns>
        protected override string CalculateCode(bool resyncTime = false, long interval = -1)
        {
            // sync time if required
            if (resyncTime || ServerTimeDiff == 0)
            {
                if (interval > 0)
                {
                    ServerTimeDiff = interval * Period * 1000L - CurrentTime;
                }
                else
                {
                    Sync();
                }
            }

            var hmac = new HMac(new Sha1Digest());

            hmac.Init(new KeyParameter(SecretKey));

            var codeIntervalArray = BitConverter.GetBytes(CodeInterval);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(codeIntervalArray);
            }
            hmac.BlockUpdate(codeIntervalArray, 0, codeIntervalArray.Length);

            var mac = new byte[hmac.GetMacSize()];

            hmac.DoFinal(mac, 0);

            // the last 4 bits of the mac say where the code starts (e.g. if last 4 bit are 1100, we start at byte 12)
            var start = mac[19] & 0x0f;

            // extract those 4 bytes
            var bytes = new byte[4];

            Array.Copy(mac, start, bytes, 0, 4);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            var fullcode = BitConverter.ToUInt32(bytes, 0) & 0x7fffffff;

            // build the alphanumeric code
            var code = new StringBuilder();

            for (var i = 0; i < CODE_DIGITS; i++)
            {
                code.Append(STEAMCHARS[fullcode % STEAMCHARS.Length]);
                fullcode /= (uint)STEAMCHARS.Length;
            }

            return(code.ToString());
        }
Exemplo n.º 22
0
        public static byte[] Compute(IDigest hash, byte[] key, byte[] data, int position, int length)
        {
            data.ValidateParameters(position, length);
            HMac hmac = new HMac(hash);

            hmac.Init(new KeyParameter(key));
            byte[] result = new byte[hmac.GetMacSize()];
            hmac.BlockUpdate(data, position, length);
            hmac.DoFinal(result, 0);
            return(result);
        }
Exemplo n.º 23
0
        byte[] ComputeClientSignature(byte[] authMessage)
        {
            var result = new byte[m_clientSignature.GetMacSize()];

            lock (m_clientSignature)
            {
                m_clientSignature.BlockUpdate(authMessage, 0, authMessage.Length);
                m_clientSignature.DoFinal(result, 0);
            }
            return(result);
        }
            //Methods
            #region ComputeHash
            public Byte[] ComputeHash(Byte[] bytes)
            {
                var hmac = new HMac(new Sha256Digest());

                hmac.Init(new KeyParameter(key));
                Byte[] result = new Byte[hmac.GetMacSize()];

                hmac.BlockUpdate(bytes, 0, bytes.Length);
                hmac.DoFinal(result, 0);

                return(result);
            }
Exemplo n.º 25
0
        /// <summary>
        /// Calculate the current code for the authenticator.
        /// Trion's implementation is broken in that they don't built the signed integer correctly from the 4-byte array, so we have to override
        /// the proper method
        /// </summary>
        /// <param name="resyncTime">flag to resync time</param>
        /// <returns>authenticator code</returns>
        protected override string CalculateCode(bool resyncTime = false, long interval = -1)
        {
            // sync time if required
            if (resyncTime == true || ServerTimeDiff == 0)
            {
                if (interval > 0)
                {
                    ServerTimeDiff = (interval * 30000L) - CurrentTime;
                }
                else
                {
                    Sync();
                }
            }

            HMac hmac = new HMac(new Sha1Digest());

            hmac.Init(new KeyParameter(SecretKey));

            byte[] codeIntervalArray = BitConverter.GetBytes(CodeInterval);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(codeIntervalArray);
            }
            hmac.BlockUpdate(codeIntervalArray, 0, codeIntervalArray.Length);

            byte[] mac = new byte[hmac.GetMacSize()];
            hmac.DoFinal(mac, 0);

            // the last 4 bits of the mac say where the code starts (e.g. if last 4 bit are 1100, we start at byte 12)
            int start = mac[19] & 0x0f;

            // extract those 4 bytes
            byte[] bytes = new byte[4];
            Array.Copy(mac, start, bytes, 0, 4);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            // this is where Trion is broken and their version uses all 32bits
            //uint fullcode = BitConverter.ToUInt32(bytes, 0) & 0x7fffffff;
            uint fullcode = BitConverter.ToUInt32(bytes, 0);

            // we use the last 8 digits of this code in radix 10
            uint   codemask = (uint)Math.Pow(10, CodeDigits);
            string format   = new string('0', CodeDigits);
            string code     = (fullcode % codemask).ToString(format);

            // New glyph authenticator now uses 6, but takes the first 6 of 8 rather the proper last 6, so again we override the standard implementation
            code = code.Substring(0, 6);

            return(code);
        }
Exemplo n.º 26
0
        /// <summary>
        /// This method computes and returns the hash in bytes
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public byte[] ComputeHash(byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            byte[] resBuf = new byte[_hmac.GetMacSize()];
            _hmac.BlockUpdate(value, 0, value.Length);
            _hmac.DoFinal(resBuf, 0);

            return(resBuf);
        }
Exemplo n.º 27
0
        //void ICryptoLibrary.ProcessAesGcmBlocks(bool encryptOrDecrypt, byte[] key, byte[] iv, byte[] input, byte[] output)
        //{
        //    if (input.Length != output.Length) throw new ArgumentException();

        //    var gcmBlockCipher = new GcmBlockCipher(new AesEngine());
        //    var blockSize = CryptoLibraries.AesBlockSize;
        //    if (input.Length % blockSize != 0) throw new ArgumentException();
        //    gcmBlockCipher.Init(encryptOrDecrypt, new ParametersWithIV(new KeyParameter(key), iv));
        //    var numberOfBlocks = input.Length / blockSize;
        //    int offset = 0;
        //    for (int i = 0; i < numberOfBlocks; i++)
        //    {
        //        gcmBlockCipher.ProcessAadBytes();
        //        gcmBlockCipher.ProcessBytes();
        //        gcmBlockCipher.GetMac();


        //          //  ProcessBlock(input, offset, output, offset);
        //        offset += blockSize;
        //    }
        //}

        byte[] ICryptoLibrary.GetSha256HMAC(byte[] key, byte[] data)
        {
            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(key));
            var result = new byte[hmac.GetMacSize()];

            hmac.BlockUpdate(data, 0, data.Length);

            hmac.DoFinal(result, 0);
            return(result);
        }
Exemplo n.º 28
0
        public byte[] Hash(string text, string key)
        {
            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(Encoding.UTF8.GetBytes(key)));
            byte[] result = new byte[hmac.GetMacSize()];
            byte[] bytes  = Encoding.UTF8.GetBytes(text);

            hmac.BlockUpdate(bytes, 0, bytes.Length);
            hmac.DoFinal(result, 0);

            return(result);
        }
        public static string HmacSHA256(string s1, string key)
        {
            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(Encoding.UTF8.GetBytes(key)));
            byte[] result = new byte[hmac.GetMacSize()];
            byte[] bytes  = Encoding.UTF8.GetBytes(s1);

            hmac.BlockUpdate(bytes, 0, bytes.Length);
            hmac.DoFinal(result, 0);

            return(Base64.ToBase64String(result));
        }
Exemplo n.º 30
0
        public byte[] ComputeHash(byte[] value, int offset, int length)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            byte[] resBuf = new byte[Hmac.GetMacSize()];
            Hmac.BlockUpdate(value, offset, length);
            Hmac.DoFinal(resBuf, offset);

            return(resBuf);
        }