示例#1
0
        public bool Unpack(byte[] tag, byte[] plain)
        {
            byte[] internalBytes = NtagHelpers.GetInternalTag(tag);

            // Generate keys
            KeygenDerivedkeys dataKeys = GenerateKey(this.data, internalBytes);
            KeygenDerivedkeys tagKeys  = GenerateKey(this.tag, internalBytes);

            // Decrypt
            dataKeys.Cipher(internalBytes, plain, false);

            // Init OpenSSL HMAC context
            HMac hmacCtx = new HMac(new Sha256Digest());

            // Regenerate tag HMAC. Note: order matters, data HMAC depends on tag HMAC!
            hmacCtx.Init(new KeyParameter(tagKeys.hmacKey));
            hmacCtx.BlockUpdate(plain, 0x1D4, 0x34);
            hmacCtx.DoFinal(plain, HMAC_POS_TAG);

            // Regenerate data HMAC
            hmacCtx.Init(new KeyParameter(dataKeys.hmacKey));
            hmacCtx.BlockUpdate(plain, 0x029, 0x1DF);
            hmacCtx.DoFinal(plain, HMAC_POS_DATA);

            Array.Copy(tag, 0x208, plain, 0x208, 0x014);

            return
                (NativeHelpers.MemCmp(plain, internalBytes, HMAC_POS_DATA, 32) &&
                 NativeHelpers.MemCmp(plain, internalBytes, HMAC_POS_TAG, 32));
        }
示例#2
0
            /// <summary>
            /// Calculate F.
            /// F(P,S,c,i) = U1 ^ U2 ^ ... ^ Uc
            /// Where F is an xor of c iterations of chained PRF. First iteration of PRF uses master password P as PRF key and salt concatenated to i. Second and greater PRF uses P and output of previous PRF computation:
            /// </summary>
            /// <param name="P"></param>
            /// <param name="S"></param>
            /// <param name="c"></param>
            /// <param name="i"></param>
            /// <param name="DK"></param>
            /// <param name="DKoffset"></param>
            private void F(byte[] P, byte[] S, int c, byte[] i, byte[] DK, int DKoffset)
            {
                // first iteration (ses master password P as PRF key and salt concatenated to i)
                byte[]            buf   = new byte[m_hlen];
                ICipherParameters param = new KeyParameter(P);

                m_mac.Init(param);
                m_mac.BlockUpdate(S, 0, S.Length);
                m_mac.BlockUpdate(i, 0, i.Length);
                m_mac.DoFinal(buf, 0);
                Array.Copy(buf, 0, DK, DKoffset, buf.Length);

                // remaining iterations (uses P and output of previous PRF computation)
                for (int iter = 1; iter < c; iter++)
                {
                    m_mac.Init(param);
                    m_mac.BlockUpdate(buf, 0, buf.Length);
                    m_mac.DoFinal(buf, 0);

                    for (int j = buf.Length - 1; j >= 0; j--)
                    {
                        DK[DKoffset + j] ^= buf[j];
                    }
                }
            }
