コード例 #1
0
        public static string HMAC(byte[] data, byte[] key)
        {
            // initialize key with zeros
            //unsigned char usedKey[HashMethod::BlockSize] = {0};
            uint numDataBytes = (uint)data.Length;
            uint numKeyBytes  = (uint)key.Length;

            byte[] usedKey = new byte[BlockSize];

            // adjust length of key: must contain exactly blockSize bytes
            if (numKeyBytes <= BlockSize)
            {
                // copy key
                //memcpy(usedKey, key, numKeyBytes);
                usedKey = key;
                Array.Resize(ref usedKey, (int)BlockSize);
            }
            else
            {
                // shorten key: usedKey = hashed(key)
                HMAC_SHA256 keyHasher = new HMAC_SHA256();
                keyHasher.add(key, numKeyBytes);
                keyHasher.getHash(usedKey);
            }

            // create initial XOR padding
            for (int i = 0; i < BlockSize; i++)
            {
                usedKey[i] ^= 0x36;
            }

            // inside = hash((usedKey ^ 0x36) + data)
            byte[]      inside       = new byte[HashBytes];
            HMAC_SHA256 insideHasher = new HMAC_SHA256();

            insideHasher.add(usedKey, BlockSize);
            insideHasher.add(data, numDataBytes);
            inside = insideHasher.getHash(inside);

            // undo usedKey's previous 0x36 XORing and apply a XOR by 0x5C
            for (int i = 0; i < BlockSize; i++)
            {
                usedKey[i] ^= 0x5C ^ 0x36;
            }

            // hash((usedKey ^ 0x5C) + hash((usedKey ^ 0x36) + data))
            HMAC_SHA256 finalHasher = new HMAC_SHA256();

            finalHasher.add(usedKey, BlockSize);
            finalHasher.add(inside, HashBytes);

            byte[] buffer = new byte[32];

            return(Convert.ToBase64String(finalHasher.getHash(buffer)));
        }
コード例 #2
0
        public static string GetSHA256(string key, string message)
        {
            return(HMAC_SHA256.HMAC(Encoding.UTF8.GetBytes(message), Encoding.UTF8.GetBytes(key)));
            //MacAlgorithmProvider sha256 = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA256");
            //IBuffer contentBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);

            //IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
            //var signatureKey = sha256.CreateKey(keyBuffer);

            //IBuffer digest = CryptographicEngine.Sign(signatureKey, contentBuffer);

            //return CryptographicBuffer.EncodeToBase64String(digest);
        }