示例#3
0
    public void Init(BigInteger n, BigInteger d, byte[] message)
    {
        this.n = n;
        Arrays.Fill(V, 1);
        Arrays.Fill(K, 0);
        byte[] array  = new byte[(n.BitLength + 7) / 8];
        byte[] array2 = BigIntegers.AsUnsignedByteArray(d);
        Array.Copy(array2, 0, array, array.Length - array2.Length, array2.Length);
        byte[]     array3     = new byte[(n.BitLength + 7) / 8];
        BigInteger bigInteger = BitsToInt(message);

        if (bigInteger.CompareTo(n) >= 0)
        {
            bigInteger = bigInteger.Subtract(n);
        }
        byte[] array4 = BigIntegers.AsUnsignedByteArray(bigInteger);
        Array.Copy(array4, 0, array3, array3.Length - array4.Length, array4.Length);
        hMac.Init(new KeyParameter(K));
        hMac.BlockUpdate(V, 0, V.Length);
        hMac.Update(0);
        hMac.BlockUpdate(array, 0, array.Length);
        hMac.BlockUpdate(array3, 0, array3.Length);
        hMac.DoFinal(K, 0);
        hMac.Init(new KeyParameter(K));
        hMac.BlockUpdate(V, 0, V.Length);
        hMac.DoFinal(V, 0);
        hMac.BlockUpdate(V, 0, V.Length);
        hMac.Update(1);
        hMac.BlockUpdate(array, 0, array.Length);
        hMac.BlockUpdate(array3, 0, array3.Length);
        hMac.DoFinal(K, 0);
        hMac.Init(new KeyParameter(K));
        hMac.BlockUpdate(V, 0, V.Length);
        hMac.DoFinal(V, 0);
    }
        private Byte[] StreamDecryption(Byte[] source, Byte[] data, HMac hmac, out Int32 sequenceNum)
        {
            // ciphered text consist of data and mac
            Byte[] decrypted;

            if (source.SequenceEqual(this.ClientDirection))
            {
                var d = this.DataDecrypter.DecryptData(data, WriteKeySpec.Client);

                decrypted = new Byte[d.Length];

                Array.Copy(d, decrypted, d.Length);

                var key = new KeyParameter(this.ClientHMacKey);
                hmac.Init(key);

                sequenceNum = this.DataDecrypter.ClientSeq;
            }
            else
            {
                var d = this.DataDecrypter.DecryptData(data, WriteKeySpec.Server);

                decrypted = new Byte[d.Length];

                Array.Copy(d, decrypted, d.Length);

                var key = new KeyParameter(this.ServerHMacKey);
                hmac.Init(key);

                sequenceNum = this.DataDecrypter.ServerSeq;
            }

            return(decrypted);
        }
示例#5
0
        public void Pack(byte[] plain, byte[] tag)
        {
            byte[] cipher = new byte[NtagHelpers.NFC3D_AMIIBO_SIZE];

            // Generate keys
            var tagKeys  = GenerateKey(this.tag, plain);
            var dataKeys = GenerateKey(this.data, plain);

            // Init OpenSSL HMAC context
            HMac hmacCtx = new HMac(new Sha256Digest());

            // Generate tag HMAC
            hmacCtx.Init(new KeyParameter(tagKeys.hmacKey));
            hmacCtx.BlockUpdate(plain, 0x1D4, 0x34);
            hmacCtx.DoFinal(cipher, HMAC_POS_TAG);

            // Generate data HMAC
            hmacCtx.Init(new KeyParameter(dataKeys.hmacKey));
            hmacCtx.BlockUpdate(plain, 0x029, 0x18B);          // Data
            hmacCtx.BlockUpdate(cipher, HMAC_POS_TAG, 0x20);   // Tag HMAC
            hmacCtx.BlockUpdate(plain, 0x1D4, 0x34);           // Tag
            hmacCtx.DoFinal(cipher, HMAC_POS_DATA);

            // Encrypt
            dataKeys.Cipher(plain, cipher, true);

            // Convert back to hardware
            NtagHelpers.InternalToTag(cipher, tag);

            Array.Copy(plain, 0x208, tag, 0x208, 0x014);
        }
示例#6
0
        public override void SetKey(byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            _key = (byte[])value.Clone();
            _hmac.Init(new KeyParameter(_key));
        }
        public void Init(BigInteger n, BigInteger d, byte[] message)
        {
            this.n = n;

            Arrays.Fill(V, (byte)0x01);
            Arrays.Fill(K, (byte)0);

            int size = BigIntegers.GetUnsignedByteLength(n);

            byte[] x    = new byte[size];
            byte[] dVal = BigIntegers.AsUnsignedByteArray(d);

            Array.Copy(dVal, 0, x, x.Length - dVal.Length, dVal.Length);

            byte[] m = new byte[size];

            BigInteger mInt = BitsToInt(message);

            if (mInt.CompareTo(n) >= 0)
            {
                mInt = mInt.Subtract(n);
            }

            byte[] mVal = BigIntegers.AsUnsignedByteArray(mInt);

            Array.Copy(mVal, 0, m, m.Length - mVal.Length, mVal.Length);

            hMac.Init(new KeyParameter(K));

            hMac.BlockUpdate(V, 0, V.Length);
            hMac.Update((byte)0x00);
            hMac.BlockUpdate(x, 0, x.Length);
            hMac.BlockUpdate(m, 0, m.Length);

            hMac.DoFinal(K, 0);

            hMac.Init(new KeyParameter(K));

            hMac.BlockUpdate(V, 0, V.Length);

            hMac.DoFinal(V, 0);

            hMac.BlockUpdate(V, 0, V.Length);
            hMac.Update((byte)0x01);
            hMac.BlockUpdate(x, 0, x.Length);
            hMac.BlockUpdate(m, 0, m.Length);

            hMac.DoFinal(K, 0);

            hMac.Init(new KeyParameter(K));

            hMac.BlockUpdate(V, 0, V.Length);

            hMac.DoFinal(V, 0);
        }
        private Byte[] BlockDecryption(Byte[] source, Byte[] data, HMac hmac, out Int32 sequenceNum)
        {
            // RFC 5246 in tls 1.2 ciphertext consits of
            // iv, ciphered_content { content, mac, padding, padding_length }
            // the IV length is of length
            // record_iv_length, which is equal to the
            // block_size.

            var content = new Byte[data.Length - this.DataDecrypter.IvLength];

            var iv = new Byte[this.DataDecrypter.IvLength];

            Array.Copy(data, 0, iv, 0, this.DataDecrypter.IvLength);

            Array.Copy(data, this.DataDecrypter.IvLength, content, 0, content.Length);

            Byte[] decrypted;

            if (source.SequenceEqual(this.ClientDirection))
            {
                this.DataDecrypter.SetIv(iv, WriteKeySpec.Client);
                var d = this.DataDecrypter.DecryptData(content, WriteKeySpec.Client);

                decrypted = new Byte[d.Length];

                Array.Copy(d, decrypted, d.Length);

                var key = new KeyParameter(this.ClientHMacKey);
                hmac.Init(key);

                sequenceNum = this.DataDecrypter.ClientSeq;
            }
            else
            {
                this.DataDecrypter.SetIv(iv, WriteKeySpec.Server);
                var d = this.DataDecrypter.DecryptData(content, WriteKeySpec.Server);

                decrypted = new Byte[d.Length];

                Array.Copy(d, decrypted, d.Length);

                var key = new KeyParameter(this.ServerHMacKey);
                hmac.Init(key);

                sequenceNum = this.DataDecrypter.ServerSeq;
            }

            return(decrypted);
        }
        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);
        }
示例#10
0
        /// <summary>
        /// Generate digest. The digest can be reused.
        /// </summary>
        /// <param name="parameters">Parameters.</param>
        /// <returns></returns>
        /// <exception cref="Exception"/>
        public IMac GenerateDigest(ICipherParameters parameters)
        {
            IMac digest = new HMac(_hashAlgorithm.GenerateDigest());

            digest.Init(parameters);
            return(digest);
        }
示例#11
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);
        }
示例#12
0
        /// <summary>
        ///   Creates a new instance of the <see cref="Secio1Stream"/> class.
        /// </summary>
        /// <param name="stream">
        ///   The source/destination of SECIO packets.
        /// </param>
        /// <param name="cipherName">
        ///   The cipher for the <paramref name="stream"/>, such as AES-256 or AES-128.
        /// </param>
        /// <param name="hashName">
        ///   The hash for the <paramref name="stream"/>, such as SHA256.
        /// </param>
        /// <param name="localKey">
        ///   The keys used by the local endpoint.
        /// </param>
        /// <param name="remoteKey">
        ///   The keys used by the remote endpoint.
        /// </param>
        public Secio1Stream(
            Stream stream,
            string cipherName, string hashName,
            StretchedKey localKey, StretchedKey remoteKey)
        {
            this.stream = stream;

            inHmac = new HMac(DigestUtilities.GetDigest(hashName));
            inHmac.Init(new KeyParameter(localKey.MacKey));

            outHmac = new HMac(DigestUtilities.GetDigest(hashName));
            outHmac.Init(new KeyParameter(remoteKey.MacKey));

            if (cipherName == "AES-256" || cipherName == "AES-512")
            {
                decrypt = new CtrStreamCipher(new AesEngine());
                var p = new ParametersWithIV(new KeyParameter(remoteKey.CipherKey), remoteKey.IV);
                decrypt.Init(false, p);

                encrypt = new CtrStreamCipher(new AesEngine());
                p       = new ParametersWithIV(new KeyParameter(localKey.CipherKey), localKey.IV);
                encrypt.Init(true, p);
            }
            else
            {
                throw new NotSupportedException($"Cipher '{cipherName}' is not supported.");
            }
        }
示例#13
0
        /// <summary>
        /// Gets the verifying stream.
        /// </summary>
        /// <returns></returns>
        public VerifyingStream GetVerifyingStream(KeyczarBase keyczar)
        {
            IDigest digest;

            if (Digest == DigestAlg.Sha256)
            {
                digest = new Sha256Digest();
            }
            else if (Digest == DigestAlg.Sha384)
            {
                digest = new Sha384Digest();
            }
            else if (Digest == DigestAlg.Sha512)
            {
                digest = new Sha512Digest();
            }
            else
            {
                throw new InvalidKeyTypeException($"Unsupported digest type :{Digest}");
            }

            var hmac = new HMac(digest);

            hmac.Init(new KeyParameter(HmacKeyBytes));
            return(new HmacStream(hmac, HashLength));
        }
示例#14
0
        /// <summary>
        /// Gets the verifying stream.
        /// </summary>
        /// <returns></returns>
        public VerifyingStream GetVerifyingStream(Keyczar keyczar)
        {
            var hmac = new HMac(new Sha1Digest());

            hmac.Init(new KeyParameter(HmacKeyBytes));
            return(new HmacStream(hmac));
        }
示例#15
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));
        }
示例#16
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));
        }
示例#17
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);
        }
示例#18
0
        /// <summary>
        /// Calculates the MacTag (to be used for key confirmation), as defined by
        /// <a href="http://csrc.nist.gov/publications/nistpubs/800-56A/SP800-56A_Revision1_Mar08-2007.pdf">NIST SP 800-56A Revision 1</a>,
        /// Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes.
        ///
        /// MacTag = HMAC(MacKey, MacLen, MacData)
        /// MacKey = H(K || "JPAKE_KC")
        /// MacData = "KC_1_U" || participantId || partnerParticipantId || gx1 || gx2 || gx3 || gx4
        ///
        /// Note that both participants use "KC_1_U" because the sender of the round 3 message
        /// is always the initiator for key confirmation.
        ///
        /// HMAC = {@link HMac} used with the given {@link Digest}
        /// H = The given {@link Digest}
        /// MacLen = length of MacTag
        /// </summary>
        public static BigInteger CalculateMacTag(string participantId, string partnerParticipantId,
                                                 BigInteger gx1, BigInteger gx2, BigInteger gx3, BigInteger gx4, BigInteger keyingMaterial, IDigest digest)
        {
            byte[] macKey = CalculateMacKey(keyingMaterial, digest);

            HMac mac = new HMac(digest);

            mac.Init(new KeyParameter(macKey));
            Arrays.Fill(macKey, (byte)0);

            /*
             * MacData = "KC_1_U" || participantId_Alice || participantId_Bob || gx1 || gx2 || gx3 || gx4.
             */
            UpdateMac(mac, "KC_1_U");
            UpdateMac(mac, participantId);
            UpdateMac(mac, partnerParticipantId);
            UpdateMac(mac, gx1);
            UpdateMac(mac, gx2);
            UpdateMac(mac, gx3);
            UpdateMac(mac, gx4);

            byte[] macOutput = MacUtilities.DoFinal(mac);

            return(new BigInteger(macOutput));
        }
示例#19
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"));
        }
示例#20
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}"));
        }
        public HmacSha256(byte[] key)
        {
            var sharedKey = Ensure.Type <byte[]>(key, "HmacSha256 alg expectes key to be byte[] array.");

            _hmac = new HMac(new Sha256Digest());
            _hmac.Init(new KeyParameter(sharedKey));
        }
示例#22
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);
        }
示例#23
0
        public virtual ITestResult Perform()
        {
            HMac hmac = new HMac(new Sha384Digest());

            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"));
                }
            }

            //
            // test reset
            //
            int vector = 0; // vector used for test

            byte[] m2 = Encoding.ASCII.GetBytes(messages[vector]);
            if (messages[vector].StartsWith("0x"))
            {
                m2 = Hex.Decode(messages[vector].Substring(2));
            }
            hmac.Init(new KeyParameter(Hex.Decode(keys[vector])));
            hmac.BlockUpdate(m2, 0, m2.Length);
            hmac.DoFinal(resBuf, 0);
            hmac.Reset();
            hmac.BlockUpdate(m2, 0, m2.Length);
            hmac.DoFinal(resBuf, 0);

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

            return(new SimpleTestResult(true, Name + ": Okay"));
        }
示例#24
0
        public override void PerformTest()
        {
            HMac hmac = new HMac(new NonMemoableDigest(new Sha1Digest()));

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

            for (int i = 0; i < messages.Length; i++)
            {
                byte[] m = Strings.ToByteArray(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])))
                {
                    Fail(Name + ": Vector " + i + " failed");
                }
            }

            //
            // test reset
            //
            {
                int    vector = 0; // vector used for test
                byte[] m      = Strings.ToByteArray(messages[vector]);
                if (messages[vector].StartsWith("0x"))
                {
                    m = Hex.Decode(messages[vector].Substring(2));
                }
                hmac.Init(new KeyParameter(Hex.Decode(keys[vector])));
                hmac.BlockUpdate(m, 0, m.Length);
                hmac.DoFinal(resBuf, 0);
                hmac.Reset();
                hmac.BlockUpdate(m, 0, m.Length);
                hmac.DoFinal(resBuf, 0);

                if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[vector])))
                {
                    Fail(Name + ": Reset with vector " + vector + " failed");
                }
            }
        }
示例#25
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;
 }
示例#26
0
    public static SimulatedTlsSrpIdentityManager GetRfc5054Default(Srp6GroupParameters group, byte[] seedKey)
    {
        Srp6VerifierGenerator srp6VerifierGenerator = new Srp6VerifierGenerator();

        srp6VerifierGenerator.Init(group, TlsUtilities.CreateHash(2));
        HMac hMac = new HMac(TlsUtilities.CreateHash(2));

        hMac.Init(new KeyParameter(seedKey));
        return(new SimulatedTlsSrpIdentityManager(group, srp6VerifierGenerator, hMac));
    }
示例#27
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);
        }
示例#28
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));
        }
示例#29
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);
        }
示例#30
0
        /**
         * Create a {@link SimulatedTlsSRPIdentityManager} that implements the algorithm from RFC 5054 2.5.1.3
         *
         * @param group the {@link SRP6GroupParameters} defining the group that SRP is operating in
         * @param seedKey the secret "seed key" referred to in RFC 5054 2.5.1.3
         * @return an instance of {@link SimulatedTlsSRPIdentityManager}
         */
        public static SimulatedTlsSrpIdentityManager GetRfc5054Default(Srp6GroupParameters group, byte[] seedKey)
        {
            Srp6VerifierGenerator verifierGenerator = new Srp6VerifierGenerator();
            verifierGenerator.Init(group, TlsUtilities.CreateHash(HashAlgorithm.sha1));

            HMac mac = new HMac(TlsUtilities.CreateHash(HashAlgorithm.sha1));
            mac.Init(new KeyParameter(seedKey));

            return new SimulatedTlsSrpIdentityManager(group, verifierGenerator, mac);
        }